2012-10-09 56 views
0

Iam总共JS Newb,并试图构建我的简单JS代码。目标是获取用户位置。结构JS - 变量为空?

它的工作原理,但getUserCoordinates函数没有返回值?我认为这只是一个初学者的逻辑失败?

var app = { 

geocoder: null, 

init: function() { 
    this.geocoder = new google.maps.Geocoder(); 
    coordinates = this.getUserCoordinates(); 
    console.log(coordinates); // empty?? 
    return; 
}, 

getUserCoordinates: function() { 

    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition( 

      function (coords) { 
       console.log(coords); // works Geocoder Object! 
       return coords; // the problem 
      }, // more code 

回答

2

不,这对初学者来说是一个很常见的错误。 getCurrentPosition方法是异步的(它需要一些时间来确定位置)并且不返回任何内容。完成后,它将调用您传递给它的callback函数 - 某些时候将会使用它。该值仅在该回调中可用,或者仅在那里调用的函数中可用。

+0

感谢听起来合乎逻辑,有没有什么好的解决方案呢? – opHASnoNAME

+0

您可以使用回调函数(您传递给getUserCoordinates方法),或者从代表该值的函数返回一个[Promise](http://wiki.commonjs.org/wiki/Promises)并使用回调函数内部。 – Bergi