1

我一直在尝试在 ionic 2 项目中添加谷歌地图位置自动完成以更新用户位置。但是,addEventListener 似乎不起作用,并且没有控制台错误,谁能告诉我哪里出错了?

 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" />

索引.html

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

4

2 回答 2

1

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

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,所以可以得到地址如下:

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

Plunker 示例

于 2016-12-06T11:47:58.397 回答
0

尝试使用以下组件检查place_changed事件:autoComplete

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();
    });
  }
}

与角度 js 外部的触发器一样,我们需要手动place_changed触发角度变化检测。ChangeDetectorRef

于 2016-12-06T11:30:14.780 回答