我正在尝试使用带有地理编码的 JSON 显示多个标记。我的代码在正确的位置显示所有标记,但没有在它们上显示正确的信息窗口或正确的标题。我知道这与闭包有关。但我不明白。请帮我编辑我的代码并解释为什么需要编辑它?请帮忙!!
points = data.POINTS;
var geocoder;
//var map;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(41.2324, - 98.4160);
var mapOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
for (var i = 0, length = points.length; i < length; i++) {
data = points[i],
address = data[1] + ", " + data[2] + ", " + data[3] + ", " + data[4] + ", " + data[5];
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
//Creating a marker and putting it on the map
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: data[4],
animation: google.maps.Animation.DROP
});
// Creating a closure to retain the correct data, notice how I pass the current data in the loop into the closure (marker, data)
(function (marker, points) {
// Attaching a click event to the current marker
//console.log(data[6]);
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data[6] + " " + data[0]);
infoWindow.open(map, marker);
});
})(marker, data);
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}
});