Google Maps V3 geocoding and markers in loop

2019-02-14 20:11发布

问题:

I have some problems with my code, I have a list of airports in a sql database, and I want to create markers for each 1 of those airports.

For the address i got ICAO-codes for each airport, an ICAO is unique for each airport

I get the data from the Database as array

it's is saved in "temp" with an split function and with the for-loop it get them 1 by 1

Geocoding is not the problem, but I don't know why for the TITLE and the on click event it is always the last one from the array which is used.

here is the page, the last entry in the database is ZBAA.

And all the markers are placed at the correct location but the title is wrong :s

http://mizar.lte.lu/~pr1011_meteo/projet/cartemonde4.php

The problem is with "address" i think but i m not sure.

for (var i = 0; i < temp.length; ++i){

     var address=temp[i];

     geocoder.geocode({ 'address': address}, function(results){            
          var marker  = new google.maps.Marker({
              map: map, 
              position: results[0].geometry.location,
              title:address
          });

          google.maps.event.addListener(marker, 'click', function() {
               window.open ('infomonde.php?icao='+address+'&language=fr', 'Informations météo', config='height=400, width=850, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no')});
     });  
};

回答1:

Here is a JSFiddle Demo using "dummy" addresses and alert to show the correct data associate with each marker:

What you have is a typical closure/scope issue within the for loop. To fix the issue use closure to localize the temp[i] variable before passing into geocode and callback function within it:

    for (var i = 0; i < temp.length; ++i) {
        (function(address) {
            geocoder.geocode({
                'address': address
            }, function(results) {
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    title: address
                });

                google.maps.event.addListener(marker, 'click', function() {
                    //alert(address);  //use alert to debug address
                    window.open('infomonde.php?icao=' + address + '&language=fr', 'Informations météo', config = 'height=400, width=850, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no')
                });
            });
        })(temp[i]);  //closure passing in temp[i] and use address within the closure
    }


回答2:

my guess is because

geocoder.geocode({ 'address': address}, function(results){ ... });

callback is execute in same context.

try execute marker in same context. the code below is will wait for all geocoder fetched. then parse to marker.

var results = {};
var waiting = temp.length;

while(temp.length > 0){

  var fetching = temp.pop();

  geocoder.geocode(
    { address: fetching}, 
    function(response){
      results[fetching] = response[0].geometry.location;
      --waiting;
      if(waiting == 0) // wait for everything to finish
        setMarker();
    }
  );
}
var setMarker = function(){
  for(var element in results){
    var marker  = new google.maps.Marker({
              map: map, 
              position: results[element],
              title: element
              });

    google.maps.event.addListener(marker, 'click', function() {
    window.open ('infomonde.php?icao='+element+'&language=fr', '', 'configs')});
  }
}

ps window.open if i'm not mistaken, some browser reject popup title(and might cause unable to open popup). i alway leave blank.