google maps places autocomplete addEventListener doesn't work

萝らか妹 提交于 2019-12-24 09:48:40

问题


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>

回答1:


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




回答2:


Try by checking place_changed event on autoComplete with below component :

import {Component, ViewChild, ChangeDetectorRef} from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <div>      
      <input #auto />
      {{ location?.formatted_address | json}}
    </div>
  `,
})
export class App {
  @ViewChild('auto') auto:any;

  location: any;

  constructor(private ref: ChangeDetectorRef) {
  }

  ngAfterViewInit(){
    let options = {
      componentRestrictions: {
        country: 'IN'
      }
    };
    let autoComplete = new google.maps.places.Autocomplete(this.auto.nativeElement, options);

    console.log('auto', autoComplete);

    autoComplete.addListener('place_changed', () => {
      this.location = autoComplete.getPlace();
      console.log('place_changed', this.location);
      this.ref.detectChanges();
    });
  }
}

As place_changed is triggeres outside angular js we need to trigger angular change detection with ChangeDetectorRef manually.



来源:https://stackoverflow.com/questions/40993843/google-maps-places-autocomplete-addeventlistener-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!