Search code examples
angularionic2google-maps-autocomplete

google maps places autocomplete addEventListener doesn't work


I have been trying to add google maps places auto complete in ionic 2 project to update the user location.However, the addEventListener doesn't seems to work and there is no console errors could anyone tell me where I am going wrong?

 ngAfterViewInit() {
   let input = < HTMLInputElement > document.getElementById("auto");
   console.log('input', input);
   let options = {
     componentRestrictions: {
       country: 'IN',
       types: ['(regions)']
     }
   }
   let autoComplete = new google.maps.places.Autocomplete(input, options);
   console.log('auto', autoComplete);
   google.maps.event.addListener(autoComplete, 'place_changed', function() {
     this.location.loc = autoComplete.getPlace();
     console.log('place_changed', this.location.loc);
   });
 }
<ion-label stacked>Search Location</ion-label>
<input type="text" id="auto" placeholder="Enter Search Location" [(ngModel)]="location.loc" />

index.html

<script src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxx&libraries=places"></script>


Solution

  • You can use arrow function to retain this and ChangeDetectionRef to detect changes because google map events are fired outside angular zone:

    constructor(private cd: ChangeDetectorRef) { }
    
    google.maps.event.addListener(autoComplete, 'place_changed', () => { // arrow function
      this.location.loc = autoComplete.getPlace();
      this.cd.detectChanges(); // detect changes
      console.log('place_changed', this.location.loc);
    });
    

    autoComplete.getPlace(); returns Object, so you can get address as follows:

    var place =  autoComplete.getPlace();
    this.location.loc = place.formatted_address;
    

    Plunker Example