Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps Javascript API only loads data, when console is open

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. Grey map from Google Maps API

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.

Loaded data after opening the developer console

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?

like image 479
Julian Schmuckli Avatar asked Dec 06 '25 08:12

Julian Schmuckli


2 Answers

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);
});
like image 51
Nico_ Avatar answered Dec 08 '25 21:12

Nico_


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.

like image 25
Logan Young Avatar answered Dec 08 '25 23:12

Logan Young



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!