Google maps autocomplete error dynamic loading

Viewed 31

I'm loading the Google Maps dynamically through javascript to allow for language selection. I noticed some strange behaviour however when switching languages.

The javascript is loaded as follow:

 function loadScript(lang) {
        document.querySelectorAll('script[src^="https://maps.googleapis.com"]').forEach(script => {
            script.remove();
        });
        
        if (google) {
            google.maps.event.clearListeners(autocomplete, 'place_changed');
            delete google.maps;
        }

        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://maps.googleapis.com/maps/api/js?key=xxx&libraries=places&callback=initAutocomplete';
        script.src += '&language=' + lang;
        script.id = "google-maps-script";
        document.body.appendChild(script);
    }

The script is initially triggered during the window.onload() and later when a user selects a different language in a dropdown. The old script unloads and the new language is used to load the new one.

Everything works fine, except is this usercase:

  1. Script is loaded through window.onload()
  2. The user doesn't use the autocomplete search box, but immediately changes the language and reloads the script
  3. The user tries to look up an address, the error occurs

If the user searches an address first, and then changes the language and searches again, there is no error.

The error is:

Uncaught TypeError: e.Rz is not a function
at Object.c [as _46nw80] (common.js:115:253)
at AuthenticationService.Authenticate?1shttps%3A%2F%2Fwww.url.com&4skey&callback=_xdc_._46nw80&key=key&token=127529:1:28

To summarise:

  1. So if the page load and the user looks up an address through autocomplete, everything works.
  2. If the user searches for an address, switches the language, searches again, everything still works.
  3. If the user loads the page, switches the language without using the autocomplete, the error happens.

A minimal reproducible sample can be found below:

https://www.vetworks.be/autocomplete.htm

JSFiddle example:

https://jsfiddle.net/d2skf7tq/1/

0 Answers
Related