变量不在函数外传递值

时间:2014-01-22 02:02:28

标签: javascript jquery google-maps

我正在制作Google地图地理编码,我想知道为什么我的脚本在该警报上不会带有g_latg_long的值?我确信它有一个值,因为当我做console.log()它显示的东西。

var g_lat;
var g_long;

geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    g_lat = results[0].geometry.location.lat();
    g_long = results[0].geometry.location.lng();
    console.log(g_lat); // output: -33.8468085
    console.log(g_long); // output: 151.06454640000004
  } else {
    alert('Geocode was not successful for the following reason: ' + status);
  }
});
alert(g_lat); // output: undefined
alert(g_long); // output: undefined

3 个答案:

答案 0 :(得分:1)

这是因为请求的异步性质

var g_lat;
var g_long;

//this sends an asynchronous request, meaning the execution of next statements will continue without waiting for the response to the request
geocoder.geocode({
    'address': address
}, function (results, status) {
    //once the request is completed this method gets called, all code that depends on the value returned by this request should be kept here
    if (status == google.maps.GeocoderStatus.OK) {
        g_lat = results[0].geometry.location.lat();
        g_long = results[0].geometry.location.lng();
        console.log(g_lat); // output: -33.8468085
        console.log(g_long); // output: 151.06454640000004
    } else {
        alert('Geocode was not successful for the following reason: ' + status);
    }
});
//thest statements are executed before the response comes back so you are getting undefined
alert(g_lat); // output: undefined
alert(g_long); // output: undefined

答案 1 :(得分:1)

Leandro,看起来您可能需要开始识别代码的哪些区域可以推送到各个功能中。这样可以更轻松地实现您想要的目标。

然而,首先是回调。您知道可以将函数作为参数传递给其他函数吗?这是一个非常有用的功能,特别是当您处理对API的异步调用时。类似于这个例子 - 我们调用doThis但是在我们执行了doThis中我们需要的所有其他内容后,传入一个函数来调用。控制台将按顺序显示日志。

// `doThis` receives a function as a callback and executes it after doing stuff.
function doThis(callback) {
  console.log('logged first');
  callback();
}

// pass in a function as a parameter to `doThis` when we call it
doThis(function () {
  console.log('logged second');
});

嗯,我们也可以使用你的代码。 (为了简洁起见,我删除了一些代码)

将地理编码代码推送到自己的函数中。在这里,我将地理编码的结果推送到回调中:

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

然后使用回调从代码中的其他位置调用该函数。这里,回调从地理编码函数接收结果数据。

getGeocode(function (results) {
  var g_lat = results[0].geometry.location.lat();
  var g_long = results[0].geometry.location.lng();
  console.log(g_lat, g_long);
});

你甚至可以将它包装在它自己的函数中,这样你只需要获取一些地理编码数据并记录它(例如),你只需要执行它,也许通过传入你想要的地址:

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

function getGeocodeAndProcess(address) {
  getGeocode(address, function (results) {
    var g_lat = results[0].geometry.location.lat();
    var g_long = results[0].geometry.location.lng();
    console.log(g_lat, g_long);
  });
}

getGeocodeAndProcess('chicago');

我希望这对你有用。

答案 2 :(得分:-1)

我无法测试它,但它应该可以解决问题,让我知道。

var g_lat;
var g_long;


geocoder.geocode({'address': address}.then
    (function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            g_lat = results[0].geometry.location.lat();
            g_long = results[0].geometry.location.lng();
            console.log(g_lat); 
            console.log(g_long);
        }
    }),function(error) {
        alert('Geocode was not successful for the following reason: ' + error);
    }
});
相关问题