Emery King
Emery King

Reputation: 3534

Geolocation getCurrentPosition behaving odd on callback function

I have 2 js files, 1 is to store the location data in an object and the other is the event handler for the click events and such.

This works:

var Geology = {
    coords: {},
    error: '',
    setPosition: function (position) {
        Geology.coords = position.coords;
        // DEBUG
        for (var prop in Geology.coords)
            console.log(prop + ': ' + Geology.coords[prop]);
    },
    setError: function (error) {
        Geology.error = error;
    }
};

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(Geology.setPosition,Geology.setError,{timeout:10000});
}

But i want to be able to update the location data if necessary by a click or timer. Any time i try to do that it doesn't assign the vars to Geology like it does initially.

like this:

jQuery(document).ready(function($){
    $('.toggle').click(function(){
        //- get geo location if available
        if (typeof Geology === 'object') {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(Geology.setPosition,Geology.setError,{timeout:10000});
            }
        }
    });
});

I don't get errors in the console but it just fails and does not run the callback. However, it does run the getCurrentPosition method because I've tested to see if it makes it through the conditionals.

Upvotes: 0

Views: 1583

Answers (1)

wakooka
wakooka

Reputation: 1428

I think you need to set the maximum_age parameter, otherwise the results will be cached forever :

navigator.geolocation.getCurrentPosition( 
      geo_success, 
      geo_error, 
      { maximumAge:60000 } // set to 1min (in ms)
);

You also have two other parameters : enableHighAccuracy and timeout

More info: https://developer.mozilla.org/en-US/docs/Using_geolocation

EDIT : I just found this, it's probably related to your issue navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

Upvotes: 1

Related Questions