0

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.

1
  • Can you share a jsfiddle with the functional code? Commented Oct 7, 2012 at 3:03

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.