我正在尝试使用带地理编码的JSON显示多个标记。我的代码在正确的位置显示所有标记,但不显示正确的Infowindow或正确的标题。我知道它与闭包有关。但我不明白。请帮助我并善意编辑我的代码并解释为什么需要编辑它? 请帮助!!
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);
}
});
}
});
答案 0 :(得分:1)
答案如下:
我需要的是在循环外调用添加标记功能。感谢您对我的问题的所有考虑。希望我的解决方案能帮助别人。
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);
infoWindow = new google.maps.InfoWindow();
for (var i = 0; i < points.length; i++) {
var myLoc = points[i];
var geoOptions = {
address: myLoc[1] + "," + myLoc[2] + "," + myLoc[3] + "," + myLoc[4] + "," + myLoc[5]
}
geocoder.geocode(geoOptions, addMarkers(myLoc[6]));
}
function addMarkers(myTitle) {
return function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: myTitle,
zIndex: i
});
(function (marker, myTitle) {
// Attaching a click event to the current marker
//console.log(data[6]);
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(myTitle);
infoWindow.open(map, marker);
});
})(marker, myTitle);
}
};
}
答案 1 :(得分:0)
这是因为您始终将内容设置为数据[6] +数据[0]。
在迭代标记时,需要为每次迭代更改信息窗口的内容。
infoWindow.setContent(data[i] + " " + data[i]);
像上面这样的东西应该可以解决问题,但我不知道你想要什么数据。 HTH
...您在标题区域始终将其设置为标题[4]
时遇到同样的问题