firefox位置感知+javascript范围
firefox location awareness + javascript scope
我主要用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);
...
});
}
相关文章:
- 正在全局范围中查找JavaScript函数
- Javascript:'受保护'范围界定
- Javascript innerHTML超出范围的问题
- 可以't访问JavaScript函数范围中的变量
- 用javascript映射和匹配范围
- firefox中的Javascript事件范围问题
- 如何在JavaScript中获取文本区域的选定文本范围
- 从GWT中的HighCharts库(以及一般的Javascript)自定义Stockchart范围选择器按钮
- 获取给定JavaScript范围内的解析函数
- 使用javascript中的var关键字创建块范围的变量
- 为什么在javascript中的模块模式中实现Lazy函数时范围会发生变化
- 用Javascript编辑范围数据(时间序列)
- 为什么此变量超出范围?JavaScript
- 范围 JavaScript 中变量和对象之间的差异
- Struts:getElementByID来自请求范围(Javascript)
- 查找数组/范围javascript中所有丢失的元素
- 定义数组的隔离范围javascript
- 同时更改两个范围- javascript
- 如何获取一周中存在于某个日期范围(Javascript)中的天数列表
- 随机大整数在范围JavaScript