2017-02-21 177 views
-1
var cityMap = new google.maps.Map(document.getElementById('cityMap'), { 
    zoom: 12, 
}); 
var infowindow = new google.maps.InfoWindow(); 
var services = document.getElementsByClassName('s__item'); 
var marker; 
var geocoderCity = new google.maps.Geocoder(); 

for (i=0; i < services.length; i++) { 
    var address = $(services[i]).find('.s__item__address_at').text(); 
    var contentString = address; 

    geocoderCity.geocode({'address': address}, function (results, status) { 
    if (status === google.maps.GeocoderStatus.OK) { 
     center = results[0].geometry.location; 
     cityMap.setCenter(results[0].geometry.location); 

     marker = new google.maps.Marker({ 
      map: cityMap, 
      position: center,     
     }); 

     google.maps.event.addListener(marker, 'click', (function(marker) { 
      return function() { 
       infowindow.setContent(contentString); 
       infowindow.open(cityMap, marker); 
      } 
     })(marker)); 
    } 
}); 
} 

s__item__address_at塊中有一個地址。我使用地理編碼器獲取位置。然後我嘗試在地圖上添加infowindows,但是我只獲得迭代的最後結果。我該如何解決它?谷歌地圖api。多個標記

jsfiddle

回答

0

你可以使用一個clousure爲使現有的VAR實例聽者

function markerListener(aMap, aMarker, aContent){ 
      google.maps.event.addListener(marker, 'click', (function(marker) { 
       return function() { 
       infowindow.setContent(aContent); 
       infowindow.open(aMap, aMarker); 
       } 
      }); 
    } 

    var cityMap = new google.maps.Map(document.getElementById('cityMap'), { 
    zoom: 12, 
    }); 
    var infowindow = new google.maps.InfoWindow(); 
    var services = document.getElementsByClassName('s__item'); 
    var marker; 
    var geocoderCity = new google.maps.Geocoder(); 



    for (i=0; i < services.length; i++) { 
     var address = $(services[i]).find('.s__item__address_at').text(); 
     var contentString = address; 

     geocoderCity.geocode({'address': address}, function (results, status) { 
     if (status === google.maps.GeocoderStatus.OK) { 
      center = results[0].geometry.location; 
      cityMap.setCenter(results[0].geometry.location); 

      marker = new google.maps.Marker({ 
       map: cityMap, 
       position: center,     
      }); 

      markerListener(cityMap, marker, contentString) 
     } 
    }); 

}