firefox位置感知+javascript范围

firefox location awareness + javascript scope

本文关键字:范围 +javascript 感知 位置 firefox      更新时间:2023-09-26

我主要用PHP编写代码,对JavaScript范围没有广泛的知识;希望有人能很快解决我的问题。如注释所示,检查mapCenter.Litude和mapCenter.L经度-它们显示为空。

如果浏览器中有位置感知功能,if将执行-我确信它对我有效,我用alert()测试了它。此外,我知道它正在正确地获取position.words.latitude/经度,因为我也用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);
        ...
    });
}