I'm trying to move from my old procedural approach to javascript coding to a more object based approach. One of the pieces of code I'm trying to migrate is my location tracker as shown here:
var gps = new geolocation();
function geolocation() {
this.watchID;
this.position;
this.success = function(p) {
this.position = p;
};
this.failure = function(error) {
var errmsg;
// convert the error code to a readable message
switch(error.code)
{
case error.PERMISSION_DENIED:
errmsg="App doesn't have permission to access your location.";
break;
case error.POSITION_UNAVAILABLE:
errmsg="Your location information is unavailable to App.";
break;
case error.TIMEOUT:
errmsg="App's request to get your location timed out.";
break;
case error.UNKNOWN_ERROR:
errmsg="An unknown GPS error occurred.";
break;
}
console.log(errmsg);
};
this.watchPosition = function() {
if(!this.watchID)
{
this.watchID = navigator.geolocation.watchPosition(this.success, this.failure, { maximumAge: 1000, timeout: 15000, enableHighAccuracy: true });
}
};
this.getPosition = function() {
return(this.position);
};
this.clearWatch = function() {
if(this.watchID)
{
// turn off the watch
navigator.geolocation.clearWatch(this.watchID);
this.watchID = null;
console.log("GPS WatchID was cleared.", "GPS Status");
}
};
};
I can access all the methods in this object. When I start gps.watchPosition(); this.watchID gets set. However, when I use:
var p = gps.getPosition();
I get p as 'undefined' and running through the debugger shows this.position is also undefined.
If I break this code back out to it's procedural state, it works fine. Obviously, I'm missing something but I just can't figure out what.
(note: I did some minimizing of this code before posting)