Google Maps JavaScript API

Introduction

It would be great fun to use and work with the Google Maps JavaScript API.

In this article I've created a simple navigation panel that looks and works like Google Maps. Of course there will be some difference in design but the functionality will be the same as in Google Maps.

First of all, all you need is a Google Maps JavaScript API to proceed in this project.

Go to this link and obtain you own personal API key.

Google Maps

Here from the preceding link use the procedure described there and you can get your own API Key.

Now all you need to do is to create your own design. The following is the screen shot of the template I designed.

template

Now please find the code below.

Home.html

  1. <!DOCTYPE HTML>  
  2. <html>  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
  5. <title>Google Maps</title>  
  6. <link rel="stylesheet" href="css/style.css" type="text/css">  
  7. <!--Deploy Script For Google Maps API-->  
  8.  <script type="text/javascript"  
  9.       src="https://maps.googleapis.com/maps/api/js?key=YOUR_OWN_API_KEY &sensor=true">  
  10.     </script>  
  11. <!--API Deployment Script Ends Here-->  
  12. <!-- deploy this script AFTER the maps api-->  
  13.    
  14.     <script src="scripts/google-maps-3-vs-1-0.js" type="text/javascript"></script>  
  15.     <!--Deployments Ends-->  
  16.     <script type="text/javascript" src="javascript/mainJavaScript.js"></script>  
  17.     <script type="text/javascript">  
  18.         function myfunction(cc) {  
  19.    
  20.             var locations = cc;  
  21.             for (i = 0; i < locations.length; i++) {  
  22.                 var map = new google.maps.Map(document.getElementById('map_canvas'), {  
  23.                     zoom: 14,  
  24.    
  25.                     center: new google.maps.LatLng(locations[i][1], locations[i][2]),  
  26.                     mapTypeId: google.maps.MapTypeId.ROADMAP  
  27.                 });  
  28.             }  
  29.             var infowindow = new google.maps.InfoWindow();  
  30.    
  31.             var marker, i;  
  32.    
  33.             for (i = 0; i < locations.length; i++) {  
  34.                 marker = new google.maps.Marker({  
  35.                     position: new google.maps.LatLng(locations[i][1], locations[i][2]),  
  36.                     map: map  
  37.                 });  
  38.    
  39.                 google.maps.event.addListener(marker, 'click', (function (marker, i) {  
  40.                     return function () {  
  41.                         infowindow.setContent(locations[i][0]);  
  42.                         infowindow.open(map, marker);  
  43.                     }  
  44.                 })(marker, i));  
  45.             }  
  46.         }  
  47.           
  48.     </script>  
  49. <script src="javascript/style_script.js" type="text/javascript"></script>  
  50. </head>  
  51.    
  52. <body onLoad="initialize()">  
  53.    <div class="main">  
  54.       <header>  
  55.          <div id="search_cnt">  
  56.    
  57.             <center>  
  58.                <table id="tab">  
  59.                   <tr>  
  60.                      <th><input type="text" class="text_box" value="Enter Place To Search" id="search" onBlur="onblur_js()" onFocus="onfocus_js();" /></th>  
  61.                      <th><input type="button" class="btn_box" onClick="initialize()"  value="Search"/></th>  
  62.                   </tr>  
  63.                </table>  
  64.             </center>  
  65.          </div>  
  66.       </header>  
  67.       <aside id="cnt1">  
  68.       <div>  
  69.          <center>  
  70.             <p><label title="Directions" class="label_font">Directions</label></p>  
  71.                <table style="margin-top:30px;">  
  72.                <tr>  
  73.                   <td><img src="images/start.png" height="25px" width="25px"/></td>  
  74.                      <td>  
  75.                         <input type="text" class="text_box" value="Choose start point" onBlur="st_blur_js()" onFocus="st_focus_js()" id="first_location"/>  
  76.                      </td>  
  77.                   </tr>  
  78.                <tr>  
  79.                <td><img src="images/dest.png" height="25px" width="25px" /></td>  
  80.             <td>  
  81.                <input type="text" class="text_box" value="Choose end Point" onBlur="en_blur_js()" onFocus="en_focus_js()" id="second_location"/>  
  82.             </td>  
  83.          </tr>  
  84.          <tr>  
  85.          <th colspan="2">  
  86.             <select id="dirtype" class="drop_list" style="font-family:'Comic Sans MS', cursive">  
  87.             <option value="1">Driving</option>  
  88.             <option value="2">Walking</option>  
  89.             <option value="3">Transit</option>  
  90.          </select>  
  91.       </th>  
  92.    </tr>  
  93.    <tr>  
  94.       <th colspan="2"><input type="button" class="btn_box" value="Find Direction" id="getDirection" onClick="calcRoute()"/></th>  
  95.    </tr>  
  96.    </table>  
  97. </center>  
  98. </div>  
  99. <div  style="overflow:auto; max-height:250px">  
  100.       <div id="directionsPanel"></div>  
  101.       </div>  
  102. </aside>  
  103.    
  104. <aside id="cnt2">  
  105.    <!--To print map-->  
  106.    <div id="map_canvas" style="height:100%;"></div>  
  107.    </aside>  
  108.       <footer>  
  109.    <br/>  
  110.       <center>  
  111.          © Designed By Paras Babbar. All Right Reserved: Google Custom Maps.  
  112.       </center>  
  113.       </footer>  
  114.    </div>  
  115.    
  116. </body>  
