Google Maps JavaScript API – By Paras Babbar

Title

Google Maps JavaScript API – By Paras Babbar

Introduction

In this post I will show you how you can use Google Maps JavaScript API to create an exciting application. It would be great fun using and working on Google Maps JavaScript API.

In this post I’ve created a simple navigation panel the same we can see on Google Maps off course there will be some difference in design but the functionality will be 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

https://developers.google.com/maps/documentation/javascript/tutorial

img1

 

 

 

 

 

 

 

 

Here on above link follow the steps as mentioned there and you can get your own API Key.

Now all you need is to create your own design. Below is the screen shot of template which I designed.

img 2

 

 

 

 

 

 


Now please find the code below

Home.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Google Maps</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
<!--Deploy Script For Google Maps API-->
 <script type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_OWN_API_KEY &sensor=true">
    </script>
<!--API Deployment Script Ends Here-->
<!-- deploy this script AFTER the maps api-->

    <script src="scripts/google-maps-3-vs-1-0.js" type="text/javascript"></script>
    <!--Deployments Ends-->
    <script type="text/javascript" src="javascript/mainJavaScript.js"></script>
    <script type="text/javascript">
        function myfunction(cc) {

            var locations = cc;
            for (i = 0; i < locations.length; i++) {
                var map = new google.maps.Map(document.getElementById('map_canvas'), {
                    zoom: 14,

                    center: new google.maps.LatLng(locations[i][1], locations[i][2]),
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                });
            }
            var infowindow = new google.maps.InfoWindow();

            var marker, i;

            for (i = 0; i < locations.length; i++) {
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                    map: map
                });

                google.maps.event.addListener(marker, 'click', (function (marker, i) {
                    return function () {
                        infowindow.setContent(locations[i][0]);
                        infowindow.open(map, marker);
                    }
                })(marker, i));
            }
        }
       
    </script>
<script src="javascript/style_script.js" type="text/javascript"></script>
</head>

<body onLoad="initialize()">
<div class="main">
<header>
<div id="search_cnt">

<center>
<table id="tab">
<tr>
<th><input type="text" class="text_box" value="Enter Place To Search" id="search" onBlur="onblur_js()" onFocus="onfocus_js();" /></th>
<th><input type="button" class="btn_box" onClick="initialize()"  value="Search"/></th>
</tr>
</table>
</center>
</div>
</header>
<aside id="cnt1">
<div>
<center>
<p><label title="Directions" class="label_font">Directions</label></p>
<table style="margin-top:30px;">
<tr>
<td><img src="images/start.png" height="25px" width="25px"/></td>
<td>
<input type="text" class="text_box" value="Choose start point" onBlur="st_blur_js()" onFocus="st_focus_js()" id="first_location"/>
</td>
</tr>
<tr>
<td><img src="images/dest.png" height="25px" width="25px" /></td>
<td>
<input type="text" class="text_box" value="Choose end Point" onBlur="en_blur_js()" onFocus="en_focus_js()" id="second_location"/>
</td>
</tr>
<tr>
<th colspan="2">
<select id="dirtype" class="drop_list" style="font-family:'Comic Sans MS', cursive">
<option value="1">Driving</option>
<option value="2">Walking</option>
<option value="3">Transit</option>
</select>
</th>
</tr>
<tr>
<th colspan="2"><input type="button" class="btn_box" value="Find Direction" id="getDirection" onClick="calcRoute()"/></th>
</tr>
</table>
</center>
</div>
<div  style="overflow:auto; max-height:250px">
   <div id="directionsPanel"></div>
   </div>
</aside>

<aside id="cnt2">
<!--To print map-->
<div id="map_canvas" style="height:100%;"></div>
</aside>
<footer>
<br/>
<center>
&copy; Designed By Paras Babbar. All Right Reserved: Google Custom Maps.
</center>
</footer>
</div>

</body>
</html>

Here, replace YOUR_OWN_API_KEY with the API key you received.

<script type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_OWN_API_KEY &sensor=true">
    </script>

Style.css

@charset "utf-8";
/* CSS Document */

body{
    background-color:#b0e0e6;
}

/*This class belongs to the main div tag just after body tag*/
.main{
    height:auto;
    width:auto;
    background:#0F0;
    border-top:solid;
    border-left:solid;
    border-right:solid;
    border-color:#000;
    border-bottom:solid;
}

header{
    height:100px;
    width:auto;
    background-color:#FFF;
    border-bottom:solid;
    border-color:#000;
    background-image:url(../images/title.png);
}

/*This ID belongs to the aside one seaction*/
#cnt1{
    height:500px;
    width:300px;
    background-color:#CCC;
    float:left;
    border-right:solid;
    border-bottom:solid;
}

/*This id belongs to the aside two section*/
#cnt2{
    height:500px;
    width:auto;
    background-color:#CCC;
    border-bottom:solid;
}

