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

时间:2015-01-05 09:46:17

标签: javascript 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'。抱歉没有问题,请提前感谢您!

2 个答案:

答案 0 :(得分:0)

仅在完成地理编码回调函数后才会触发

alert("The coordinates of the....)。但是alert ("Lat: "+lat+", \nLng: "+long);会在if (geocoder) { }条件之后立即触发,而不会等待任何事情。这就是为什么你得到lat和long的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
}

答案 1 :(得分:0)

试试这个: 阅读评论

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);

}