反向地理编码器返回未定义 [英] Reverse Geocoder Returning undefined

查看:91
本文介绍了反向地理编码器返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我使用谷歌的反向地理编码器,所以我最初做的是输入一个地址,如东京,然后我得到latlng latlng并将其放回地理编码器以接收位置的专有名称,但相反,它只是返回undefined。我的代码是:

  var geocoder = new google.maps.Geocoder(); 
var place = document.getElementById(location)。value;
var name;
var place_latlng;
geocoder.geocode({'address':place},function(results,status){
if(status == google.maps.GeocoderStatus.OK){
place_latlng = results [0 ] .geometry.location;
addMarker(place_latlng);
}
});
geocoder.geocode({'latLng':place_latlng},function(results,status){
if(status == google.maps.GeocoderStatus.OK){
name = results [0 ] .formatted_address;
}
});

名字每次都会被定义为undefined,有没有办法解决这个问题?

解决方案

Geocoder是异步的,您需要使用Geocoder在其回调函数(未测试)中返回的数据:

  geocoder.geocode({'address':place},function(results,status){
if(status == google.maps .GeocoderStatus.OK){
place_latlng = results [0] .geometry.location;
addMarker(place_latlng);
geocoder.geocode({'latLng':place_latlng},function(results,状态){
if(status == google.maps.GeocoderStatus.OK){
name = results [0] .formatted_address;
alert(name =+ name);
} else {alert(反向地理编码为+ place_latlng +失败(+ status +));}
});
} else {alert(geocode of+ place +failed (+ status +));}
});

示例


So, I am using google's reverse geocoder, so what I originally do is enter an address such as, tokyo, then I get that latlng take the latlng and place it back into the geocoder to receive the proper name of the location but instead it just returns undefined. My code is:

var geocoder = new google.maps.Geocoder();
var place = document.getElementById("location").value;
var name;
var place_latlng;
geocoder.geocode({'address' : place}, function(results, status){
  if (status == google.maps.GeocoderStatus.OK){
    place_latlng = results[0].geometry.location;
    addMarker(place_latlng);
  }
});
geocoder.geocode({'latLng' : place_latlng},function(results, status){
  if (status == google.maps.GeocoderStatus.OK){
    name = results[0].formatted_address;
  }
});

name ends up being undefined every time, is there a way I can fix this?

解决方案

The Geocoder is asynchronous, you need to use the data returned by the Geocoder inside its callback function (not tested):

geocoder.geocode({'address' : place}, function(results, status){
  if (status == google.maps.GeocoderStatus.OK){
    place_latlng = results[0].geometry.location;
    addMarker(place_latlng);
    geocoder.geocode({'latLng' : place_latlng},function(results, status){
      if (status == google.maps.GeocoderStatus.OK){
        name = results[0].formatted_address;
        alert("name = "+name);
      } else { alert("reverse geocode of "+place_latlng+ " failed ("+status+")"); }
    });
  } else { alert("geocode of "+place+" failed ("+status+")"); }
});

Example

这篇关于反向地理编码器返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