Javascript 未调用地理代码反向回调函数
我是Javascript新手。我正试图使用谷歌api的GMAPv3实现一个反向地理编码。我已经阅读了很多教程,并编写了一个简单的代码。问题是传递给geocoder.geocode()的匿名函数有时有效,但有时无效。谢谢你的帮助Javascript 未调用地理代码反向回调函数,javascript,google-maps,google-maps-api-3,Javascript,Google Maps,Google Maps Api 3,我是Javascript新手。我正试图使用谷歌api的GMAPv3实现一个反向地理编码。我已经阅读了很多教程,并编写了一个简单的代码。问题是传递给geocoder.geocode()的匿名函数有时有效,但有时无效。谢谢你的帮助 function geoCode(latStr,lngStr){ var lat = parseFloat(latStr); var lng = parseFloat(lngStr); var latlng = new go
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中的数组是基于零的?您可能需要结果[0]
:
if (results && results.length > 0) {
callback(results[0].formatted_address);
} else {
alert("No results found");
}
解释一下:如果(results[1]),如果“results”是长度为0或1的数组,那么您的代码将在上崩溃,因此我猜测是间歇性故障。var geocoder=new google.maps.geocoder();
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;
});
}
地理编码({
“latLng”:位置
},功能(结果、状态){
if(status==google.maps.GeocoderStatus.OK){
如果(结果[1]){
地址=结果[1]。格式化的\u地址;
//警惕(“哇!明白了”);
}否则{
//警报(“无结果
//发现“);
infowindow.setContent(“未找到地址”);
}
}否则{
//警报(“由于以下原因,地理编码器失败
//至:“+地位);
infowindow.setContent(“地理编码器因“+状态”而失败);
}
infowindow.setContent(地址+'
'+时间戳);
});
打开(marker.get('map'),marker,this);
currentInfoWindow=infowindow;
});
}
尝试使用上述代码后您所说的“有时有效,有时无效”是什么意思?发生这种情况时,您在哪里使用它?你收到其他警报了吗?我是说,我没有收到任何其他警报。。。匿名函数有时不调用。它的信息窗口是什么?我没有使用谷歌地图来显示地图。我用的是OpenLayers,我只想用谷歌做反向地理编码。谢谢你的帮助。你是对的,是零基的。我根据一个例子来编写它,这个例子没有结果[1]。我将尝试使用[0]。。。谢谢