I am trying to display a map on my page, which sets a marker.
What's my problem
The map instance works without any problems. There is no error in the console or from Google at self. But unfortunately, the map data is not loading. I just get the Google logo and a grey background, as you can see on the picture.

Then, when I open the console of Google Chrome, it loads the map data and it display me the map with the requested map type.

What I tried
I searched in the internet, found some other problems like the grey box, but the solution doesn't help me.
Right 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 someone help me?
It's not perfect but you can try to force the resize when the maps is 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);
});
You Shouldn'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 is waiting for you to "load" the DOM so is waiting for you to open teh Console before loading the map.
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