Search code examples
javascriptfirebasefirebase-realtime-databasegoogle-geocoder

Firebase update in a Google Geocode async method


I am trying to write a method that updates my Firebase database after the geocode function finishes. I am writing the code in Angular2 so my Firebase database is defined in my constructor. I understand that the issue is with asynchronous functions, but I am unsure on how to go about this. Here is my code:

geocoding(callback){
var geocoder = new google.maps.Geocoder();
  geocoder.geocode({'address': this.loc}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      callback([results[0].geometry.location.lat(), results[0].geometry.location.lng()]);
    } else {
      this.lat = 0;
    }
  });  
}

and:

geocode(){
this.geocoding(function(latLng){
  this.db.object('users/' + this.auth.id).update({
    lat: latLng[0],
    lng: latLng[1]
  });
});
}

Solution

  • I figured out how to do it. Turns out you need to use promises, here is the working code:

    geocode(address){
        return new Promise(function(resolve,reject){
          var geocoder = new google.maps.Geocoder();
            geocoder.geocode({'address': address}, function(results, status) {
              if (status == google.maps.GeocoderStatus.OK) {
                resolve(results);
              } else {
                this.lat = 0;
              }
            });
          });
      }
    

    and:

      this.geocode(this.loc).then(results => {
          this.db.object('users/' + this.auth.id).update({
            lat: results[0].geometry.location.lat(),
            lng: results[0].geometry.location.lng()
          });
        });