firefox位置感知+ javascript作用域

| 我主要使用PHP编写代码,我对JavaScript范围没有广泛的了解;希望有人能很快解决我的问题。如评论所示,检查mapCenter.Latitude和mapCenter.Longitude-它们显示为空。 如果浏览器中提供位置识别功能,则if将执行-我确定它对我有用,我使用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);
...
...
}
谢谢!     
已邀请:
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
将在匿名函数内部可用,因为它的行为类似于闭包,因此在词法上绑定了它的定义范围。     
geolocation.getCurrentPosition()是异步的。这意味着getCurrentPosition()在传递给您的函数被调用之前返回。浏览器存储您的函数,计算坐标,然后最终调用您的函数。在load()函数完成之后很久就发生了这种情况,因此为什么mapCenter为空。 一个简单的解决方法是将所有依赖于mapCenter的后续代码移入回调函数:
    ...
    navigator.geolocation.getCurrentPosition(function(position) 
    {
        mapCenter.Latitude = position.coords.latitude;
        mapCenter.Longitude = position.coords.longitude;
        ...
        map.SetCenterAndZoom(mapCenter, 15);
        ...
    });
}            
    

要回复问题请先登录注册