Here, replace YOUR_OWN_API_KEY with the API key you received.
  1. <script type="text/javascript"  
  2.       src="https://maps.googleapis.com/maps/api/js?key=YOUR_OWN_API_KEY &sensor=true">  
  3.     </script>  
  4.   
  5. Style.css  
  6.   
  7. @charset "utf-8";  
  8. /* CSS Document */  
  9.    
  10. body{  
  11.     background-color:#b0e0e6;  
  12. }  
  13.    
  14. /*This class belongs to the main div tag just after body tag*/  
  15. .main{  
  16.     height:auto;  
  17.     width:auto;  
  18.     background:#0F0;  
  19.     border-top:solid;  
  20.     border-left:solid;  
  21.     border-right:solid;  
  22.     border-color:#000;  
  23.     border-bottom:solid;  
  24. }  
  25.    
  26. header{  
  27.     height:100px;  
  28.     width:auto;  
  29.     background-color:#FFF;  
  30.     border-bottom:solid;  
  31.     border-color:#000;  
  32.     background-image:url(../images/title.png);  
  33. }  
  34.    
  35. /*This ID belongs to the aside one seaction*/  
  36. #cnt1{  
  37.     height:500px;  
  38.     width:300px;  
  39.     background-color:#CCC;  
  40.     float:left;  
  41.     border-right:solid;  
  42.     border-bottom:solid;  
  43. }  
  44.    
  45. /*This id belongs to the aside two section*/  
  46. #cnt2{  
  47.     height:500px;  
  48.     width:auto;  
  49.     background-color:#CCC;  
  50.     border-bottom:solid;  
  51. }  
  52.    
  53. footer{  
  54.     height:45px;  
  55. }  
  56.    
  57. /*This id belongs to the div tag placed in header section*/  
  58. #search_cnt{  
  59.     height:auto;  
  60.     width:auto;  
  61. }  
  62.    
  63. /*This ID belongs to the table section inside the div tag under header*/  
  64. #tab{  
  65.     padding-top:30px;  
  66. }  
  67.    
  68. /*This class is uder to decorate text box*/  
  69.    
  70. .text_box{  
  71.     border:1px solid #999;  
  72.     width:200px;  
  73.     height:20px;  
  74.     color:#03F;  
  75.     font-family:"Comic Sans MS", cursive;  
  76. }  
  77.    
  78. .text_box:focus{  
  79.     border:1px solid blue;  
  80. }  
  81.    
  82. /*This section is used to decorate button*/  
  83.    
  84. .btn_box{  
  85.     border:1px solid #999;  
  86.     height:24px;  
  87.     font-family:"Comic Sans MS", cursive;  
  88. }  
  89.    
  90. .btn_box:hover{  
  91.     border:1px solid blue;  
  92. }  
  93.    
  94. /*To dacorate dropdown list*/  
  95.    
  96. .drop_list{  
  97.     border:1px solid blue;  
  98.     height:20px;  
  99. }  
  100.    
  101. .label_font{  
  102.     font-family:"Comic Sans MS", cursive;  
  103.     font-size:40px;  
  104. }  
  105.    
  106. .label_font:hover{  
  107.     color:white;  
  108. }  
  109.    
  110. /*Class to highlight title*/  
  111.    
  112. .title{  
  113.     font-family:"Comic Sans MS", cursive;  
  114.     font-size:18px;  
  115.     color:#06F;  
  116. }  
  117.    
  118. footer{  
  119.     background-color:#CCC;  
  120.     color:#03F;  
  121.     padding-bottom:5px;  
  122. }  
