Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 683
Elias Avatar asked Aug 01 '18 08:08

Elias


2 Answers

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}`);
  });
like image 126
David Avatar answered Sep 21 '22 19:09

David


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

navigator.geolocation.watchPosition(res => ...
like image 36
René Winkler Avatar answered Sep 20 '22 19:09

René Winkler