通过 Google 地理编码获取地址坐标

Getting address coordinates through Google geocoding

我正在尝试通过 Google 地理编码获取地址的坐标,并且使用此方法几乎可以正常工作:

function getAddressCoordinates() {

    var geocoder = new google.maps.Geocoder();
    var address = $('#cAddress').get(0).value;
    var lat = 0;
    var long = 0;

    if (geocoder) {
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {

                alert("The coordinates of the entered address are: \nLatitude: "+results[0].geometry.location.lat()+"\nLongitude: "+results[0].geometry.location.lng());
                lat = results[0].geometry.location.lat();
                long = results[0].geometry.location.lng()
            }
            else {
                alert("Geocoding failed: " + status);
            }
        });
    } 
    alert ("Lat: "+lat+", \nLng: "+long);
}

问题:'lat' 和 'long' 变量没有被赋予正确的值,它们仍然为 0,尽管警报显示了正确的坐标。另一个观察结果:最后一个警报首先弹出,然后是 'if' 中的警报。抱歉,菜鸟问题,提前谢谢你!

alert("The coordinates of the....)只有完成地理编码回调函数后才会触发。但是 alert ("Lat: "+lat+", \nLng: "+long); 将在 if (geocoder) { } 条件之后立即触发,无需等待任何事情。这就是为什么您得到经纬度的 0 值的原因。

这里给全局变量赋值不是个好主意。您可以做的是在回调函数本身中编写更多代码,例如

if (status == google.maps.GeocoderStatus.OK) {

   alert("The coordinates of the entered address are: \nLatitude: "+results[0].geometry.location.lat()+"\nLongitude: "+results[0].geometry.location.lng());
   lat = results[0].geometry.location.lat();
   long = results[0].geometry.location.lng();

   furtherProcessing(lat,long);
}

// 在回调

之外定义furtherProcessing 函数
function furtherProcessing(lat,long) {
 // do what ever with lat n long
}

试试这个: 阅读评论

function getAddressCoordinates() {

var geocoder = new google.maps.Geocoder();
var address = $('#cAddress').get(0).value;
var lat = 0;
var long = 0;

if (geocoder) {
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {

            alert("The coordinates of the entered address are: \nLatitude: "+results[0].geometry.location.lat()+"\nLongitude: "+results[0].geometry.location.lng());
            lat = results[0].geometry.location.lat();
            long = results[0].geometry.location.lng();
            // this section gets executed only after geocoding service call is complete
            // so return/alert your lat long values from here
        }
        else {
            alert("Geocoding failed: " + status);
        }
    });
} 
// as geocoding service is asynchronous, it executes immediately with 0 values
alert ("Lat: "+lat+", \nLng: "+long);

}