无法应对navigator.geolocation的异步性质

Raj*_*aja 5 javascript w3c geolocation

我在firefox 3.6中使用了navigator.geolocation.getCurrentPosition(function)api.当我试图反复调用这个方法时,我发现它有时会起作用,有时则不然.我认为问题是由于它的异步回调性质.我可以看到回调函数在某个时刻被调用,但我的外部函数已经退出,所以我无法捕获位置坐标的值.

我是javascript的新手,所以我假设其他javascript编码器可能已经找到了如何处理它.请帮忙.

编辑:这是我正在使用的一段代码示例

<script type="text/javascript">
   function getCurrentLocation() {
     var currLocation;
      if(navigator.geolocation) {
         navigator.geolocation.getCurrentPosition(function(position) {
          currLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
        });
       }
       return currLocation; // this returns undefined sometimes. I need help here
}    
</script>
Run Code Online (Sandbox Code Playgroud)

编辑2:感谢大家的回答,我希望我能选择所有答案为"已接受",但不能这样做.

现在我面临另一个问题.我每3秒调用一次navigator.geolocation.getCurrentPosition,但响应在10到15个回复后停止.任何人都有任何想法?

再次感谢

小智 6

您可以使用承诺:

var lat,lon;
var promise1 = new Promise(function(resolve, reject) {
    navigator.geolocation.getCurrentPosition(function(pos){
        lat = pos.coords.latitude
        lon = pos.coords.longitude
        resolve({lat,lon});
    }) 
})

promise1.then(function(value) {
      console.log(value.lat,value.lon)  
});
Run Code Online (Sandbox Code Playgroud)


Dan*_*llo 5

是的,您对操作的回调性质有疑问。您不能调用该getCurrentLocation()函数并期望它会同步返回。我什至很惊讶它偶尔会起作用。

在处理异步调用时,您必须使用稍微不同的范例。您可能应该调用您的函数,plotCurrentLocation()并执行类似于以下示例的操作:

function plotCurrentLocation(map) {
   if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
         var currLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);

         // plot the currLocation on Google Maps, or handle accordingly:

         new google.maps.Marker({ title: 'Current Location',
                                  map: map, 
                                  position: currLocation });

         map.setCenter(currLocation);
      });
   }
}
Run Code Online (Sandbox Code Playgroud)

请注意map传递给plotCurrentLocation()函数的参数如何可供内部函数使用。这是有效的,因为 JavaScript 有闭包


更新:

通过添加另一层抽象,其他答案建议的回调方法是解决此问题的另一种选择。


Mat*_*hen 5

你试图使它同步,它将无法正常工作.如您所见,无法保证在函数返回时设置currLocation.你现在可能有类似的东西:

var loc = getCurrentLocation();
//doSomethingWith loc
Run Code Online (Sandbox Code Playgroud)

将您的功能更改为:

function getCurrentLocation(callback) {
   if(navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
         callback(new google.maps.LatLng(position.coords.latitude,
                                       position.coords.longitude));
       });
    }
    else {
       throw new Error("Your browser does not support geolocation.");     
    }
}     
Run Code Online (Sandbox Code Playgroud)

和客户端代码:

getCurrentLocation(function(loc)
{
  //doSomethingWith loc
});
Run Code Online (Sandbox Code Playgroud)