为什么这个变量未定义或未返回?

时间:2012-09-17 21:58:49

标签: javascript google-maps-api-3

我有以下代码:

/*
 * converts a string to geolocation and returns it
 */

function stringToLatLng(string){
    if(typeof string == "string"){
        geocoder = new google.maps.Geocoder();
        geocoder.geocode( { 'address': string}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
              console.log("LatLng: "+results[0].geometry.location);
              return results[0].geometry.location;
           } else {
              console.log("Geocode was not successful for the following reason: " + status);
           }
        });
   }
}

LatLng将正确的位置输出到控制台,但是当我写这个时:

var pos = stringToLatLng('New York');
            console.log(pos);

我回来了undefined。这是为什么?感谢

2 个答案:

答案 0 :(得分:2)

这样的事情:

function stringToLatLng(strloc, callback){
    if(typeof string == "string"){
        geocoder = new google.maps.Geocoder();
        geocoder.geocode( { 'address': strloc}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
              callback.call({}, results[0].geometry.location);
           } else {
              console.log("Geocode was not successful for the following reason: " + status);
           }
        });
   }
}

stringToLatLng('New York', function(pos){
    console.log(pos);
});

在你的代码中,当你返回时,你实际上是从函数(结果,状态){..}函数返回,而不是stringToLatLng函数,如注释中所说的异步调用,所以你必须使用回调

答案 1 :(得分:0)

var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();

REF: Javascript geocoding from address to latitude and longitude numbers not working