我正在尝试在我的网站中启动自定义的自动完成功能。我尝试使用Google的Places自动完成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中启用了我的地方信息库(尽管在GCP用法中我没有看到尝试实现此目的的用法。)。我没有什么错误可以用来理解问题所在,只是无法正常工作。
我尝试使用我的API密钥来使用REST API,并且它可以正常工作,但是我不想弄乱跨域请求,在这种特定情况下,我认为没有必要。
非常感谢您的协助。谢谢!
我设法解决了。显然,导致此问题的原因是一次调用Google api库和调用Google api进行地图回调。需要将其组合如下:
<script src="https://maps.googleapis.com/maps/api/js?key=[Here-I-Entered-My-API-Key]&libraries=places&callback=initMap"></script>