You should use custom binding, for example:
ko.bindingHandlers.map = { init: function (element, valueAccessor, allBindingsAccessor, viewModel) { var mapObj = ko.utils.unwrapObservable(valueAccessor()); var latLng = new google.maps.LatLng( ko.utils.unwrapObservable(mapObj.lat), ko.utils.unwrapObservable(mapObj.lng)); var mapOptions = { center: latLng, zoom: 5, mapTypeId: google.maps.MapTypeId.ROADMAP}; mapObj.googleMap = new google.maps.Map(element, mapOptions); } };
Your HTML will look like this:
<div id="mapDiv" data-bind="style:{width:'300px',height:'300px'},map:myMap"></div>
Finally, your view model:
function MyViewModel() { var self = this; self.myMap = ko.observable({ lat: ko.observable(55), lng: ko.observable(11)}); }
Here is a fiddle that is slightly larger than what you ask, but should work just fine for your case as well.
schmidlop
source share