Multiple Google Map on single page with marker and click event

Posted on April 22, 2016 by Suresh Kamrushi in Javascript

Sharing below how we can create multiple google map in a single html page with marker and click event. I have added click event to show more detail about the marker like description, but we can also add different functionality like navigating to different page or zoom in or zoom out etc,.

Just copy and past the below code and save the file as “index.html” and open the page in browser you will see two different map with different marker and descriptions.

<html> 
 <head>
 <title>Google Maps API</title>
 <script type="text/javascript" src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
 </script>
 <script type="text/javascript">
 function initialize() { 
   var latlngNgp = new google.maps.LatLng(21.1458, 79.0882); 
   var latlngHyd = new google.maps.LatLng(17.3850, 78.4867); 
   var desNgp = "Nagpur is the second capital and the third largest city of the Indian state of Maharashtra after Mumbai and Pune. It is the 13th largest urban agglomeration in India and the largest city in Vidarbha Region."; 
   var desHyd = "Hyderabad is the capital of southern India's Telangana state. A major center for the technology industries."; 
   var ngpOptions = { 
       zoom: 15, 
       center: latlngNgp, 
       mapTypeId: google.maps.MapTypeId.ROADMAP 
   }; 
   var hydOptions = { 
       zoom: 15, 
       center: latlngHyd, 
       mapTypeId: google.maps.MapTypeId.SATELLITE 
    }; 
   var mapNgp = new google.maps.Map(document.getElementById("nagpur"), ngpOptions); 
   var mapHyd = new google.maps.Map(document.getElementById("hyderabad"), hydOptions); 
   //Adding market to map
   var markerNgp = new google.maps.Marker( { 
                      position: latlngNgp, 
                      map: mapNgp, 
                      title: "Nagpur" 
                   }); 
   var markerHyd = new google.maps.Marker( { 
                      position: latlngHyd, 
                      map: mapHyd, 
                      title: "Hyderabad" 
                   }); 
   var infoWindow = new google.maps.InfoWindow(); 
   
  //Adding click event to marker.
   markerNgp.addListener('click', function() { 
      infoWindow.setContent(desNgp); 
      infoWindow.open(mapNgp, markerNgp); 
   }); 
   markerHyd.addListener('click', function() { 
      infoWindow.setContent(desHyd); 
      infoWindow.open(mapHyd, markerHyd); 
   }); 
 }
 </script>
 </head>
 <body onload="initialize()">
 <div id="nagpur" style="margin:10px;width:510px; height:420px; float: left"></div>
 <div id="hyderabad" style="margin:10px;width:510px; height:420px"></div>
 </body>
</html

Documentation link : Google Map

  Comments or questions are welcome