MainJavaScript.js
  1. /// <reference path="scripts/google-maps-3-vs-1-0.js" />  
  2. /// <reference path="scripts/GMAPJS/GMAPJSHelper_Release.js" />  
  3. var directionsDisplay;  
  4. var directionsService = new google.maps.DirectionsService();  
  5. var map;  
  6. var myCenter = new google.maps.LatLng(28.63100000000001, 77.21750683593746);  
  7. function initialize() {  
  8.    
  9.     directionsDisplay = new google.maps.DirectionsRenderer();  
  10.        
  11.         var mapOptions = {  
  12.             center: myCenter,  
  13.             zoom: 8,  
  14.             mapTypeId: google.maps.MapTypeId.ROADMAP  
  15.         };  
  16.    
  17.         map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);  
  18.         directionsDisplay.setMap(map);  
  19.         directionsDisplay.setPanel(document.getElementById('directionsPanel'));  
  20.        
  21.    
  22.     /*  points and marker codes*/  
  23.    
  24.     var points;  
  25.     var latitude;  
  26.     var longitude;  
  27.    
  28.     /*pink ball marker*/  
  29.    
  30.     var locate = document.getElementById('search').value;  
  31.    
  32.     /* Code to get Latitude and Longitude of location*/  
  33.    
  34.     var geocoder = new google.maps.Geocoder();  
  35.     var address = locate;  
  36.    
  37.     geocoder.geocode({ 'address': address }, function (results, status) {  
  38.    
  39.         if (status == google.maps.GeocoderStatus.OK) {  
  40.             latitude = results[0].geometry.location.lat();  
  41.             longitude = results[0].geometry.location.lng();  
  42.             points = new google.maps.LatLng(latitude, longitude);  
  43.    
  44.             /* marker code*/  
  45.    
  46.             var mapProp = {  
  47.                 center: points,  
  48.                 zoom: 12,  
  49.                 panControl: true/*In order to show navigating control*/  
  50.                 zoomControl: true,  
  51.                 mapTypeControl: true,  
  52.                 scaleControl: true,  
  53.                 streetViewControl: true/*Enable street view control*/  
  54.                 overviewMapControl: true,  
  55.                 rotateControl: true,  
  56.                 mapTypeId: google.maps.MapTypeId.ROADMAP  
  57.             };  
  58.    
  59.             var map = new google.maps.Map(document.getElementById('map_canvas'), mapProp);  
  60.             map.setTilt(45);  /*To rotate map with an angle of 45 degree*/  
  61.             var marker = new google.maps.Marker({  
  62.                 position: points,  
  63.                // icon: 'pinkball.png'  
  64.             });  
  65.    
  66.             marker.setMap(map);  
  67.    
  68.         }  
  69.     });  
  70.     document.getElementById('directionsPanel').innerHTML = "";  
  71. }  
  72.    
  73. function calcRoute() {  
  74.     var direction_type = document.getElementById('dirtype').value;  
  75.         if (direction_type == '1') {  
  76.         drive();  
  77.     }  
  78.     else if (direction_type == '2') {  
  79.         walk();  
  80.     }  
  81.     else if (direction_type == '3') {  
  82.         trans();  
  83.     }  
  84.    
  85. }  
  86. // driving path  
  87.    
  88. function drive() {  
  89.     document.getElementById('search').value = "Enter Place To Search";  
  90.     initialize();  
  91.     var start = document.getElementById('first_location').value;  
  92.     var end = document.getElementById('second_location').value;  
  93.     var request = {  
  94.         origin: start,  
  95.         destination: end,  
  96.         travelMode: google.maps.TravelMode.DRIVING  
  97.     };  
  98.     directionsService.route(request, function (response, status) {  
  99.         if (status == google.maps.DirectionsStatus.OK) {  
  100.             directionsDisplay.setDirections(response);  
  101.         }  
  102.     });  
  103. }  
  104. // walking path  
  105.    
  106. function walk() {  
  107.     document.getElementById('search').value = "Enter Place To Search";  
  108.     initialize();  
  109.     var start = document.getElementById('first_location').value;  
  110.     var end = document.getElementById('second_location').value;  
  111.     var request = {  
  112.         origin: start,  
  113.         destination: end,  
  114.         travelMode: google.maps.TravelMode.WALKING  
  115.     };  
  116.     directionsService.route(request, function (response, status) {  
  117.         if (status == google.maps.DirectionsStatus.OK) {  
  118.             directionsDisplay.setDirections(response);  
  119.         }  
  120.     });  
  121. }  
  122. // transit path  
  123.    
  124. function trans() {  
  125.     document.getElementById('search').value = "Enter Place To Search";  
  126.     initialize();  
  127.     var start = document.getElementById('first_location').value;  
  128.     var end = document.getElementById('second_location').value;  
  129.     var request = {  
  130.         origin: start,  
  131.         destination: end,  
  132.         travelMode: google.maps.TravelMode.TRANSIT  
  133.     };  
  134.     directionsService.route(request, function (response, status) {  
  135.         if (status == google.maps.DirectionsStatus.OK) {  
  136.             directionsDisplay.setDirections(response);  
  137.         }  
  138.     });  
  139. }  
