Skip to content
Advertisement

How to implement google map places autocomplete in Javascript?

I am trying to implement google map place autocomplete api in my application. 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-

enter image description here

But I am facing following error in my console-

Uncaught (in promise), message: “autoAddress is not a function”, name: “InvalidValueError”.

What should I do to solve this? An example code will be much appreciated for reference.

Advertisement

Answer

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!

<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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement