Amir Amir - 2 months ago 14
Javascript Question

Adding multiple markers from external json to Google Map in Javascript

I receive json data from a server and need to add them to a google map. It works fine, however, I only see one marker and I assume every time I add a marker it changes it to new coordinates and doesnt add an extra marker. How can I define markers as an array?

$.getJSON(url, function(data) {

var entry = data.feed.entry;


$(entry).each(function(){
for (var prop in this["gsx$instruments"]) {
//alert(this["gsx$instruments"][prop]);
listContacts(this["gsx$instruments"][prop])
var myLatLng = {lat: Number(this["gsx$ycor"][prop]), lng: Number(this["gsx$xcor"][prop])};

var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 13,
center: myLatLng
});

var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: this["gsx$instruments"][prop]
});

}
// Column names are name, age, etc.
//$('.results').prepend('<h2>'+this.gsx$instruments.$t+'</h2><p>'+this.gsx$type.$t+'</p>');
});

});

Answer

Add a new function addMarker and use that function to include markers also keep the map variable outside the ajax call as well. updated code below

var map = new google.maps.Map(document.getElementById('googleMap'), {
          zoom: 13,
          center: {lat: LAT, lng: LONG}
        });
function addMarker(position, map, title){
      var marker = new google.maps.Marker({
      position: position,
      map: map,
      title: title
    });
}

$.getJSON(url, function(data) {

var entry = data.feed.entry;


$(entry).each(function(){
   for (var prop in this["gsx$instruments"]) {
    //alert(this["gsx$instruments"][prop]);
    listContacts(this["gsx$instruments"][prop])
        var myLatLng = {lat: Number(this["gsx$ycor"][prop]), lng: Number(this["gsx$xcor"][prop])};

        addMarker(myLatLng,map,this["gsx$instruments"][prop]);

   }
  // Column names are name, age, etc.
  //$('.results').prepend('<h2>'+this.gsx$instruments.$t+'</h2><p>'+this.gsx$type.$t+'</p>');
});

});
Comments