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 comment, 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!
getCurrentPositionaccepts 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 aftermap.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:
mapwill 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.