-2

I have placed the geolocation call in a service which I want to use in different areas of the application. However, undefined is being returned. How do I return the value properly so that it can be retrieved?

Service code

   getUserPosition() {
     this.geolocation.getCurrentPosition().then((position) => {
    this.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    this.currentLat = position.coords.latitude;
    this.currentLng = position.coords.longitude;
    return this.latLng;

    }, (err) => {
      console.log('There was an error');
    });
  }

Call this function from the service

  async ngOnInit() {
    // Since ngOnInit() is executed before `deviceready` event,
    // you have to wait the event.
    await this.platform.ready();
    await this.loadMap();

   this.val =  await this.location.getUserPosition(); 
   console.log("I should be here val "+ this.val);
  }
georgeawg
  • 48,608
  • 13
  • 72
  • 95
A.Mac
  • 203
  • 3
  • 19

2 Answers2

0

It seems that you are not returning anything inside getUserPosition function. You see, return this.latLng; is result of then in promise, not the result of getUserPosition. To fix this, you can for example wait until promise is completed and then return value:

async getUserPosition() {
    try {
        const position = await this.geolocation.getCurrentPosition();
        this.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
        this.currentLat = position.coords.latitude;
        this.currentLng = position.coords.longitude;
        return this.latLng;
    }, (err) => {
      console.log('There was an error');
    });
}

I strongly recommend to use typescript to avoid this type of mistakes - if you add type to the function properly, the compiler would tell you that function should return a specific type but tries to return void.

  • I had tried returning it from the getUserPosition function and it was still saying undefined. However, I was able to find a solution which I posted. – A.Mac Feb 08 '21 at 15:04
0

Returning the details from the function

async getUserPosition() {
    await this.geolocation.getCurrentPosition().then((position) => {
      this.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      this.currentLat = position.coords.latitude;
      this.currentLng = position.coords.longitude;
      this.locationData = [this.latLng, this.currentLat, this.currentLng];
    }, (err) => {
      console.log('There was an error' + err.message);
    });
    // return all the details returned from the location
    return this.locationData;
  }

Using the details returned

   this.geolocationData = await this.location.getUserPosition();
    this.latLng = this.geolocationData[0];
    this.currentLat = this.geolocationData[1];
    this.currentLng = this.geolocationData[2];
A.Mac
  • 203
  • 3
  • 19