Quantcast
Channel: Everything Technical » Other Programming
Viewing all articles
Browse latest Browse all 10

Draw directions between two locations using google maps

$
0
0

In earlier tutorials, we have learnt the basics of google maps and looked through examples like creating a store locator. In this tutorial, we will learn how to Draw directions between two locations using google maps v3. Google Maps api provides a DirectionService which allows to show turn by turn directions. Directions Service receives direction requests and returns computed results. We may either handle these directions results yourself or use the DirectionsRenderer object to render these results.

Direction Requests

To use directions in V3, we create an object of type DirectionsService and call DirectionsService.route() to initiate a request to the Directions service, passing it a DirectionsRequest object literal containing the input terms and a callback method to execute upon receipt of the response. A Sample DirectionsRequest is given below.

 var request = { 
	origin: "350 5th Ave, New York, NY", 
	destination: "1 Brewster Road, Newark, NJ", 
	travelMode: google.maps.DirectionsTravelMode.DRIVING,
        provideRouteAlternatives : false
 }; 

The DirectionsRequest has few more properties such as waypoints, avoidHighways, avoidTolls among others. For more information on the these please read this article.

Rendering Directions

Initiating a directions request to the DirectionsService with the route() method requires passing a callback which executes upon completion of the service request. This callback will return a DirectionsResult and a DirectionsStatus code in the response.

The DirectionsResult contains the result of the directions query, which you may either handle yourself, or pass to a DirectionsRenderer object, which can automatically handle displaying the result on a map.

To display a DirectionsResult using a DirectionsRenderer, you simply need to do the following:

  1. Create a DirectionsRenderer object.
  2. Call setMap() on the renderer to bind it to the passed map.
  3. Call setDirections() on the renderer, passing it the DirectionsResult as noted above. Because the renderer is an MVCObject, it will automatically detect any changes to its properties and update the map when its associated directions have changed.

Sample Code is given below

	var map;
	var directionsDisplay;
	var directionsService = new google.maps.DirectionsService();

	$(document).ready(function () {
	        //draw a map centered at Empire State Building Newyork
		var latlng = new google.maps.LatLng(40.748492, -73.985496);
	        var myOptions = {
	            zoom: 15,
	            center: latlng,
	            mapTypeId: google.maps.MapTypeId.ROADMAP
	        };
	        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
                //Create a DirectionsRenderer object
		directionsDisplay = new google.maps.DirectionsRenderer();
		directionsDisplay.setMap(map);
		directionsDisplay.setPanel(document.getElementById("divDirections"));
			
		$("#btnGetDirections").click(function(){
		    calcRoute($("#txtAddress1").val(),$("#txtAddress2").val());
		});
	});	
	function calcRoute(start,end) {
	  var request = {
		origin:start,
		destination:end,
		travelMode: google.maps.TravelMode.DRIVING,
		provideRouteAlternatives : false
	  };
	  directionsService.route(request, function(result, status) {
		if (status == google.maps.DirectionsStatus.OK) {
		  directionsDisplay.setDirections(result);
		  //displayDirections(result);
		}
	  });
	}

That’s it, it should plot the map with the directions between the two locations. directionsDisplay.setPanel sets the the turn by turn directions to the div divDirections.

If we want our own styling for displaying turn by turn directions, we can do that looping through the result object ourself.

DirectionResult object

The DirectionsResult result object contains array of route objections. Generally, only one route is returned for any given request, unless the request’s provideRouteAlternatives field is set to true, in which, multiple routes may be returned. Since for our request we have given provideRouteAlternatives as false, only one route would be returned. Below diagram of the route object

DirectionService Response object

Every Route object can have one or more legs.A DirectionsLeg defines a single leg of a journey from the origin to the destination in the calculated route. For routes that contain no waypoints, the route will consist of a single “leg,” but for routes that define one or more waypoints, the route will consist of one or more legs, corresponding to the specific legs of the journey.

Every leg has multiple steps. A DirectionsStep is the most atomic unit of a direction’s route, containing a single step describing a specific, single instruction on the journey. E.g. “Turn left at W. 4th St.” The step not only describes the instruction but also contains distance and duration information relating to how this step relates to the following step. Steps has steps object which contains detailed directions for walking or driving steps in transit directions. Sub-steps are only available for transit directions. You can find more detailed explanation of the object here.

Display Directions

Once you understand the response object, it is easy to loop through the object to display the turn by turn instructions. Since our request did not have any waypoints and it had provideRouteAlternatives set to false, our response will have only one route and one leg. But you can loop through the routes and legs through as required.

Sample code to display turn by turn directions