The preceding code is the main JavaScript code that plays a vital role in the functioning of the maps.

Let us see how this code works.
  1. var directionsDisplay;  
  2. var directionsService = new google.maps.DirectionsService();  
  3. var map;  
  4. var myCenter = new google.maps.LatLng(28.63100000000001, 77.21750683593746);  
Here we have created a variable directionDisplay in the first line.

In second line we created a direction service object, in other words directionService of the Google Maps JavaScript API.

In the third line we have a variable map and in the last line we created an object, myCenter, of the Google Maps LatLng class for passing the latitudes and longitudes of New Delhi.

You can change them accordingly.

The following is the main function used to display the map:
  1. function initialize() {  
  2.    
  3.     directionsDisplay = new google.maps.DirectionsRenderer();  
  4.    
  5.         var mapOptions = {  
  6.             center: myCenter,  
  7.             zoom: 8,  
  8.             mapTypeId: google.maps.MapTypeId.ROADMAP  
  9.         };  
  10.    
  11.         map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);  
  12.         directionsDisplay.setMap(map);      
  13.         directionsDisplay.setPanel(document.getElementById('directionsPanel'));  
Here we created an object directionDisplay, whose main work is to fetch values and display the map.

The variable mapOptions holds the following three attributes: 
  • Center
  • Zoom
  • mapTypeId

The purpose of center is to fetch the latitudes and longitudes and display the map accordingly. In the preceding screen shot of my application you can see that when the map is loaded the center is New Delhi, because in this application I used latitudes and longitudes as the default center (this can be changed depending on the requirements).

Second is the Zoom, this attribute is used to set the zoom value for when the map is loaded, you can change it accordingly.

The third one is the mapTypeId, this is basically used to display the type of map, here I'm displaying a ROADMAP.

If you see in the HTML code we have a block to display the map.

  1. <!--To print map-->  
  2. <div id="map_canvas" style="height:100%;"></div>  
Here:
  1. map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);  
This line of code is used to display the map.

We also have a block to display the direction panel.
  1. <div style="overflow:auto; max-height:250px">  
  2.    <div id="directionsPanel"></div>  
  3. </div>  
This block displays the direction, the following piece of code is responsible for the direction panel.
  1. directionsDisplay.setPanel(document.getElementById('directionsPanel'));  
See that in the following screen shot.

screen shot

The following is the last statement in this function.
  1. directionsDisplay.setMap(map);  
Is displays the directions.

directions

The following piece of code works when we search a place from the search bar.
  1. /*  points and marker codes*/  
  2.    
  3.     var points;  
  4.     var latitude;  
  5.     var longitude;  
  6.    
  7.     /*pink ball marker*/  
  8.    
  9.     var locate = document.getElementById('search').value;  
  10.    
  11.     /* Code to get Latitude and Longitude of location*/  
  12.    
  13.     var geocoder = new google.maps.Geocoder();  
  14.     var address = locate;  
  15.    
  16.     geocoder.geocode({ 'address': address }, function (results, status) {  
  17.    
  18.         if (status == google.maps.GeocoderStatus.OK) {  
  19.             latitude = results[0].geometry.location.lat();  
  20.             longitude = results[0].geometry.location.lng();  
  21.             points = new google.maps.LatLng(latitude, longitude);  
  22.    
  23.             /* marker code*/  
  24.    
  25.             var mapProp = {  
  26.                 center: points,  
  27.                 zoom: 12,  
  28.                 panControl: true/*In order to show navigating control*/  
  29.                 zoomControl: true,  
  30.                 mapTypeControl: true,  
  31.                 scaleControl: true,  
  32.                 streetViewControl: true/*Enable street view control*/  
  33.                 overviewMapControl: true,  
  34.                 rotateControl: true,  
  35.                 mapTypeId: google.maps.MapTypeId.ROADMAP  
  36.             };  
  37.    
  38.             var map = new google.maps.Map(document.getElementById('map_canvas'), mapProp);  
  39.             map.setTilt(45);  /*To rotate map with an angle of 45 degree*/  
  40.             var marker = new google.maps.Marker({  
  41.                 position: points,  
  42.                // icon: 'pinkball.png'  
  43.             });  
  44.    
  45.             marker.setMap(map);  
  46.    
  47.         }  
  48.     });  
  49.     document.getElementById('directionsPanel').innerHTML = "";  
  50. }  
