How to get your current location in real-time using geolocation?

I am getting my current location using Geolocation below:

ngAfterViewInit(): void {
    this.getLoc().then((resp) => {
      this.initMap(resp.coords.latitude, resp.coords.longitude);
    }, er => {
      alert('Cannot retrieve Location')

getLoc() {
    return this.geolocation.getCurrentPosition(
        maximumAge: 1000, timeout: 5000,
        enableHighAccuracy: true

The above code retrieves my current location when I open up the app.

But now when the user has the app open, I want their location to be updated in realtime.

I.e. If I have the app open, & start walking, I want my longitude & latitude values to be updated on the map I’m initiating in ngAfterViewInit().

Can someone please tell me what changes I need to make to add this functionality?

Hi, you are reading the current position at the beginning with a Promise which “dies” ones it is resolved.

If you want your position constantly updated you need to subscribe to an Observable:

let watch = this.geolocation.watchPosition();
watch.subscribe((data) => {
  updatePosition(data.coords.latitude, data.coords.longitude)   // or just (data) and you read data inside updatePosition, that's up to you

remember to unsubscribe watch whenever you don’t need it anymore.


Thanks for this.

Where could I be calling this code?

Is it in ngOnInit()?

It really depends on your code, I’d say you can put it just after reference of the map is defined!

It could be ngOnInit, ngAfterViewInit or even into the constructor if you handle the situation where the map object is null/undefined.

OK, I’m initialising the map in ngAfterViewInit(), so I’ll give that a try & post the outcome here