gpt4 book ai didi

asynchronous - 加载 Google Places 自动完成异步 Angular 2

转载 作者:太空狗 更新时间:2023-10-29 18:21:32 25 4
gpt4 key购买 nike

我正在尝试在 Angular 2 组件中实例化 Google Places 自动完成输入。我使用这段代码来做到这一点:

loadGoogle() {
let autocomplete = new google.maps.places.Autocomplete((this.ref.nativeElement), { types: ['geocode'] });
let that = this
//add event listener to google autocomplete and capture address input
google.maps.event.addListener(autocomplete, 'place_changed', function() {
let place = autocomplete.getPlace();
that.place = place;
that.placesearch = jQuery('#pac-input').val();
});
autocomplete.addListener()
}

我相信,通常情况下,我会使用 Google API 提供的回调函数来确保在此函数运行之前加载它,但我无法在组件范围内访问它。我能够在 90% 的时间内加载自动完成输入,但在较慢的连接上,我有时会出错

google is not defined

有没有人想出如何确保在实例化之前将 Google API 加载到组件中。

最佳答案

不确定这是否有帮助,但我只是在我的 index.html 中使用一个简单的脚本标记来加载 Google API,而且我从未收到任何错误。我相信你也会这样做。我在这里发布我的代码,希望它能有所帮助。

注意:我使用 Webpack 来加载除 Google Map API 之外的其他脚本。

<html>
<head>
<base href="/">
<title>Let's Go Holiday</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Google Map -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<your-key>&libraries=places"></script>
</head>

<body>
<my-app>Loading...</my-app>
</body>
</html>

然后在你的组件中:

...
declare var google: any;

export class SearchBoxComponent implements OnInit {

ngOnInit() {
// Initialize the search box and autocomplete
let searchBox: any = document.getElementById('search-box');
let options = {
types: [
// return only geocoding results, rather than business results.
'geocode',
],
componentRestrictions: { country: 'my' }
};
var autocomplete = new google.maps.places.Autocomplete(searchBox, options);

// Add listener to the place changed event
autocomplete.addListener('place_changed', () => {
let place = autocomplete.getPlace();
let lat = place.geometry.location.lat();
let lng = place.geometry.location.lng();
let address = place.formatted_address;
this.placeChanged(lat, lng, address);
});
}
...
}

关于asynchronous - 加载 Google Places 自动完成异步 Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37312081/

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