Reputation: 610
I'm starting to learn javascript and was fiddling around gps. Currently, I'm having issues with scoping on a function.
The code
$(document).ready(function () {
var lat, lng;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
$(document).data('lat', position.coords.latitude); //undefined outside
lat = position.coords.latitude; //undefined outside
lng = position.coords.longitude; //undefined outside
});
}
var coords = new google.maps.LatLng(lat,lng); //lat & lng are undefined
});
the problem lies in the fact that whatever value I assign in the local scope of the function called by getCurrentPosition is not kept. What is best practice on handling this issue. I'm assuming it is to just return an object back containing the data, but how exactly do i do that? I tried doing that, but it still wasn't working
Upvotes: 0
Views: 70
Reputation: 610
Well, I figured it out thanks to the two comments above. The problem isn't a scoping problem, but rather an asynchronous problem. Refer to stackoverflow.com/q/14220321/218196
$(document).ready(function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error, { maximumAge: 75000 });
}
function success(position) {
var coords = new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude);
initMap(coords);
}
function error(err) {
//coordinates of LA
initMap(new google.maps.LatLng(34,118));
}
function initMap(coords) {
//logic here
}
});
Upvotes: 3