I wanted to play with geolocation API on my Android. I know that there is a “navigator” object that is defined and that should be used to aquire user position. So, I created this sample code:
function GeolocationTester()
{
// here I want to store all acquired locations
this.locations = new Array();
alert("this.locations defined: " + this.locations);
this.onSuccess = function(position)
{
alert("Entered onSuccess");
alert("this.locations defined: " + this.locations);
}
this.onError = function(error)
{
alert("error acquiring location");
}
navigator.geolocation.watchPosition(this.onSuccess, this.onError, { enableHighAccuracy: true });
}
And it doesn’t work for me. Each time watchPosition call onSuccess the this.locations field isn’t defined (and it is defined just after new Array). I known that I’m doing somethind wrong, but as it is one of my JavaScript attempts, not sure what. So, anybody could find a problem here?
The problem is with the scoping of
this. When theonSuccessoronErroris called,thisisn’t bound to the object containing thelocationsarray. You need to create an explicit variable outside of the functions to which the array should be assigned and then use this variable in the callbacks, like this: