use*_*848 4 javascript closures google-maps geocoding google-maps-api-3
我的代码有一些问题,我在sql数据库中有一个机场列表,我想为这些机场中的每一个创建标记.
对于我获得每个机场的ICAO代码的地址,国际民航组织对每个机场都是独一无二的
我从数据库中获取数据作为数组
它被保存在带有分割功能的"temp"中,而for循环则将它们逐个1地保存
地理编码不是问题,但我不知道为什么TITLE和on click事件始终是使用的数组中的最后一个.
这是页面,数据库中的最后一个条目是ZBAA.
并且所有标记都放在正确的位置,但标题是错误的:s
http://mizar.lte.lu/~pr1011_meteo/projet/cartemonde4.php
我认为问题是"地址",但我不确定.
for (var i = 0; i < temp.length; ++i){
var address=temp[i];
geocoder.geocode({ 'address': address}, function(results){
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title:address
});
google.maps.event.addListener(marker, 'click', function() {
window.open ('infomonde.php?icao='+address+'&language=fr', 'Informations météo', config='height=400, width=850, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no')});
});
};
Run Code Online (Sandbox Code Playgroud)
KJY*_*葉家仁 10
这是一个使用"虚拟"地址和警报的JSFiddle演示,以显示与每个标记关联的正确数据:
你有什么是for循环中典型的闭包/范围问题.要解决此问题,请temp[i]在传递到地理编码和回调函数之前使用闭包来本地化变量:
for (var i = 0; i < temp.length; ++i) {
(function(address) {
geocoder.geocode({
'address': address
}, function(results) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: address
});
google.maps.event.addListener(marker, 'click', function() {
//alert(address); //use alert to debug address
window.open('infomonde.php?icao=' + address + '&language=fr', 'Informations météo', config = 'height=400, width=850, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no')
});
});
})(temp[i]); //closure passing in temp[i] and use address within the closure
}
Run Code Online (Sandbox Code Playgroud)