简体   繁体   English

如何在Javascript中实现谷歌地图位置自动完成?

[英]How to implement google map places autocomplete in Javascript?

I am trying to implement google map place autocomplete api in my application.我正在尝试在我的应用程序中实现google map place autocomplete api。 My code is as below-我的代码如下-

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

    <script type="text/javascript">
        function autoAddress() {
            console.log('here');
            var input = document.getElementById('auto-address');
            var autocomplete = new google.maps.places.Autocomplete(input);
            console.log(autocomplete);
        }

        google.maps.event.addDomListener(document.getElementById('auto-address'), 'keypress', autoAddress);

    </script>

<input class="form-control" name="address" id="auto-address" type="text" placeholder="Address Details etc.">

</body>

I am trying to give suggestions on addresses on keypress event after user presses each character in the input field like below image in official documentation-在用户按下输入字段中的每个字符后,我试图就按键事件的地址提供建议,如下图官方文档中所示 -

在此处输入图片说明

But I am facing following error in my console-但是我在控制台中遇到了以下错误-

Uncaught (in promise), message: "autoAddress is not a function", name: "InvalidValueError".未捕获(承诺),消息:“autoAddress 不是函数”,名称:“InvalidValueError”。

What should I do to solve this?我该怎么做才能解决这个问题? An example code will be much appreciated for reference.示例代码将不胜感激以供参考。

It seems I have found my solution.看来我找到了我的解决方案。 The issue was in the line-问题出在这条线上——

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

I was following some an example from a blog that I cant remember where it said to use a callback function as the request parameter.我正在关注博客中的一些示例,我不记得它在哪里说使用回调函数作为请求参数。 When I removed the parameter from the script src I dont know why, but it worked!当我从脚本 src 中删除参数时,我不知道为什么,但它起作用了!

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

If anyone could explain the reason it would be really helpful for me though.如果有人能解释原因,那对我来说真的很有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM