我想爲Google地圖添加不同顏色的標記;如果地址是出租屋(「Y」),並且地址屬於私人廣告客戶(「N」),則添加紅色標記。我認爲這可以很容易地通過IF條件來完成,但不知何故它不起作用,我無法找出解決方案。 if (usertypes[x]=="Y") {}
未被識別,因此它會自動跳轉到else {}
,這就是爲什麼現在結果始終爲藍色。添加Google地圖標記 - JavaScript'IF'在'FOR'循環中不起作用
代碼:
var addresses = ['address1', 'address2', 'address3', 'address4', 'address5'];
var usertypes = ['Y', 'N', 'Y', 'Y', 'N'];
var bounds = new google.maps.LatLngBounds();
// the loop:
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address=' + addresses[x] + '&sensor=false', null, function(data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
// set red marker if the advertiser is a private user:
if (usertypes[x] == "Y") {
new google.maps.Marker({
position: latlng,
map: map,
icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png',
title: 'item position'
});
bounds.extend(latlng);
// set blue marker if it is a rental house:
} else {
new google.maps.Marker({
position: latlng,
map: map,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
title: 'item position'
});
bounds.extend(latlng);
}
});
}
map.fitBounds(bounds);
感謝您的幫助:)
你有沒有看過'usertypes [x]'?你能確認它是否有「Y」的確切值?我很確定'如果'陳述不會突然停止正常工作。 –
是的,在控制檯中它爲我提供了正確的值 –
然後它可能有一個或多個空間。另外,'$ .getJSON'完成時'x'不會是正確的值。 [閱讀這個問題,找出原因。](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) –