0

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)

ppetree
  • 826
  • 3
  • 15
  • 31
  • I'd guess that `navigator.geolocation.watchPosition` is not finished (it's an async call, right?) when you call getPosition. – James Nov 08 '17 at 23:33
  • watchPosition gets called on init... I can wait a full minute and hit getPosition and get the same result. And like I said, I can move this back to procedural and it works just fine. – ppetree Nov 09 '17 at 00:28

1 Answers1

0

the answer lies in "this" - as apparently keeping up with the "this" is a bit too complicated for the javascript engineers so inside your object you have to make a copy of "this" and then use the copy to reference items in your object.

function geolocation() {
  var self = this;
  this.watchID;
  this.position;

  this.success = function(p) {
    self.position = p;
  };
ppetree
  • 826
  • 3
  • 15
  • 31