[英]Google Maps V3 geocoding and markers in loop
我的代碼有一些問題,我在sql數據庫中有一個機場列表,我想為每個機場中的1個創建標記。
對於我獲得每個機場的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')});
});
};
這是一個使用“虛擬”地址和警報的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
}
我的猜測是因為
geocoder.geocode({ 'address': address}, function(results){ ... });
回調是在相同的上下文中執行的。
嘗試在相同的上下文中執行標記 下面的代碼將等待獲取的所有地理編碼器。 然后解析為標記。
var results = {};
var waiting = temp.length;
while(temp.length > 0){
var fetching = temp.pop();
geocoder.geocode(
{ address: fetching},
function(response){
results[fetching] = response[0].geometry.location;
--waiting;
if(waiting == 0) // wait for everything to finish
setMarker();
}
);
}
var setMarker = function(){
for(var element in results){
var marker = new google.maps.Marker({
map: map,
position: results[element],
title: element
});
google.maps.event.addListener(marker, 'click', function() {
window.open ('infomonde.php?icao='+element+'&language=fr', '', 'configs')});
}
}
ps window.open如果我沒有弄錯,有些瀏覽器會拒絕彈出標題(並且可能導致無法打開彈出窗口)。 我總是留空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.