从javascript函数返回变量

时间:2014-04-05 17:52:08

标签: javascript google-maps-api-3

我试图从这个函数返回经度和纬度,我可以控制它们两个,但当我尝试返回其中一个时,我得到了未定义。

如何返回纬度,经度?

function latLong(location) {
    var geocoder = new google.maps.Geocoder();
    var address = location;
    var longitude;
    var latitude;
    geocoder.geocode({
        'address': address
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            latitude = results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
        console.log(longitude);
    });
}

2 个答案:

答案 0 :(得分:4)

地理编码器是异步的,你不能从异步函数返回数据,但你可以使用回调

function latLong(location, callback) {
    var geocoder = new google.maps.Geocoder();
    var address = location;
    var longitude;
    var latitude;
    geocoder.geocode({
        'address': address
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            latitude = results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();

            callback(latitude, longitude);

        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

并使用它

 latLong(location, function(lat, lon)  {
     // inside this callback you can use lat and lon
 });

答案 1 :(得分:1)

你没有。

通常使用的技术是将回调传递给latLong函数作为参数,并在收到结果时运行此函数。

类似的东西:

function latLong(location, callback) {

    var geocoder = new google.maps.Geocoder();
    var address = location;
    var longitude;
    var latitude;
    geocoder.geocode({
        'address': address
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            latitude = results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();
            callback(latitude, longitude);
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
        console.log(longitude);
    });
}