Let's see how this codes works.
  1. var locate = document.getElementById('search').value;  
This code fetches the location value from the search bar using:

code fetch

In this example, the value will be Karol Bagh, New Delhi.
  1. var geocoder = new google.maps.Geocoder();  
  2.     var address = locate;  
  3.    
  4.     geocoder.geocode({ 'address': address }, function (results, status) {  
  5.    
  6.         if (status == google.maps.GeocoderStatus.OK) {  
  7.             latitude = results[0].geometry.location.lat();/*Fetch latitude of location */  
  8.             longitude = results[0].geometry.location.lng();/*Fetch longitude of location*/  
  9.             points = new google.maps.LatLng(latitude, longitude);  
  10.    
  11.             /* marker code*/  
  12.    
  13.             var mapProp = {  
  14.                 center: points,  
  15.                 zoom: 12,  
  16.                 panControl: true/*In order to show navigating control*/  
  17.                 zoomControl: true,  
  18.                 mapTypeControl: true,  
  19.                 scaleControl: true,  
  20.                 streetViewControl: true/*Enable street view control*/  
  21.                 overviewMapControl: true,  
  22.                 rotateControl: true,  
  23.                 mapTypeId: google.maps.MapTypeId.ROADMAP  
  24.             };  
In this piece of code, using the geocoder class of the Google Maps API, we can fetch the latitude and longitude of the location that we entered in the search bar.

You can see in the comments, what everything in each line of code does.

Last but not the least:
  1. function calcRoute() {  
  2.     var direction_type = document.getElementById('dirtype').value;  
  3.         if (direction_type == '1') {  
  4.         drive();  
  5.     }  
  6.     else if (direction_type == '2') {  
  7.         walk();  
  8.     }  
  9.     else if (direction_type == '3') {  
  10.         trans();  
  11.     }  
  12.    
  13. }  
This piece of code is for searching for directions from location A to location B.

It is calling the following three functions: 
  • Drive() that is used to display the navigation in driving mode.
  • Walk(), that is used to display the navigation in walking mode.
  • Trans(), that is used to display the navigation in transit mode.

Style_Script.js

  1. // JavaScript Document  
  2.    
  3. /*Function to clear text on blur and focus*/  
  4.    
  5. function onfocus_js()  
  6. {  
  7.     var txt= document.getElementById('search').value;  
  8.     if(txt=="Enter Place To Search")  
  9.     {  
  10.         document.getElementById('search').value="";  
  11.     }  
  12. }      
  13.    
  14. function onblur_js()  
  15. {  
  16.     var txt=document.getElementById('search').value;  
  17.     if(txt=="" || txt==NULL)  
  18.     {  
  19.         document.getElementById('search').value="Enter Place To Search";  
  20.     }  
  21. }  
  22.    
  23. function st_blur_js()  
  24. {  
  25.     var txt=document.getElementById('first_location').value;  
  26.     if(txt==""|| txt==NULL)  
  27.     {  
  28.         document.getElementById('first_location').value="Choose start point";  
  29.     }  
  30. }  
  31.    
  32. function st_focus_js()  
  33. {  
  34.     var txt=document.getElementById('first_location').value;  
  35.     if(txt=="Choose start point")  
  36.     {  
  37.         document.getElementById('first_location').value="";  
  38.     }  
  39. }  
  40.    
  41. function en_blur_js()  
  42. {  
  43.     var txt=document.getElementById('second_location').value;  
  44.     if(txt=="" || txt==NULL)  
  45.     {  
  46.         document.getElementById('second_location').value="Choose end Point";  
  47.     }  
  48. }  
  49.    
  50. function en_focus_js()  
  51. {  
  52.     var txt=document.getElementById('second_location').value;  
  53.     if(txt=="Choose end Point")  
  54.     {  
  55.         document.getElementById('second_location').value="";  
  56.     }  
  57. }  
This script is used for designing purposes.

Demo Work 

Reference

Up Next
    Ebook Download
    View all
    Learn
    View all