我可以在回调函数

时间:2015-08-10 11:09:51

标签: javascript google-maps

我在position函数中定义geocode时遇到了一些问题。 我在我的函数中得到了正确的结果,但我不能在函数之外使用它。

var position;

var geocoder = new google.maps.Geocoder();

geocoder.geocode({
  'address': row.Address + ' ' + row.Postal_Code + ' ' + row.City + ' ,' + row.Country
}, function(results, status) {
  if(status == google.maps.GeocoderStatus.OK) {
    position = results[0].geometry.location; // console.log(position) // correct result
  }
});

的console.log(结果); //未定义

2 个答案:

答案 0 :(得分:1)

除非您没有在地理编码中运行您的函数,否则该值不会分配给位置变量。

var position;
function forPosition(results, status) {
    if(status == google.maps.GeocoderStatus.OK) {
    position = results[0].geometry.location;
}
forPosition();// now position is set to results[0].geometry.location;

您有一个匿名函数,应该运行该函数以便为变量赋值。

或者只是在下面的例子中

var greeting = "Hello";
function func(){
    greeting = "hi"
    alert(greeting)
}
//func() //uncommenting func() will result in alerting two times 'hi'. 
alert(greeting)

运行函数func后,它将greeting变量设置为'hi'并警告函数内的变量,然后在函数范围之外的警报将再次警告greeting变量。除非函数运行,问候语始终设置为“Hello”。

答案 1 :(得分:-1)

您已在回调函数中分配了position变量,现在您正尝试将result变量输出到控制台。此变量从未被声明或分配。它肯定会返回undefined

应该有效:

console.log(position);

<强>更新
好的,现在,稍微纠正一下 - google.maps.Geocoder异步方法。 OP在帖子的任何地方都没有提到它 - 我必须找到这个库,下载它,研究它的API并自己学习。
在我看来,所有用户都没有必要知道每个第三方库,在这种情况下,我是对的 - 即使方法是同步的,这个代码也会输出undefined输出未定义的变量

相关问题