1

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

2
  • It works for me without using ngZone Commented May 5, 2017 at 6:00
  • Interesting. I thought geolocation is one of the examples where zone is required. Did they fix it in zone.js (didn't follow the development)? Commented May 5, 2017 at 6:05

1 Answer 1

2

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;
      });
    });
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, I tried the exact same code but it's not working for me :(
As yurzui explained it shouln't even be necessary. Please create a plunker that allows to reproduce the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.