Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google maps and knockoutjs

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.

 var map = new google.maps.Map(mapId, {
        zoom: 5,
        center: new google.maps.LatLng(55, 11),
        mapTypeId: google.maps.MapTypeId.ROADMAP
 });

The parameter mapId is giving me a problem. The view contains a div with id say "mapId", but I am not able to get the id and so the map cannot be displayed. I tried HTML binding, attribute binding but it does not work. I am new to knockout. Please suggest some method

like image 567
Empty Avatar asked Oct 04 '12 08:10

Empty


People also ask

What is KnockoutJS used for?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.

What is knockout language?

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.


2 Answers

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:

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

like image 150
schmidlop Avatar answered Dec 19 '22 10:12

schmidlop


Here's a good example of using Knockout JS and Google Maps. Hopefully, it will help get you on the right track. http://www.codeproject.com/Articles/387626/BikeInCity-2-KnockoutJS-JQuery-Google-Maps

like image 20
AlignedDev Avatar answered Dec 19 '22 09:12

AlignedDev