Mohit.B
Mohit.B

Reputation: 95

ReferenceError: google is not defined After Page Refresh

I am using Google Places API in my website for autosuggestion purpose, In First go It Works fine but when i refreshes the page on particular angular component it shows error that

ReferenceError: google is not defined

i have searched number of website but none of solution worked i have tried adding async and defer in script tag in index.html but doesn't works

register.component.ts

declare var google: any;
export class RegisterComponent implements AfterViewInit {
   constructor() { }
   ngAfterViewInit() {
      const input = <HTMLInputElement>document.getElementById('googlePlaces');
      const autocomplete = new google.maps.places.Autocomplete(input, { types: ['geocode'] });
      google.maps.event.addListener(autocomplete, 'place_changed', () => {
       this.place = autocomplete.getPlace();
      })
   }
}

register.component.html

<input id="googlePlaces" type="text" class="input-custom" formControlName="location" placeholder="Enter Place">

and I have added script in main index.html file with valid API key which seems to be okay as it works in first go

Upvotes: 1

Views: 1005

Answers (2)

Thomaz Diogo
Thomaz Diogo

Reputation: 1

You can try:

let listen; 
    this._mapsAPILoader.load().then(() => {
      let autocomplete = new  google.maps.places.Autocomplete(document.getElementById('autocompleteInput'), {});
      listen = google.maps.event.addListener(autocomplete, 'place_changed', () => {
        this._ngZone.run(() => {
          const place = autocomplete.getPlace();
          ...
       });
     ...
   });
...
        google.maps.event.removeListener(listen); // then you can reload autocomplete without problens

Upvotes: 0

andrea06590
andrea06590

Reputation: 1299

You are not using the proper way to initialize google map in angular

Look at this code and you'll find your happiness on Google :)

this._mapsAPILoader.load().then(() => {
      let autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocompleteInput'), {});
      google.maps.event.addListener(autocomplete, 'place_changed', () => {
        this._ngZone.run(() => {
          const place = autocomplete.getPlace();
          ...
       });
     ...
   });

mapsAPILoader and ngZone must be added into the constructor

 constructor(
      private _mapsAPILoader: MapsAPILoader,
      private _ngZone: NgZone) { }

Don't hesitate to vote if it helps ;)

Upvotes: 3

Related Questions