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"
}
)
});