Google Maps V3 geocoding and markers in loop

前端 未结 2 801
挽巷
挽巷 2021-01-06 07:32

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

相关标签:
2条回答
  • 2021-01-06 08:12

    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.

    0 讨论(0)
  • 2021-01-06 08:19

    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
        }
    
    0 讨论(0)
提交回复
热议问题