Search code examples
angularreverse-geocodingangular-google-maps

Reverse geocoding in angular google maps


getAddress( lat: number, lng: number ) {
    console.log('Finding Address');
    if (navigator.geolocation) {
      let geocoder = new google.maps.Geocoder();
      let latlng = new google.maps.LatLng(lat, lng);
      let request = { latLng: latlng };
      geocoder.geocode(request, (results, status) => {
        if (status === google.maps.GeocoderStatus.OK) {
          let result = results[0];
          let rsltAdrComponent = result.address_components;
          let resultLength = rsltAdrComponent.length;
          if (result != null) {
            this.address = rsltAdrComponent[resultLength - 8].short_name;
          } else {
            alert('No address available!');
          }
        }
      });
  }
  }

I am trying to use reverse geocoding in my angular 4 application. I am using agm for integrating google map with the angular app.

Declared google variable in *.ts as follows

declare let google: any;

But when I am using I am getting the error as follows,

ERROR ReferenceError: google is not defined

Please help me to resolve the issue.

Here is the component.ts

declare let google: any;
@Component({
  selector: 'app-find-cycle',
  templateUrl: './cmp.component.html',
  styleUrls: ['./cmp.component.scss']
})

export class Cmp {
}

Solution

  • execute getAddress() after the map is loaded:

    <agm-map (mapReady)="mapReady()" [latitude]="lat" [longitude]="lng" [zoom]="zoom" [styles]="styles">
    
    mapReady() {
        this.getAddress(...);
    }
    

    or add private mapsAPILoader: MapsAPILoader, to your constructor do this

     this.mapsAPILoader.load().then(() => { ... });