我正在使用Google Maps API地理编码器尝试从地址获取lat / lng。
这是我的代码:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function geocodeAddress(address) {
geocoder.geocode({address:address}, function (results,status){
if (status == google.maps.GeocoderStatus.OK) {
var p = results[0].geometry.location;
var lat=p.lat();
var lng=p.lng();
var location = '{'+lat+','+lng+'}';
// If I alert(location) here, I get the correct lat/lng
return location;
// The return isn't happening?
} else {
alert('GeoCoder problem');
}
});
}
var geocoder = new google.maps.Geocoder();
var point = geocodeAddress('Cape Town Carnival, Somerset Road, Green Point, South Africa');
alert(point); // this returns "Undefined".
</script>
这是在FF。我没有得到JS错误。我不是JS专家。谁能看到我做错了什么?
由于
J
答案 0 :(得分:3)
您获得undefined
因为geocode()
是异步功能。
要获得结果,您必须 - 例如 - 将回调函数传递给geocodeAddress()
,并在您拥有该位置时调用该函数。
function geocodeAddress(address, succCallback) {
geocoder.geocode({address:address}, function (results,status){
if (status == google.maps.GeocoderStatus.OK) {
var p = results[0].geometry.location;
var lat=p.lat();
var lng=p.lng();
var location = '{'+lat+','+lng+'}';
succCallback(location);
} else {
alert('GeoCoder problem');
}
});
}
var geocoder = new google.maps.Geocoder();
var point = geocodeAddress(
'Cape Town Carnival, Somerset Road, Green Point, South Africa',
function(l) {
alert(l);
});