Google Maps Javascript API only load data when console is open
I am trying to display a map on my page that sets a marker.
What's my problem
The card instance works without issue. There is no error on console or google. Unfortunately, the map data is not loaded. I just get google logo and gray background as you can see in the picture.
Then when I open the Google Chrome console it downloads the map data and displays the map to me with the requested map type.
What i tried
I searched on the internet, found some other problems like gray box, but the solution doesn't help me.
Now my code looks like this:
<div id="map" style="width:100%;height:400px;"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap"></script>
<script>
function initMap() {
//Just some example coordinates
var lat = 47.8;
var lon = 8.9
var location = {lat: lat, lng: lon};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: location,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: location,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initMap);
</script>
Can anyone help me?
source to share
It's not ideal, but you can try to force the resize when the maps are loaded:
google.maps.event.addListenerOnce(map, 'idle', function(){
$(window).trigger('resize');
});
Or without jQuery:
google.maps.event.addListenerOnce(map, 'idle', () => {
const event = new Event('resize');
window.dispatchEvent(event);
});
source to share
You don't need to add a DOM listener. The map should just load with this script:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&callback=initMap">
</script>
and the initMap function.
EDIT: The DOM listener expects you to "load" the DOM, so wait for you to open the Console before loading the map.
source to share