Adding Google Map in web page using Javascript

Author - Richa

How to add Google Map in your project and show markers and InfoWindows for various locations using HTML and Javascript.

Google Map API is one of the most used APIs in websites and projects. We can use the API to show maps on a webpage. The API is basically a Javascript library which can be included in the web-page using <script> tag. For accessing the API, developers are required to have a free API key generated by google for their project. Visit https://console.developers.google.com for generating the free API key. Most importantly, enable the Google MAP Javascript API after creating the key for your project without which the map will not work.

In order to include the API in your project, below is sample code (go through the comments to understand purpose of pieces of code):

<!DOCTYPE html>

 <html>

  <head>

    <style>

     .containerDiv { 

        position: relative;

        height: 100%;

      }

      html,

      body {

   margin: 0;

         padding: 0;

         font-family: Georgia, sans-serif;

         height: 100%;

      }

    #map {

        bottom:0px;

        height: 100%;

        left: 0px;

        position: absolute;

        right: 0px;

      }

    </style>

   </head>

  <body>

  <div class="containerDiv">

<div id="map"></div>

  </div>

   <script>

      var map;

      var markers = [];

      function initAutocomplete() {

        // Constructor creates a new map using following required fields

        map = new google.maps.Map(document.getElementById('map'), {

         //center is the initial center of the map, 'lat' and 'lng' fields contain latitude and longitude values of a location

          center: {lat: 40.7413549, lng: -73.9980244}, 

          zoom: 13  // an integer value specifying the initial map zoom level.

        });

       

//uncomment following block to place a single marker on a location (just to understand the process of creating a marker and its infoWindow). Make sure to comment rest of the code till end of this function

 

/* var myLoc = {lat: 40.7413549, lng: -73.9980244};

         var marker = new google.maps.Marker({

position : myLoc,

map : map,

title : 'Test Marker'

});

var infowindow = new google.maps.InfoWindow({

content : "Health Care Center"

});

marker.addListener('click',function(){

infowindow.open(map,marker);

});

*/

//create an array of various locations with their respective lats and longs to be shown on map

var locations = [

{title : ' ABC Sweets' ,  location : {lat : 40.7713024,lng : -73.9632393}},

{title : 'XYZ Sweets' , location : {lat : 40.7444883,lng : -73.9949465}},

{title : 'Local Post Office' ,  location : {lat : 40.7347062,lng : -73.9895759}},

{title : 'Children\'s Park' , location : {lat : 40.7281777,lng : -73.984377}},

{title : 'Local Service Center' ,  location : {lat : 40.7195264,lng : -74.0089934}}

];

//InfoWindow() method creates a popup window showing details of that location when clicked on a marker


var popupInfoWindow = new google.maps.InfoWindow();

//LatLngBounds constructor creates a rectangular boundary for a location using Lat Long points

var bounds = new google.maps.LatLngBounds();

//the loop uses the locations array to create an array of markers on initialize.

for(var i=0; i<locations.length;i++){

//get the position from the location array

var position = locations[i].location;

var title = locations[i].title;

//create a marker per location and add them in markers array

var marker = new google.maps.Marker({

map : map,

position : position,

title : title,

animation : google.maps.Animation.DROP, // animation to display markers in a unique way

id : i

});

//push the marker array to array of markers

markers.push(marker);


//extend the boundaries of the map for each marker

bounds.extend(markers[i].position);


//create an onclick event for each marker to open an infowindow

marker.addListener('click',function(){

openInfoWindow(this,popupInfoWindow);

});

}

//adding bounds for each position in fitBounds method to set the viewport

map.fitBounds(bounds);  

}

    

      //the function will populate infoWindow for each marker when clicked

      

      function openInfoWindow(marker, infoWindow){

       //check if an infowindow is not already opened for this marker

if(infoWindow.marker != marker){

infoWindow.marker = marker;

infoWindow.setContent('<div>' + marker.title + '</div>');

infoWindow.open(map,marker);

//clear marker porperty if infowindow is closed.

infoWindow.addListener('closeclick',function(){

infoWindow.setMarker(null);

});

}

  

      }

  

  

    </script>

//Generate the free API key and add it in key parameter. The callback function specified below will be called when the API is loaded.  

//defer attribute instructs the browser to execute the script when the whole page is loaded.

//async attributes instructs the browser to fetch the script asynchronously meaning executing the script as soon as it is retrieved

    <script async defer     src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&v=3&callback=initAutocomplete">

    </script>

  </body>

</html>
Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *

Send your message