footer{
    height:45px;
}

/*This id belongs to the div tag placed in header section*/
#search_cnt{
    height:auto;
    width:auto;
}

/*This ID belongs to the table section inside the div tag under header*/
#tab{
    padding-top:30px;
}

/*This class is uder to decorate text box*/

.text_box{
    border:1px solid #999;
    width:200px;
    height:20px;
    color:#03F;
    font-family:"Comic Sans MS", cursive;
}

.text_box:focus{
    border:1px solid blue;
}

/*This section is used to decorate button*/

.btn_box{
    border:1px solid #999;
    height:24px;
    font-family:"Comic Sans MS", cursive;
}

.btn_box:hover{
    border:1px solid blue;
}

/*To dacorate dropdown list*/

.drop_list{
    border:1px solid blue;
    height:20px;
}

.label_font{
    font-family:"Comic Sans MS", cursive;
    font-size:40px;
}

.label_font:hover{
    color:white;
}

/*Class to highlight title*/

.title{
    font-family:"Comic Sans MS", cursive;
    font-size:18px;
    color:#06F;
}

footer{
    background-color:#CCC;
    color:#03F;
    padding-bottom:5px;
}

MainJavaScript.js

/// <reference path="scripts/google-maps-3-vs-1-0.js" />
/// <reference path="scripts/GMAPJS/GMAPJSHelper_Release.js" />
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var myCenter = new google.maps.LatLng(28.63100000000001, 77.21750683593746);
function initialize() {

    directionsDisplay = new google.maps.DirectionsRenderer();
    
        var mapOptions = {
            center: myCenter,
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(document.getElementById('directionsPanel'));
    

    /*  points and marker codes*/

    var points;
    var latitude;
    var longitude;

    /*pink ball marker*/

    var locate = document.getElementById('search').value;

    /* Code to get Latitude and Longitude of location*/

    var geocoder = new google.maps.Geocoder();
    var address = locate;

    geocoder.geocode({ 'address': address }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            latitude = results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();
            points = new google.maps.LatLng(latitude, longitude);

            /* marker code*/

            var mapProp = {
                center: points,
                zoom: 12,
                panControl: true, /*In order to show navigating control*/
                zoomControl: true,
                mapTypeControl: true,
                scaleControl: true,
                streetViewControl: true, /*Enable street view control*/
                overviewMapControl: true,
                rotateControl: true,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById('map_canvas'), mapProp);
            map.setTilt(45);  /*To rotate map with an angle of 45 degree*/
            var marker = new google.maps.Marker({
                position: points,
               // icon: 'pinkball.png'
            });

            marker.setMap(map);

        }
    });
    document.getElementById('directionsPanel').innerHTML = "";
}

function calcRoute() {
    var direction_type = document.getElementById('dirtype').value;
        if (direction_type == '1') {
        drive();
    }
    else if (direction_type == '2') {
        walk();
    }
    else if (direction_type == '3') {
        trans();
    }

}
// driving path

function drive() {
    document.getElementById('search').value = "Enter Place To Search";
    initialize();
    var start = document.getElementById('first_location').value;
    var end = document.getElementById('second_location').value;
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}
// walking path

function walk() {
    document.getElementById('search').value = "Enter Place To Search";
    initialize();
    var start = document.getElementById('first_location').value;
    var end = document.getElementById('second_location').value;
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.TravelMode.WALKING
    };
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}
// transit path

function trans() {
    document.getElementById('search').value = "Enter Place To Search";
    initialize();
    var start = document.getElementById('first_location').value;
    var end = document.getElementById('second_location').value;
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.TravelMode.TRANSIT
    };
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}

The above code is the main JavaScript code which plays a vital role in functioning of maps.
Let us see how this code works

var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var myCenter = new google.maps.LatLng(28.63100000000001, 77.21750683593746);

Here we have created a variable directionDisplay in first line,
In second line we have created a direction service object i.e. directionService of Google Maps JavaScript API.
In third line we have a variable map and in last line we have created a object myCenter of Google Maps LatLng class where I’ve passed latitudes and longitudes of New Delhi.
You can change them accordingly.
Below is the main function used to display map.

