谷歌地图地方自动完成addEventListener不起作用

问题描述:

我一直在尝试在离子2项目中添加谷歌地图自动完成以更新用户位置。但是,addEventListener似乎没有工作,没有控制台错误,任何人都可以告诉我哪里出错了?

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

index.html

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

你可以使用arrow函数保留 ChangeDetectionRef 以检测更改,因为谷歌地图事件是在角度区域之外触发的:

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(); 返回Object ,所以你可以得到如下地址:

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

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

Plunker示例

Plunker Example