'InvalidValueError: initAutocomplete is not a function Google Places and Autocomplete API

Hope you can help as I've hit a wall, I'm also quite new to using Google's Places APIs.

I'm not going to post any code just yet as my code works fine when the 2 pieces I am about to describe run in isolation.

I am using Google's Places in addition to the Autocomplete API working from the Javascript examples provided by Google.

Initially I had the following script at the bottom of my document:

<script src="https://maps.googleapis.com/maps/api/js?&libraries=places&callback=initAutocomplete" async defer></script>

and this script at the top of my document:

 <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>

This gave me the, "You have included the Google Maps API multiple times on this page. This may cause unexpected errors." so after looking into this I merged both together like this:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&callback=initAutocomplete&sensor=false"></script>

However, now that I have done this, I receive the following errors:

InvalidValueError: initAutocomplete is not a function
TypeError: searchBox is undefined

I don't receive these errors when theses scripts are not merged, but I realised afterwards that the functions requiring the Places API stopped working. If I remove the Autocomplete API reference, the Places functions work.

Any ideas on how I can make both of these work together, merging these as shown and solving the 'not a function' issue?

Any suggestions would be much appreciate, please let me know if you really need to see the code.

Thanks in advance, Steph



Solution 1:[1]

You should use include script just once, like:

//maps.googleapis.com/maps/api/js?key=__API-KEY__&libraries=places

Note that you omit the 'callback' param when including script. Then load initAutocomplete on window load like:

google.maps.event.addDomListener(window, 'load', initAutocomplete);

Maybe you would need to include gmaps script in head or you would get 'google is not defined' error, if you placed your js inline.

Solution 2:[2]

Just tried this and found that removing the asyc attribute solves this problem. Even when using the callback on the Google API URL for Places.

Removing the async attribute is a smaller fix.

Solution 3:[3]

Just remove &callback=initAutocomplete from the query and call it in the script when all will be loaded.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bobz
Solution 2 sa77
Solution 3 NSukonny