IkeDoud
IkeDoud

Reputation: 87

Knockout Object Literals not working with Google Maps?

So I've got a small maps project I'm working on, has worked great until I decided to bring KnockoutJS into the mix for handling a few things. I've defined my markers via an observable array for ease of display in the front end. But, if I try to call it to place markers in my map, I don't get any markers displayed. If I remove the lat/lng object literals in the code below (but keep the numbers as part of the array) and just call them via

markers()[i][1] 

and

markers()[i][2]

respectively, I get the markers. Halp! I've poured over the knockout docs and haven't found any info on this. Not throwing any console errors either - just don't have any markers on the map. Greatly appreciate any help!

var markers = ko.observableArray([
   [{ Name: 'Eye On Entrepreneurs' }, { lat: 45.913750 }, { lng: -89.257755 }],
   [{ Name: 'Trigs of Eagle River' }, { lat: 45.915717 }, { lng: -89.240019 }],
   [{ Name: 'Eagle River Airport' }, { lat: 45.934099 }, { lng: -89.261834 }]
]);

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 45.917034, lng: -89.248168},
    zoom: 15,
    disableDefaultUI: true
  });

  for (i = 0; i < markers().length; i++){
    var position = new google.maps.LatLng(markers()[i].lat, markers()[i].lng);
    marker = new google.maps.Marker({
       position: position,
       map: map,
       title: markers()[i].name
    });
  }
}

Upvotes: 1

Views: 62

Answers (1)

Ray
Ray

Reputation: 3959

I'm currently working with KnockoutJS and OracleJET in my office.

Although it isn't incorrect, I haven't seen a use case till now where an observableArray has more arrays inside it. We simply place objects inside the parent observableArray. I modified your code like this:

this.markers = ko.observableArray([
                {Name: 'Eye On Entrepreneurs', lat: 45.913750, lng: -89.257755},
                {Name: 'Trigs of Eagle River', lat: 45.915717, lng: -89.240019},
                {Name: 'Eagle River Airport', lat: 45.934099, lng: -89.261834}
            ]);

It works fine.

And you have a typo: capitalize 'n' of name. title: self.markers()[i].Name

Upvotes: 2

Related Questions