Reputation: 2758
So I have some code that does not seem to be working. This is pretty much the top of the page. Above it are just some other declarations
window.lat = 42.688;
window.lng = -75.980;
$(function () {
if (Modernizr.geolocation) {
alert('ayoson');
navigator.geolocation.getCurrentPosition(function (position) {
window.lat = position.coords.latitude;
window.lng = position.coords.longitude;
})
}
// Build map
var mapOptions = {
center: new google.maps.LatLng(window.lat, window.lng),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
I just end up with the defaults that i set, even though when I put an alert in Modernizr.geolocation it triggers.
Furthermore if I put an alert above var mapOptions
(like alert(window.lng);
) The first alert no longer triggers.
Thanks in advance.
Upvotes: 0
Views: 126
Reputation: 522005
The callback of navigator.geolocation.getCurrentPosition
is executed asynchronously sometime after var mapOptions
is assigned. navigator.geolocation.getCurrentPosition
(possibly) requires a feedback from the user, the callback is only executed afterwards. Meanwhile the rest of your code continues to run.
Since the callback is not guaranteed to run at all if the user ignores it, the best strategy is to build the map with a default location, then, on successfully geolocating the user, update the map position from the navigator.geolocation.getCurrentPosition
callback.
Upvotes: 1