我有下面显示的代码,它在 GoogleMap 上显示 3 个标记,位置数据位于 JSON 对象中。
标记显示正确,但侦听器 (addListener) 仅在最后一个标记上工作,而不是在前 2 个标记上工作。我的代码有什么问题?
我看了很多例子,就是看不出来。:( 谢谢你的帮助!
(function() {
window.onload = function() {
// Creating a map
var options = {
zoom: 3,
center: new google.maps.LatLng(37.09, -95.71),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), options);
// Creating a JSON object with weather data
var weatherData = {'weather': [
{
'lat': 40.756054,
'lng': -73.986951
},
{
'lat': 47.620973,
'lng': -122.347276
},
{
'lat': 37.775206,
'lng': -122.419209
}
]};
var infoWindow = new google.maps.InfoWindow({
content: 'Hello world'
});
// Looping through the weather array in weatherData
for (var i = 0; i < weatherData.weather.length; i++) {
// creating a variable that will hold the current weather object
var weather = weatherData.weather[i];
// Creating marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(weather.lat, weather.lng),
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.open(map, marker);
});
}
}
})();