javascriptgoogle-maps-api-3geoxml3

Google is undefined error when using geoxml3.js and ProjectedOverlay.js to display KMZ file


I have a website that uses Google Maps API JavaScript to display a map. I also use geoxml3 and ProjectedOverlay to display a KMZ/KML file on the map.

My scripts:

<script async defer src="//maps.googleapis.com/maps/api/js?key=API_KEY_HERE&libraries=places"></script>
<script type="text/javascript" src="/js/geoXML/ZipFile.complete.js"></script>
<script type="text/javascript" src="/js/geoXML/geoxml3.js"></script>
<script type="text/javascript" src="/js/geoXML/ProjectedOverlay.js"></script>
<script src="/js/app.js"></script> 

When loading the page the errors:

Uncaught ReferenceError: google is not defined at ProjectedOverlay.js

and

Uncaught ReferenceError: google is not defined at PROJECT_NAME:115

will be thrown.

Line 115 is the following:

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

However they are not always thrown. This happens once out of maybe every 10 times I load the page.


Solution

  • The issue is that the google script is loading asynchronously. geoxml3.js and ProjectedOverlay.js require the Google Maps API to be fully connected and loaded to work.

    If loaded asynchronously one of the other JS scripts will load before the Google API has loaded, throwing an error.

    The simple solution is to remove the async defer in the Google API script:

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