0

I have a JS Widget that is used to work out the closest location to a users current location from a list (using lat/long).

First of all I use the _create() method tries to set the users location by calling setLocation() method, and then after that there is a check to see if the coordinates were successfully set before continuing. Here is the setLocation() method, which generates no errors but doesn't result in my proceeding beyond the aforementioned check (if(typeof(this.coords) != 'undefined')) -

/**
 * Set the users current loction (latitude and longitude)
 */
setLocation : function(){

    var t = this;   // This object

    if(navigator.geolocation){  // Ensure that the users location is available

        navigator.geolocation.getCurrentPosition(function(position){    // Set the users current location within this object
            t.coords = {
                latitude:   position.coords.latitude,
                longitude:  position.coords.longitude
            };
        });

    }

}, // getLocation

The curious thing however is that when I console.log(this), this.coords is correctly set as an object. However, console.log(this.coords) results in undefined being output.

Is anyone able to help me understand why this behavior is occurring?

I've listed my full code in this pastebin, and as an example here is how your could test the code -

$('#closest').closest({
    stations:   new Array(
        {
            "name": "Exeter St David's",
            "code": "EXD",
            "link": "neveryoumindEXD.html",
            "latitude": "50.729342",
            "longitude": "-3.543290"
        },
        {
            "name": "Swindon (Wilts)",
            "code": "SWI",
            "link": "neveryoumindSWI.html",
            "latitude": "51.566828",
            "longitude": "-1.785450"
        }
    )
});
David Gard
  • 11,225
  • 36
  • 115
  • 227
  • Given that you're doing `var t = this`, can I assume that `getCurrentPosition` is asynchronous? In that case, you're probably using the results before they're actually known, and the concepts in [this question](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) are relevant – James Thorpe Mar 20 '15 at 12:45
  • From what I can tell through the docs, the `getCurrentPosition()` is not asynchronous. I think the problem is that I'm setting `t.coords`, which isn't actually `this`. I've tried `this.coords = t.coords`, but that also failed. – David Gard Mar 20 '15 at 13:41

0 Answers0