Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through Markers with Google Maps API v3 Problem

I'm not sure why this isn't working. I don't have any errors, but what happens is, no matter what marker I click on, it always clicks the last marker. Im not sure why though because the_marker is set up the same way. How can I fix this?:

(Updated with new jQuery + XML)

$(function(){
    var latlng = new google.maps.LatLng(45.522015,-122.683811);
    var settings = {
        zoom: 15,
        center: latlng,
        disableDefaultUI:true,
        mapTypeId: google.maps.MapTypeId.SATELLITE
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), settings);

    $.get('mapdata.xml',{},function(xml){
        $('location',xml).each(function(i){
            the_marker = new google.maps.Marker({
                title:$(this).find('name').text(),
                map:map,
                clickable:true,
                position:new google.maps.LatLng(
                    parseFloat($(this).find('lat').text()),
                    parseFloat($(this).find('lng').text())
                )
            });
            infowindow = new google.maps.InfoWindow({
                content: $(this).find('description').text()
            });
            new google.maps.event.addListener(the_marker, 'click', function() {
                infowindow.open(map,the_marker);
            });
        });
    });
});
like image 396
Oscar Godson Avatar asked Apr 19 '10 19:04

Oscar Godson


People also ask

What causes Google Maps JavaScript API v3 to not work properly?

"This site overrides Array. from() with an implementation that doesn't support iterables, which could cause Google Maps JavaScript API v3 to not work correctly."

How many markers can Google Maps API handle?

2048 characters in URL is just under 100 GeoCode values. So, again no more than 100 markers.

How do I add multiple markers to Google Maps API?

You just need this code: var marker = new google. maps. Marker({ position: new google.


2 Answers

You are having a very common closure problem in the following loop:

for(x in locations){
   console.log(x);
   infowindow[x] = new google.maps.InfoWindow({content: x});
   marker[x] = new google.maps.Marker({title:locations[x][0],map:map,position:locations[x][2]});
   google.maps.event.addListener(marker[x], 'click', function() {infowindow[x].open(map,marker[x]);});
}

Variables enclosed in a closure share the same single environment, so by the time the click callbacks are executed, the loop has run its course and the x variable will be left pointing to the last entry.

You can solve it with even more closures, using a function factory:

function makeInfoWindowEvent(map, infowindow, marker) {  
   return function() {  
      infowindow.open(map, marker);
   };  
} 

for(x in locations){
   infowindow[x] = new google.maps.InfoWindow({content: x});

   marker[x] = new google.maps.Marker({title: locations[x][0],
                                       map: map, 
                                       position: locations[x][3]});

   google.maps.event.addListener(marker[x], 'click', 
                                 makeInfoWindowEvent(map, infowindow[x], marker[x]);
}

This can be quite a tricky topic, if you are not familiar with how closures work. You may to check out the following Mozilla article for a brief introduction:

  • Working with Closures

UPDATE:

Further to the updated question, you should consider the following:

  • First of all, keep in mind that JavaScript does not have block scope. Only functions have scope.

  • When you assign a variable that was not previously declared with the var keyword, it will be declared as a global variable. This is often considered an ugly feature (or flaw) of JavaScript, as it can silently hide many bugs. Therefore this should be avoided. You have two instances of these implied global variables: the_marker and infowindow, and in fact, this is why your program is failing.

  • JavaScript has closures. This means that inner functions have access to the variables and parameters of the outer function. This is why you will be able to access the_marker, infowindow and map from the callback function of the addListener method. However, because your the_marker and infowindow are being treated as global variables, the closure is not working.

All you need to do is to use the var keyword when you declare them, as in the following example:

$(function() {
   var latlng = new google.maps.LatLng(45.522015,-122.683811);

   var settings = {
      zoom: 15,
      center: latlng,
      disableDefaultUI: true,
      mapTypeId: google.maps.MapTypeId.SATELLITE
   };

   var map = new google.maps.Map(document.getElementById("map_canvas"), settings);

   $.get('mapdata.xml', {}, function(xml) {
      $('location', xml).each(function(i) {

         var the_marker = new google.maps.Marker({
            title: $(this).find('name').text(),
            map: map,
            clickable: true,
            position: new google.maps.LatLng(
               parseFloat($(this).find('lat').text()),
               parseFloat($(this).find('lng').text())
            )
         });

         var infowindow = new google.maps.InfoWindow({
            content: $(this).find('description').text();
         });

         new google.maps.event.addListener(the_marker, 'click', function() {
            infowindow.open(map, the_marker);
         });
      });
   });
});
like image 86
Daniel Vassallo Avatar answered Oct 07 '22 17:10

Daniel Vassallo


Here is my approach.

for(x in locations){
    var name = locations[x][0];
    var latlng = locations[x][3];
    addMarker(map, name, latlng);
}

function addMarker(map, name, latlng){
    var infoWin = new google.maps.InfoWindow({content: name});
    var marker = new google.maps.Marker({
        map: map,
        position: latlng,
        title: name
    });
    google.maps.event.addListener(marker, 'click', function(){
        infoWin.open(map, marker);
    });
}
like image 44
Joe Cheng Avatar answered Oct 07 '22 17:10

Joe Cheng