Google Maps V3 geocoding and markers in loop

前端 未结 2 800
挽巷
挽巷 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.

提交回复
热议问题