Elias
Elias

Reputation: 357

Get coordinates of current location in angular

I created the following function in a service, to get the coordinates of the current location and store them in 2 variables:

  getCurrentLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(position => {

        this.currLat = position.coords.latitude;
        this.currLng = position.coords.longitude;
      });
    }
    else {
      alert("Geolocation is not supported by this browser.");
    }
  }

how can I return the coordinates through this function in order to use them in a component?

Upvotes: 19

Views: 43594

Answers (2)

René Winkler
René Winkler

Reputation: 7058

Just in case if you want continually request the position, then use

navigator.geolocation.watchPosition(res => ...

Upvotes: 7

David
David

Reputation: 34435

You could return a promise.

locationService.ts

 getPosition(): Promise<any>
  {
    return new Promise((resolve, reject) => {

      navigator.geolocation.getCurrentPosition(resp => {

          resolve({lng: resp.coords.longitude, lat: resp.coords.latitude});
        },
        err => {
          reject(err);
        });
    });

  }

component.ts

  this.locationService.getPosition().then(pos=>
  {
     console.log(`Positon: ${pos.lng} ${pos.lat}`);
  });

Upvotes: 49

Related Questions