Search code examples
javascripthtmlgoogle-maps

GoogleMaps API working only when dev tools is open


Hey I am trying to have a map in my project. I got my API_KEY from google for GoogleMaps... I have no error in console but map doesnt display anything, till I open developers tools on google Chrome...

enter image description here2

After that is working but marker is in work palce.. Still no errors in console.

enter image description here

WHat am I doing wrong?

Style:

#map {
 width: 100%;
 height: 300px;
 background-color: grey;
}

Code:

<div id="map"></div>
 <script>
   function initMap() {
   var myLatLng = {lat: -0.250608, lng: 52.025528};

   var map = new google.maps.Map(document.getElementById('map'), {
   zoom: 4,
   center: myLatLng
   });

   var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: 'Title!'
    });
  }
 </script>
 <script async defer
   src="https://maps.googleapis.com/maps/api/js?key=MYKEY&callback=initMap">
 </script> 

Solution

  • You are init-ing the map in a container that is not visible/has no dimensions.

    Opening dev tools triggers a resize on your browser which causes the map to resize itself.**

    You can fix it by either:

    either waiting to init the map until it's container is visible

    or calling google.maps.event.trigger('resize',map) (where map is an instance of the map) when your container becomes visible.

    ** Proof that this is what's happening: undock your dev tools so it's a floating window. Then refresh your page (with dev tools closed) and open dev tools again after you fail to see the map, it still won't be visible because your browser never resized (because your dev tools is floating and not docked)