2011-05-25 66 views
1

我主要使用PHP代码,我没有丰富的JavaScript范围知识;希望有人能很快解决我的问题。如评论所示,检查mapCenter.Latitude和mapCenter.Longitude - 它们显示为空。firefox位置感知+ javascript范围

如果将执行,如果位置感知在浏览器中可用 - 我敢肯定它适用于我,我用alert()测试它。此外,我知道它正确地抓住position.coords.latitude/longitude,因为我用alert()的方法测试了这些...但是这些值在函数之外并不是持久的。这可能是微不足道的 - 解决方法是什么?

function load(){ 
     map = new VEMap('MapDiv'); 
     map.LoadMap(); 
     mapCenter = new VELatLong(); 
     if(navigator.geolocation) 
     { 
      navigator.geolocation.getCurrentPosition(function(position) 
      { 
       mapCenter.Latitude = position.coords.latitude; 
       mapCenter.Longitude = position.coords.longitude; 

      });    
     }   

     //Inspecting mapCenter.Latitude & mapCenter.Longitude shows empty... 

     map.SetCenterAndZoom(mapCenter, 15); 
... 
... 
} 

谢谢!

回答

3

getCurrentPosition接受回调,告诉我它正在执行异步操作。所以发生的事情是你的匿名函数中的代码最有可能在调用map.setCenterAndZoom(mapCenter, 15)之后执行。当您使用异步操作时,执行过程不再等待完成(因此是异步)而进入异步调用。因此,如果您依赖于来自异步调用的任何数据,则需要确保在回调中处理它,因为否则很可能无法使用它。

你应该做的是拨打电话回调,像这样:

function load(){ 
     map = new VEMap('MapDiv'); 
     map.LoadMap(); 
     mapCenter = new VELatLong(); 
     if(navigator.geolocation) 
     { 
      navigator.geolocation.getCurrentPosition(function(position) 
      { 
       mapCenter.Latitude = position.coords.latitude; 
       mapCenter.Longitude = position.coords.longitude; 
       map.SetCenterAndZoom(mapCenter, 15); 
       //any other code that needs to deal with mapCenter 
      });    
     }   
} 

map将可匿名函数里面,因为它就像一个闭合,所以它在词法势必范围在其中被定义。

+0

这是完美的,谢谢你的代码,和优秀的解释。干杯! – 2011-05-25 22:14:22

0

geolocation.getCurrentPosition()是asynchronous。这意味着getCurrentPosition()在传递给它的函数被调用之前返回。浏览器存储您的功能,计算坐标,然后最终调用您的功能。这会在load()函数完成后很长时间发生,因此mapCenter为什么是空的。

一个简单的解决方法是把所有后续的代码是依赖于mapCenter步入回调函数:

... 
    navigator.geolocation.getCurrentPosition(function(position) 
    { 
     mapCenter.Latitude = position.coords.latitude; 
     mapCenter.Longitude = position.coords.longitude; 
     ... 
     map.SetCenterAndZoom(mapCenter, 15); 
     ... 
    }); 
}