X

Headline

This is an important message requiring you to make a choice if you're based in the EU.

How to dynamically load Google Maps

Sometimes you need to load the Google Maps dynamically, and when you try to do it, you meet some problems, and you don't know how to fix them. Here is a way how you can dynamically load Google Maps.

The solution is: You can init your map in a simple form, how you usually do and you must make that map invisible.

<!DOCTYPE html>
<html>
   <head>
      <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA3XfuMJJGzaU8TUItQM7XWD4esZdbpgtA"></script>
      <script>
         function initialize() {
           var prop = {
            center:new google.maps.LatLng(51.508742,-0.120850),
            zoom:5,
            mapTypeId:google.maps.MapTypeId.ROADMAP
           };
          var map=new google.maps.Map(document.getElementById("w3docs-map"), prop);
         }
         google.maps.event.addDomListener(window, 'load', initialize);
      </script>
   </head>
   <body>
      <div id="w3docs-map" style="width:500px;height:380px;"></div>
   </body>
</html>

Now let's make the map invisible, putting on it CSS style display: none. Then we will make an action to load the map by any Event.

<!DOCTYPE html>
<html>
   <head>
      <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA3XfuMJJGzaU8TUItQM7XWD4esZdbpgtA"></script>
      <script>
         var map;
         function initialize() {
           var prop = {
            center:new google.maps.LatLng(51.508742,-0.120850),
            zoom:5,
            mapTypeId:google.maps.MapTypeId.ROADMAP
           };
          return new google.maps.Map(document.getElementById("w3docs-map"), prop);
         }
         setTimeout(function(){
            map = initialize();
         },500);
         function w3Load(){
            document.getElementById("w3docs-map").style.display = 'block';
            google.maps.event.trigger(map, 'resize');
         }
      </script>
   </head>
   <body>
      <div id="w3docs-map" style="width:500px;height:380px;display: none"></div>
      <button onclick="w3Load()">Load The Map</button>
   </body>
</html>

Do you find this helpful?

Related Resources


Related articles