【发布时间】:2014-04-24 00:00:18
【问题描述】:
我正在研究 Google Maps API v3 javascript。我正在使用地理编码器功能,我在其中传递城市名称并将其绘制在地图上。除了这个标记,我想为每个标记添加一个单独的信息窗口,但我不能这样做。所有信息窗口都显示为最后一个标记设置的内容,而不是为每个设置不同的信息窗口。请在下面找到 javascript 代码:
function initialize() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById('address').value;
var jString = JSON.parse(address);
var infowindow;
for (var key in jString) {
contentStr = JSON.stringify(jString[key]); //This is step where I am setting the content which is independent for every maker
if (jString.hasOwnProperty(key)) {
geocoder.geocode( { 'address': key}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
infowindow = new google.maps.InfoWindow({
content: contentStr//Not able to access 'contentStr' set above.
});
infowindow.open(map,marker);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
调试后我了解到,由于某种原因,在“for”循环的最后一次迭代期间设置的变量“contentStr”的值仅用于以下所有函数调用:
geocoder.geocode( { 'address': key}, function(results, status) {
所以基本上,我无法将变量“contentStr”传递给另一个函数的参数中定义的函数。我想我在这里缺少一些基本的东西。有人可以指导我吗?
谢谢!
【问题讨论】:
-
关闭。然而循环并不是那么简单:
-
这正是我想要的。对不起,重复的家伙。我是 JavaScript 新手,我不知道闭包概念。谢谢! :)
标签: javascript google-maps google-maps-api-3