0

I have problem with my flow, I am using promises to do that

The context is : The User click to button to get your position with ionic geolocation, ir returns lat and log , then I want to decode the coordinates to get the City and the last step is set lat,long and city to the user.

tryGeolocation() {       
    this.geolocation.getCurrentPosition().then((resp) => {
      let pos = {
        lat: resp.coords.latitude,
        lng: resp.coords.longitude
      };
      this.lat = resp.coords.latitude;
      this.long = resp.coords.longitude;          
      console.log(this.lat+"--"+this.long);
      this.decodeCoord(this.lat, this.long);
      alert(this.city);
      this.uploadLocation();    
    }).catch((error) => {
      console.log('Error getting location', error);
      this.loading.dismiss();
    });
  }



 decodeCoord(lat, long) {    
    console.log("decodeCoord");
    var latlng = new google.maps.LatLng(lat, long);
    this.geocoder.geocode({'latLng': latlng}, function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {       
        if (results[1]) {
          var indice = 0;
          for (var j = 0; j < results.length; j++) {
            if (results[j].types[0] == 'locality') {
              indice = j;
              break;
            }
          }   

          let city, region, country;
          for (var i = 0; i < results[j].address_components.length; i++) {
            if (results[j].address_components[i].types[0] == "locality") {
              //this is the object you are looking for City
              city = results[j].address_components[i];
            }
            if (results[j].address_components[i].types[0] == "administrative_area_level_1") {
              //this is the object you are looking for State
              region = results[j].address_components[i];
            }
            if (results[j].address_components[i].types[0] == "country") {
              //this is the object you are looking for
              country = results[j].address_components[i];
            }
          }
          //city data        
          this.city=city;
        } else {
          console.log("No results found");
        }           
      } else {
        console.log("Geocoder failed due to: " + status);
      }
    });      
  }



uploadLocation() {   
    let position = {
      latitude: this.lat,
      longitude: this.long,
      city: this.city
    }  
    this._us.updateUserIndividual(position).then(data => {      
      console.log("USER UPDATED");
    }).catch((err) => {
      this.presentToast("Ups! Ha ocurrido un Error, intentalo otra vez");
    })
  }

I've tried add this.decodeCoord(this.lat, this.long); on uploadLocation but it doesnt function also.

The city is always empty.

Poul Kruijt
  • 58,329
  • 11
  • 115
  • 120
SDLUJO
  • 133
  • 1
  • 8

1 Answers1

1

The this.city is empty because you are assigning it inside a separate this context. You created this new context when you defined this.geocoder.geocode(), and used the function keyword to create the callback function. Replace this with an arrow function, and I suppose you are fine again:

this.geocoder.geocode({'latLng': latlng}, (results, status) => {
  // ...
});

But I could not have been more wrong.

this.decodeCoord(this.lat, this.long);
alert(this.city);

That is not going to work. Because the callback function I made you change is, as the name suggest, an async function. So best you could do is return a Promise from the decodeCoord method:

decodeCoord(lat, long) {    
  return new Promise((resolve, reject) => {
    // ...
    this.geocoder.geocode({'latLng': latlng}, (results, status) => {
      if (status == google.maps.GeocoderStatus.OK) { 
        // ...
        resolve();
      } else {
        reject();
      }
    });
  });
}

And then you are not even there yet, you also need to return the promise from your updateLocation method:

return this._us.updateUserIndividual(position).

Then you can change your tryGeolocation method:

async tryGeolocation() {   
  try {
    const { coords } = await this.geolocation.getCurrentPosition();
    this.lat = coords.latitude;
    this.long = coords.longitude;          

    await this.decodeCoord(coords.latitude, coords.longitude);
    alert(this.city);
    await this.uploadLocation(); 
  } catch (e) {
    console.log('Error getting location', e);
  }  finally {
    this.loading.dismiss();  
  }
}

And you are done, with a nice sequential async await result

Poul Kruijt
  • 58,329
  • 11
  • 115
  • 120
  • Thank you soo much @pierreDuc I've implemented that and it functions very well – SDLUJO Sep 07 '18 at 08:58
  • how can I Know where the code breaks exactly ? in this case I want to Know what line with await fails , is there any solution to know that ? – SDLUJO Sep 10 '18 at 13:38
  • The stack trace will show you that. Just change the console.log to console.error. And there will be a stacktrace in the console – Poul Kruijt Sep 10 '18 at 14:17