Google maps and knockoutjs

前端 未结 4 1732
攒了一身酷
攒了一身酷 2021-02-02 03:43

I am making a single page app where in the second view I need to display the Google map. I am using the Google maps API where the map object is to be created.

          


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-02 03:52

    You should use a custom binding like so:

    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 would look like this:

    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 does a bit more than what you are asking but should work fine for your case as well.

提交回复
热议问题