【发布时间】:2020-04-16 19:39:01
【问题描述】:
我正在尝试在我的网站中启动自定义的自动完成功能。我尝试使用 Google 的地点自动完成 API 来实现这一点。 我希望首先将预测输出到日志中以验证它是否正常工作,但它似乎没有进入回调函数,并且我没有收到任何错误消息。无。
我首先添加了 Google 地方信息库:
<script src="https://maps.googleapis.com/maps/api/js?key=[Here-I-Entered-My-API-Key]&libraries=places"></script>
之后我尝试了多种选择:
-
起初我尝试使用简单的自动完成请求来查看任何结果。我输入了以下代码:
let searchInput = $( ".search-input" )[0]; autocomplete = new google.maps.places.Autocomplete(searchInput, { types: ["address"] });
这样做没有任何结果,它没有显示自动完成选项。
-
在我的第二次尝试中,我尝试使用 AutocompleteService 来实现我最初想要的预测并将其打印在控制台日志中。我输入了以下代码:
// Create a new session token. let sessionToken = new google.maps.places.AutocompleteSessionToken(); // Pass the token to the autocomplete service. let autocompleteService = new google.maps.places.AutocompleteService(); autocompleteService.getPlacePredictions( { input: "Mitt", type: ["address"], componentRestriction: {country: 'de'}, sessionToken: sessionToken }, function (predictions, status) { console.log("Query resulted in -> " + status); console.log("Received " + predictions.length + " predictions"); for(let prediction of predictions){ console.log(prediction); console.log(prediction.description); } } );
只是为了验证它是否向我显示了一个结果,但看起来它并没有到达我的回调函数。
我尝试从我在网上看到的其他用法中复制示例,但也没有用。我不明白发生了什么事。 我的 API 密钥是可用的,我已经在 GCP 中启用了我的 Places 库(尽管我没有看到在 GCP 使用中尝试实现这一点的用法。)。 没有任何错误可以用来理解问题可能是什么,它只是不起作用。
我尝试使用我的 API 密钥来使用 Places REST API,它可以工作,但我不想搞乱跨域请求,我认为在这种特定情况下没有必要这样做。
非常感谢您的帮助。 谢谢!
【问题讨论】:
-
您应该提交支持案例。
标签: javascript html google-maps google-places-api googleplacesautocomplete