从地名获取位置的纬度和经度值

时间:2015-09-20 20:44:44

标签: javascript google-maps

我正在编写一个JavaScript函数来返回给定地名的纬度和经度值。我使用谷歌地图API来获得结果。但是我没有得到我想要的结果。这是我的代码来获得结果

function getLocationCoordinates(place)
{    
    var geocoder = new google.maps.Geocoder();
    var address = place;
    geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        //alert(results[0].geometry.location.H+","+results[0].geometry.location.L);
       return results[0].geometry.location.H+","+results[0].geometry.location.L;      

    } else {
        return "0,0";
    }
    });
} 

当我调用函数getLocationCoordinates('kollam')时,我得到值“undefined”。它应该返回值'8.8800,76.6000'。但是当我警告'results [0] .geometry.location .H +“,”+结果[0] .geometry.location.L',显示正确的值。如何使此函数返回正确的值。

1 个答案:

答案 0 :(得分:2)

您的代码中存在2个问题

首先geocoder.geocode()是异步的,这意味着您无法将响应返回到您的外部函数,因为在该函数完成之前,Google服务器尚未返回数据。

第二......即使它不是非常理想的,地理编码回调中的return也不会返回外部函数。

目前getLocationCoordinates()将始终返回undefined,因为没有返回任何内容

您需要返回使用gecode响应解析的promise或使用地理编码回调中的数据。