Get coordinates of current location in angular

后端 未结 2 1224
忘掉有多难
忘掉有多难 2021-02-19 10:42

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

  getCurrentLocation() {
    if (nav         


        
2条回答
  •  暖寄归人
    2021-02-19 11:28

    You could return a promise.

    locationService.ts

     getPosition(): Promise
      {
        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}`);
      });
    

提交回复
热议问题