While geocoding stuck


#1

chooseItem(item: any) {
this.address = item;
let data = this.geocodeAddress();
console.log(data);
//how to get or console lat value;
//how to get or console lng value;
}

geocodeAddress(){
var loc= [];
this.geocoder.geocode({‘address’: this.address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
loc[‘lat’] = results[0].geometry.location.lat();
loc[‘lng’] = results[0].geometry.location.lng();
} else {
console.log('Geocoder failed due to: ’ + status);
}
});
return loc;
}


#2

Geocoder.geocode is asynchronous, so you’ll need to code reactively. I’d propose something like this:

chooseItem(item: any) {
  this.address = item;
  this.geocodeAddress().then(data => {
    console.log(data);
    console.log("latitude", data.lat);
    console.log("longitude", data.longitude);
  });
}

geocodeAddress() {
  return this.geocoder.geocode({'address': this.address}, (results, status) => {
    if (status == google.maps.GeocoderStatus.OK) {
      return {
        lat: results[0].geometry.location.lat(),
        lng: results[0].geometry.location.lng()
      };
    }

    console.log('Geocoder failed due to: ' + status);
    return { lat: 0, lng: 0 }; //Whatever your sane defaults would be
  });
}

#3

I tried your code but it is giving property then does not exist on type void error


#4

Ah. I thought it was the Ionic Native geocoder, which I’d recommend using. You can find it here.

Anyway, you’ll want to do something like this:

geocodeAddress() {
  return new Promise((resolve, reject) => {
    this.geocoder.geocode({'address': this.address}, (results, status) => {
      if (status == google.maps.GeocoderStatus.OK) {
        resolve({
          lat: results[0].geometry.location.lat(),
          lng: results[0].geometry.location.lng()
        });

        return;
      }
  
      console.log('Geocoder failed due to: ' + status);
      reject(status);
    });
  });
}

#5

sorry for the trouble but I have been working on this for several hours but could do it right. Now the code does not find lat and lng it says property lat does not exit