function displayDirections(result){
		//clear old data
		$("#divDirections").html('');
		var html = '<div style="margin:5px;padding:5px;background-color:#EBF2FC;border-left: 1px solid #EBEFF9;border-right: 1px solid #EBEFF9;text-align:right;">';
			html = html + '<span><strong>' + $.trim(result.routes[0].legs[0].distance.text.replace(/"/g,'')) + ', ' + $.trim(result.routes[0].legs[0].duration.text.replace(/"/g,'')) + '</strong></span></div>';
		
		$("#divDirections").html(html);
		//Display Steps
		var steps  = result.routes[0].legs[0].steps;
		for(i=0; i<steps.length; i++) {
			var instructions = JSON.stringify(steps[i].instructions);
			var distance = JSON.stringify(steps[i].distance.text);
			var time = JSON.stringify(steps[i].duration.text);
			$("#divDirections").append(getEmbedHTML(i+1,instructions,distance,time));
		}
	}

	function getEmbedHTML(seqno,instructions,distance,duration) {
		var	strhtml = '<div class="row">';
		strhtml  =  strhtml + '<span>' + seqno + '</span>&nbsp;' + $.trim(instructions.replace(/"/g,'')) + '<br/>'
		strhtml  =  strhtml + '<div style="text-align:right;"><span>' + $.trim(distance.replace(/"/g,'')) + ' <span></div>'
		strhtml  =  strhtml + '</div><div class="separator"></div>';
		
		return strhtml;
	}

Complete Code

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <link rel="stylesheet" type="text/css" href="style.css" />
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&key=AIzaSyD0X4v7eqMFcWCR-VZAJwEMfb47id9IZao">
    </script>
	<style>
	body {
		color: black;
		font-family: arial,sans-serif;
		font-size: 13px;
	}
	</style>
    <script type="text/javascript">
	var map;
	var directionsDisplay;
	var directionsService = new google.maps.DirectionsService();
	
	$(document).ready(function () {
			
			//draw a map centered at Empire State Building Newyork
		    var latlng = new google.maps.LatLng(40.748492, -73.985496);
	        var myOptions = {
	            zoom: 15,
	            center: latlng,
	            mapTypeId: google.maps.MapTypeId.ROADMAP
	        };
	        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
			directionsDisplay = new google.maps.DirectionsRenderer();
			directionsDisplay.setMap(map);
			//directionsDisplay.setPanel(document.getElementById("divDirections"));
			
			$("#btnGetDirections").click(function(){
				calcRoute($("#txtAddress1").val(),$("#txtAddress2").val());
			});
			 
			 
	});				  
      
	function calcRoute(start,end) {
	  var request = {
		origin:start,
		destination:end,
		travelMode: google.maps.TravelMode.DRIVING,
		provideRouteAlternatives : false
	  };
	  directionsService.route(request, function(result, status) {
		if (status == google.maps.DirectionsStatus.OK) {
		  directionsDisplay.setDirections(result);
		  displayDirections(result);
		}
	  });
	}
  	
	function displayDirections(result){
		var html = '<div style="margin:5px;padding:5px;background-color:#EBF2FC;border-left: 1px solid #EBEFF9;border-right: 1px solid #EBEFF9;text-align:right;">';
			html = html + '<span><strong>' + $.trim(result.routes[0].legs[0].distance.text.replace(/"/g,'')) + ', ' + $.trim(result.routes[0].legs[0].duration.text.replace(/"/g,'')) + '</strong></span></div>';
		$("#divDirections").html(html);
		
		//Display Steps
		var steps  = result.routes[0].legs[0].steps;
		for(i=0; i<steps.length; i++) {
			var instructions = JSON.stringify(steps[i].instructions);
			var distance = JSON.stringify(steps[i].distance.text);
			var time = JSON.stringify(steps[i].duration.text);
			$("#divDirections").append(getEmbedHTML(i+1,instructions,distance,time));
		}
	}
		
	function getEmbedHTML(seqno,instructions,distance,duration) {
		var	strhtml = '<div class="row">';
		strhtml  =  strhtml + '<span>' + seqno + '</span>&nbsp;' + $.trim(instructions.replace(/"/g,'')) + '<br/>'
		strhtml  =  strhtml + '<div style="text-align:right;"><span>' + $.trim(distance.replace(/"/g,'')) + ' <span></div>'
		strhtml  =  strhtml + '</div><div class="separator"></div>';
		
		return strhtml;
	}
    </script>
  </head>
  <body>
    <div id="container" class="shadow">
        <div id="map_canvas"></div>
        <div id="sidebar">
            <div class="row" style="background:#E3EDFA">
                <label> Enter Address in/around Newyork</label>
				<input type="text" id="txtAddress1" class="text" value="350 5th Ave, New York, NY" />
                <input type="text" id="txtAddress2" class="text" value="1 Brewster Road, Newark, NJ" />
                <img src="images/search.png" id="btnGetDirections" border="0" width="24" height="24" style="vertical-align:middle;"  />

            </div>
            <div class="separator"></div>
			<div id="divDirections">

			</div>

        </div>
    </div>
  </body>
</html>

Here is the output of the code above

GoogleMaps-Directions

To view the demo please click here

To download complete set of google maps examples, click here

NOTE : Please change the key if you using the code from the demo.

The post Draw directions between two locations using google maps appeared first on Everything Technical.


Viewing all articles
Browse latest Browse all 10

Trending Articles