Custom code - Wait for library to load

Hi,

have custom code in an add form that displays an editbox that is linked to googles autocomplete. works perfectly, only thing at times get the good old:
washroomsadd:1605 Uncaught TypeError: Cannot read properties of undefined (reading ‘Autocomplete’)

with the load of:
var autocomplete = new google.maps.places.Autocomplete(element, options);

have to refresh the page a few times then it kicks in correctly.

is there anyway to wait for new google.maps.places.Autocomplete()?

loadjs.ready("load", function () {
    // Startup script
        var element = document.getElementById("user_input_autocomplete_address");
                    if (element) {
                        const options = {
                            componentRestrictions: { country: "ca" },
                                fields: ["photo", "wheelchair_accessible_entrance", "address_components", "formatted_address", "geometry", "icon", "name", "opening_hours", "formatted_phone_number", "vicinity", "place_id", "type", "website", "business_status"]
};

**var autocomplete = new google.maps.places.Autocomplete(element, options);**
google.maps.event.addListener(autocomplete, 'place_changed', onPlaceChanged);
}        

Thanks!

If you use add Google Maps yourself, make sure you add your callback, e.g.

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

then change your function to initAutocomplete, e.g.

loadjs.ready(["load", , function () { ... });

// =>

window.initAutocomplete = function () { ... };

thanks for this… using the pre-generated phpMaker code..

havent’t looked at this project for a while, or the google settings in phpMaker, but noticed there is now a separate line for the “libraries” to include… i noticed in the code the loads were being duplicated as I had the libraries also on the line apikey line.

I removed them and the library seems to be calmer and not firing the load error… so far