1

I am trying to create a geolocation class so that I can call that class when and where I need it but I ran into a problem, and keep getting the error. Uncaught TypeError: Cannot read property 'setLatitude' of undefined at setCurrentPosition (geolocation.js:13)

Any guidance would be apprecitated?

 class Geolocation {
    constructor() {
        this.latitude = 0;
        this.longitude = 0;
    }

    getGeoLocation() {
        if ('geolocation' in navigator) {
            navigator.geolocation.getCurrentPosition(this.setCurrentPosition);
        }
    }
    setCurrentPosition(position) {
        this.setLatitude(position.coords.latitude);
        this.setLongitude(position.coords.longitude);
    }
    setLatitude(latitude) {
        this.latitude = latitude;
    }
    setLongitude(longitude) {
        this.longitude = longitude;
    }

    getLatitude() {
        return this.latitude;
    }

    getLongitude() {
        return this.longitude;
    }
}
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44

2 Answers2

2

You need to bind to the correct this:

navigator.geolocation.getCurrentPosition(this.setCurrentPosition.bind(this))
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
  • I did not know about bind. Thank you! I am trying to stay in the best practice and use separation of concerns pratice. Is this the best way to write this code? – jauntyCoder Apr 16 '20 at 22:10
  • You are doing it correctly but if you need a function which has a callback, then you need to use the correct `this` as context because the callback function has its own context, which is different. So yes I'd say this is pretty much how you'd do it – Anurag Srivastava Apr 16 '20 at 22:13
0

The this is not pointing to the class instance of Geolocation. You need to bind the this to the instance in the constructor:

constructor() {
   this.latitude = 0;
   this.longitude = 0;
   this.setCurrentPosition = this.setCurrentPosition.bind(this);
}
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44