function initialize() {

    directionsDisplay = new google.maps.DirectionsRenderer();

        var mapOptions = {
            center: myCenter,
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
        directionsDisplay.setMap(map);    
        directionsDisplay.setPanel(document.getElementById('directionsPanel'));

 

Here we created an object directionDisplay, whose main work is to fetch values and display the map.

Variable mapOptions holds three attributes

  • Center
  • Zoom
  • mapTypeId

Work of center is to fetch the latitudes and longitudes and display map accordingly, in the above screen shot of my application you can see that when 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 as per the requirements).

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

Third one is the mapTypeId, this is basically used to display the type of map, here I’m displaying ROADMAP

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

 

<!--To print map-->
<div id="map_canvas" style="height:100%;"></div>

Here,

map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

this line of code is used to display the map.

We also have and block to display the direction panel.

<div  style="overflow:auto; max-height:250px">
   <div id="directionsPanel"></div>
   </div>

This block display the direction, below piece of code is responsible for direction panel.

 directionsDisplay.setPanel(document.getElementById('directionsPanel'));

See in below screen shot.

img 3

 

 

 

 

 

 

 

 

 

 

 

 

The last statement in this function

directionsDisplay.setMap(map);

is used to display the directions.

img 4

 

 

 

 

Below piece of code works when we search a place from search bar.

 

/*  points and marker codes*/

    var points;
    var latitude;
    var longitude;

    /*pink ball marker*/

    var locate = document.getElementById('search').value;

    /* Code to get Latitude and Longitude of location*/

    var geocoder = new google.maps.Geocoder();
    var address = locate;

    geocoder.geocode({ 'address': address }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            latitude = results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();
            points = new google.maps.LatLng(latitude, longitude);

            /* marker code*/

            var mapProp = {
                center: points,
                zoom: 12,
                panControl: true, /*In order to show navigating control*/
                zoomControl: true,
                mapTypeControl: true,
                scaleControl: true,
                streetViewControl: true, /*Enable street view control*/
                overviewMapControl: true,
                rotateControl: true,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById('map_canvas'), mapProp);
            map.setTilt(45);  /*To rotate map with an angle of 45 degree*/
            var marker = new google.maps.Marker({
                position: points,
               // icon: 'pinkball.png'
            });

            marker.setMap(map);

        }
    });
    document.getElementById('directionsPanel').innerHTML = "";
}

 

Let’s see how this codes works.

    var locate = document.getElementById('search').value;

 

This code fetch the location value from search bar using.

img 5

 

 

 

In this example, the value will be Karol Bagh, New Delhi

  var geocoder = new google.maps.Geocoder();
    var address = locate;

    geocoder.geocode({ 'address': address }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            latitude = results[0].geometry.location.lat();/*Fetch latitude of location */
            longitude = results[0].geometry.location.lng();/*Fetch longitude of location*/
            points = new google.maps.LatLng(latitude, longitude);

            /* marker code*/

            var mapProp = {
                center: points,
                zoom: 12,
                panControl: true, /*In order to show navigating control*/
                zoomControl: true,
                mapTypeControl: true,
                scaleControl: true,
                streetViewControl: true, /*Enable street view control*/
                overviewMapControl: true,
                rotateControl: true,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

 

In this piece of code, using geocoder class of Google Maps API, we can fetch the latitude and longitude of the location which we entered in search bar.
You can see in comments, it is already mentioned for what all things the respective line of code is used.

Last but on the least

function calcRoute() {
    var direction_type = document.getElementById('dirtype').value;
        if (direction_type == '1') {
        drive();
    }
    else if (direction_type == '2') {
        walk();
    }
    else if (direction_type == '3') {
        trans();
    }

}

This piece of code is used, when we search for directions from location A to location B.

 

It is calling three functions

  • Drive() which is used to display the navigation in driving mode.
  • Walk(), which is used to display the navigation in walking mode
  • Trans(), which is used to display the navigation in transit mode.

 Style_Script.js

// JavaScript Document

/*Function to clear text on blur and focus*/

function onfocus_js()
{
    var txt= document.getElementById('search').value;
    if(txt=="Enter Place To Search")
    {
        document.getElementById('search').value="";
    }
}    

function onblur_js()
{
    var txt=document.getElementById('search').value;
    if(txt=="" || txt==NULL)
    {
        document.getElementById('search').value="Enter Place To Search";
    }
}

function st_blur_js()
{
    var txt=document.getElementById('first_location').value;
    if(txt==""|| txt==NULL)
    {
        document.getElementById('first_location').value="Choose start point";
    }
}

function st_focus_js()
{
    var txt=document.getElementById('first_location').value;
    if(txt=="Choose start point")
    {
        document.getElementById('first_location').value="";
    }
}

function en_blur_js()
{
    var txt=document.getElementById('second_location').value;
    if(txt=="" || txt==NULL)
    {
        document.getElementById('second_location').value="Choose end Point";
    }
}

function en_focus_js()
{
    var txt=document.getElementById('second_location').value;
    if(txt=="Choose end Point")
    {
        document.getElementById('second_location').value="";
    }
}

This script is used to for designing purpose.

Demo Work

http://parasbabbar.in/projects/maps_api/

Reference

 


JavaScript, ASP.Net & PHP Web Developer. Connect with me on Facebook and Twitter.

Share This Post

Related Articles

Powered by Paras Babbar · Designed by Paras Babbar