I have a separate label.js file in which I have defined a custom overlay. It uses the google.maps.OverlayView as its prototype:
Label.prototype = new google.maps.OverlayView();
I am not sure where to place the script tags for this js file in my index.html file. If I place the script tags below the google maps loading tag like so:
....
<script async defer
src="https://maps.googleapis.com/maps/api/js?...
</script>
<script src="js/label.js"></script>
</body>
</html>
The label.js file is loaded immediately while the maps api has not yet loaded causing an error.
I currently solve this by manually loading the JS in my maps loaded callback:
function initMap() {
gMap = new google.maps.Map(document.getElementById(strMapDivName), {
center: {lat: 21, lng: 78},
mapTypeId: google.maps.MapTypeId.HYBRID,
zoom: 6,
heading: 90,
tilt: 0
});
// Load label.js afterwards so we can be sure that the google maps api has loaded
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", "js/label.js")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
Is this the best way to solve this?
I know it's too late, but I use this code below
var mapWaitCount = 0;
var mapWaitMax = 5;
function map_load(param1, param2, ...) { // if you need any param
mapWaitCount++;
// if api is loaded
if(typeof google != 'undefined') {
// your code here
}
// try again if until maximum allowed attempt
else if(mapWaitCount < mapWaitMax) {
console.log('Waiting attempt #' + mapWaitCount); // just log
setTimeout(function() { map_load(); }, 1000);
}
// if failed after maximum attempt, not mandatory
else if(mapWaitCount >= mapWaitMax) {
console.log('Failed to load google api');
}
}
map_load(param1, param2, ...) { // if you need any param
It uses timeout to wait for the load, and after several attempts it will be stopped
You should include a callback function in the API call.
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=myFunction"></script>
You can then include any maps related code within the callback function:
function myFunction() {
// Your code here
}
If you need to wait until the map is "ready" ie, the map is displayed with the map options and "idle" you can use:
google.maps.event.addListenerOnce(map, 'idle', function () {
// map is ready
});
But you should still include this within the callback function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With