firefox location awareness + javascript scope
I primarily code in PHP, I don't have extensive knowledge on JavaScript scope; hoping somebody can solve my problem pretty quickly. As indicated by the com开发者_Go百科ment, inspecting mapCenter.Latitude and mapCenter.Longitude - they appear empty.
The if will execute if location awareness is available in the browser - I'm certain it works for me, I tested it with an alert(). Furthermore, I know it is grabbing position.coords.latitude/longitude correctly, as I tested these with alert()'s too... But the values aren't persistent outside of the function. This is probably trivial - what's the fix?
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);
...
...
}
Thanks!
getCurrentPosition
accepts a callback which tells me that it is performing an asynchronous operation. So what is happening is that the code inside your anonymous function is most probably getting executed after map.setCenterAndZoom(mapCenter, 15)
is called. When you work with asynchronous operations, execution proceeds past the asynchronous call without waiting for completion (hence asynchronous). So if you are depending on any data that comes from the asynchronous call, you need to make sure that you handle it within the callback, because it will most probably not be available to you otherwise.
What you should do is make the call inside your callback like so:
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
will be available inside the anonymous function since it behaves like a closure and so it is lexically bound to the scope in which it was defined.
geolocation.getCurrentPosition() is asynchronous. That means that getCurrentPosition() returns before the function you pass to it gets called. The browser stores your function, calculates the coordinates, then finally calls your function. This is occurring long after the load() function completes, thus why mapCenter is empty.
A simple fix is to move all subsequent code that's dependant on mapCenter into the callback function:
...
navigator.geolocation.getCurrentPosition(function(position)
{
mapCenter.Latitude = position.coords.latitude;
mapCenter.Longitude = position.coords.longitude;
...
map.SetCenterAndZoom(mapCenter, 15);
...
});
}
精彩评论