[英]geocode reverse callback function not called
我是Java的新手。 我正在嘗試使用Google api的Gmap v3來實現反向地理編碼。 我已經閱讀了許多教程,並編寫了一個簡單的代碼。 問題在於,傳遞給geocoder.geocode()的匿名函數有時有效,但有時無效。 謝謝你的幫助!。
function geoCode(latStr,lngStr){
var lat = parseFloat(latStr);
var lng = parseFloat(lngStr);
var latlng = new google.maps.LatLng(lat, lng);
codeLatLng(latlng,function(addr){
alert(addr); // sometimes message appears.
});
}
function codeLatLng(latlng,callback) {
if (geocoder) {
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
callback(results[1].formatted_address);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
}
我不確定Google服務是否會返回null
或空數組,但是為了安全起見,您可以使用以下兩種方法進行檢查: if (results && results.length > )
。 另外,您是否忘記了Javascript中的數組是從零開始的? 您可能想要results[0]
:
if (results && results.length > 0) {
callback(results[0].formatted_address);
} else {
alert("No results found");
}
通過解釋的方式: if (results[1])
“結果”是長度為0或1的數組, if (results[1])
代碼if (results[1])
崩潰,因此我猜測是間歇性失敗。
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng' : position
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
address = results[1].formatted_address;
// alert("Wow ! Got it");
} else {
// alert("No results
// found");
infowindow.setContent("No address found");
}
} else {
// alert("Geocoder failed due
// to: " + status);
infowindow.setContent("Geocoder failed due to: " + status);
}
infowindow.setContent(address + '<br/>' + Timestamp);
});
infowindow.open(marker.get('map'), marker, this);
currentInfoWindow = infowindow;
});
}
一次嘗試使用上面的代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.