gpt4 book ai didi

angular - google maps places autocomplete addEventListener 不起作用

转载 作者:行者123 更新时间:2023-12-05 03:10:09 24 4
gpt4 key购买 nike

我一直在尝试在 ionic 2 项目中添加 google maps places auto complete 以更新用户位置。但是,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" />

index.html

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

最佳答案

您可以使用箭头函数来保留 thisChangeDetectionRef 来检测更改,因为 google map 事件是在 Angular 区域之外触发的:

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 Example

关于angular - google maps places autocomplete addEventListener 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40993843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com