Search code examples
angularangular2-templateangular2-componentsgoogle-geolocation

Angular2 - Component variable value set on callback function not updated in template


User case: When application is opened in web browser, user gets alter- "Know your location" with options "Allow" and "Deny".

I have following code sample.

ngOnInit() {
  if ("geolocation" in navigator) {
    navigator.geolocation.getCurrentPosition((position) => {
      this.latitude = position.coords.latitude;
      this.longitude = position.coords.longitude;
      this.zoom = 18;
    });
  }
}

this works as I can see console.log that the final values of latitude and longitude is current location if allowed otherwise it is the default value which I hard coded.

Now my problem here is this updated current location changes cannot be seen in template when it print {{latitude}} and {{longitude}}

I have tried using ngZone and ChangeDetectorRef but was no success

Can anyone help


Solution

  • The geolocation API is not covered by Angulars zone. Make the callback run inside Angulars zone explicitely and Angular change detection will be run and ensure the view is updated:

    constructor(private zone:NgZone) {}
    
    ngOnInit() {
      if ("geolocation" in navigator) {                
        navigator.geolocation.getCurrentPosition((position) => {
          this.zone.run(() => {
            this.latitude = position.coords.latitude;
            this.longitude = position.coords.longitude;
            this.zoom = 18;
          });
        });
      }
    }