Using geolocation to automatically generate a route and directions in Google Maps

15 October 2012

In this tutorial we will create a google map with directions that use your current location as starting point on mobile devices (or other devices that support geolocation).

In an earlier tutorial we already built a page with a nice google map and a form to enter your location in and then calculate directions and a route to a location. Your office or home, for example. This is good if your adience most probably is at home or somewhere they know the address of. What if somebody was on in a foreign city, just wanting to know what's the nearest bookstore. He doesn't know what his address is of the where he's standing. In a street with signs it isn't hat big of a problem, but in the middle of central park...

That's why you want to use you devices built-in GPS unit (or triangulated location) as a startingpoint of the directions. The startingpoint is a default location set by you or the user can click the "use my current location" link to enter the current location to the startpoint form field.



I'll start this tutorial fresh and cover everything in the code used for this demo apart from the styling/css. The code is mostly the same as the previous tutorial, so if you've already read this one, you will recognize a lot of code and you can skip most code.

The HTML


Most important element of this page is the container for the map. Add a div to the body of your page, give it an ID and dimensions (the dimensions are important, google does not provide a default size). I made the map 100% width and a fixed height. This is probably best for your page also.

<div id="map_canvas" style="width:100%; height:300px"></div>

Next is the second part of the body; the form element where you can pick a travel mode and enter a start- and endpoint for your route. I've stripped out all unnecessary styling to keep things simple:

<form action="#" onSubmit="calcRoute();return false;" id="routeForm">
  <label>
    From: <br />
    <input type="text" id="routeStart" value="kruisstraat 50, oss">
          <a href="#" class="autoLink" style="display: none;">Use current location: <span>not found</span></a>
  </label>
        <label>
    To: <br />
    <input type="text" id="routeEnd" value="ridderhof 69, oss">
  </label>
  <label><input type="radio" name="travelMode" value="DRIVING" checked /> Driving</label>
  <label><input type="radio" name="travelMode" value="BICYCLING" /> Bicylcing</label>
  <label><input type="radio" name="travelMode" value="TRANSIT" /> Public transport</label>
  <label><input type="radio" name="travelMode" value="WALKING" /> Walking</label>
  <input type="submit" value="Calculate route">
</form>

Last piece of the HTML elements is the container to display the direction details in. Add a div with an ID. You don't have to give this element a size or other styling. It will automatically size to the contents. Don't forget to enter a default text that's displayed before the route is calculated.

<div id="directionsPanel">
  Enter a starting point and click "Calculate route".
</div>


The Javascript


Next is the Javascript. There are four functions we're using. One function (initialize) that's called when the page is loaded in which we load the map and initialize a few Google Maps objects. The other function (calcRoute) is one to calculate the route and display the directions and the last two functions (notFound & foundYou) which are callbacks for the geolocation call. The last sounds complicated, but it really isn't.

To use the Google Maps API you need to include the API in the head of your document. I also load jQuery to keep the code simple. This isn't really needed, but if I had used just plain Javascript the code samples would be much more complicated for beginning developers.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

Next we add a script-tag to the head of your document. All the javascript we'll be writing needs to go in these tags.

<script type="text/javascript"></script>

Then we enter declare a few variables that are used across the four functions (if we would declare them inside the initialize function, the will only be available inthere):
var directionDisplay, map;
var directionsService = new google.maps.DirectionsService();
var geocoder = new google.maps.Geocoder();

Next is the initialize function. I've added comment lines to the code to make it self explaning:

function initialize() {
  // set the default center of the map
  var latlng = new google.maps.LatLng(51.764696,5.526042);
  // set route options (draggable means you can alter/drag the route in the map)
  var rendererOptions = { draggable: true };
  directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
  // set the display options for the map
  var myOptions = {
    zoom: 14,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: false
  };
  // add the map to the map placeholder
  map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
  // bind the map to the directions
  directionsDisplay.setMap(map);
  // point the directions to the container for the direction details
  directionsDisplay.setPanel(document.getElementById("directionsPanel"));
  // start the geolocation API
  if (navigator.geolocation) {
    // when geolocation is available on your device, run this function
    navigator.geolocation.getCurrentPosition(foundYou, notFound);
  } else {
    // when no geolocation is available, alert this message
    alert('Geolocation not supported or not enabled.');
  }
}

To make sure this initialization code is executed when the page loads, add an onLoad event to the body of your document:

<body onLoad="initialize()">

Next function to add to the JS in the head is the notFound function which is executed when the location of the visitor could not be determined.

function notFound(msg) {  
  alert('Could not find your location :(')
}

The function executed when the location of the visitor can be determined is a little bigger. See the comment lines again for explanation:

function foundYou(position) {
  // convert the position returned by the geolocation API to a google coordinate object
  var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
  // then try to reverse geocode the location to return a human-readable address
  geocoder.geocode({'latLng': latlng}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      // if the geolocation was recognized and an address was found
      if (results[0]) {
        // add a marker to the map on the geolocated point
        marker = new google.maps.Marker({
            position: latlng,
            map: map
        });
        // compose a string with the address parts
        var address = results[0].address_components[1].long_name+' '+results[0].address_components[0].long_name+', '+results[0].address_components[3].long_name
        // set the located address to the link, show the link and add a click event handler
        $('.autoLink span').html(address).parent().show().click(function(){
          // onclick, set the geocoded address to the start-point formfield
          $('#routeStart').val(address);
          // call the calcRoute function to start calculating the route
          calcRoute();
        });
      }
    } else {
      // if the address couldn't be determined, alert and error with the status message
      alert("Geocoder failed due to: " + status);
    }
  });
}

The last function is the directions function. This one is fairly simple, but big due to all the error handling code. See the comments also to know what the code does.

function calcRoute() {
  // get the travelmode, startpoint and via point from the form  
  var travelMode = $('input[name="travelMode"]:checked').val();
  var start = $("#routeStart").val();
  var end = $("#routeEnd").val();
  // compose a array with options for the directions/route request
  var request = {
    origin: start,
    destination: end,
    unitSystem: google.maps.UnitSystem.IMPERIAL,
    travelMode: google.maps.DirectionsTravelMode[travelMode]
  };
  // call the directions API
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      // directions returned by the API, clear the directions panel before adding new directions
      $('#directionsPanel').empty();
      // display the direction details in the container
      directionsDisplay.setDirections(response);
    } else {
      // alert an error message when the route could nog be calculated.
      if (status == 'ZERO_RESULTS') {
        alert('No route could be found between the origin and destination.');
      } else if (status == 'UNKNOWN_ERROR') {
        alert('A directions request could not be processed due to a server error. The request may succeed if you try again.');
      } else if (status == 'REQUEST_DENIED') {
        alert('This webpage is not allowed to use the directions service.');
      } else if (status == 'OVER_QUERY_LIMIT') {
        alert('The webpage has gone over the requests limit in too short a period of time.');
      } else if (status == 'NOT_FOUND') {
        alert('At least one of the origin, destination, or waypoints could not be geocoded.');
      } else if (status == 'INVALID_REQUEST') {
        alert('The DirectionsRequest provided was invalid.');        
      } else {
        alert("There was an unknown error in your request. Requeststatus: nn"+status);
      }
    }
  });
}

In this table you'll see what the browser support is for the geolocation API.

Browser support for geolocation


You must have JavaScript enabled to use this form!

Leave a comment!

  1. Your mail is safe with me. It's only only used to display your Gravatar image!

26 comments

Previous Page 2 of 3 Next
  1. Gravatar

    jainil

    24 February 2015

    a perfect example....no issue...Really thankful to you Sir.....

  2. Gravatar

    Shabnam

    21 July 2014

    Thank you for this tutorial ! :)

  3. Gravatar

    Michael

    10 September 2013

    Is this tut now out of date? Demo just says "Could not find your location :(" ?

  4. Gravatar

    Ian

    25 August 2013

    Just trying to understand this stuff and this is excellent tutorial thanks for spending time explaining.

    Have bookmarked this site for future learning I am not a youngster.

    Cheers

    Ian

  5. Gravatar

    Jigar

    10 July 2013

    Thanks Johan for the post.
    Can you tell me How to provide options for departure date and time in transit mode?

    I need to incorporate this to one of my project on urgent basis.
    thanks in advance.

  6. Gravatar

    Rick

    02 March 2013

    Hello, thank you for this tutorial. It is very good. But I have problems in my theme:

    jquery min - commands.

    There are then other functions with me. Can that even without jquery min active?

    Thank you. greetings Rick

  7. Gravatar

    Adrian

    08 February 2013

    Can you please make an example witch uses "current location" from Geolocation to a selectable location ? Thank you. Please email me

  8. Gravatar

    Phil Did,

    06 December 2012

    I found your tuto after seing this Googlemap/calculate route, on a website using CMSMadeSimple

    Look good but so much js

  9. Gravatar

    Mitak

    07 November 2012

    Hi ,Johan. First of all, I really like your toutorials and they helped me alot with my current work.
    I am having some problem here and I thought you could give me some advice.
    Basically I want the geolocation to be used automatically in the caclulation of the route, without the "From" textfield, but every time I run the calcRoute function it justs sets my geolocation over and over again.
    http://pastebin.com/MS4HQBjc - this is the code I am using, maybe if u have some free time , you can have a look.
    Thanks in advance!
    Kindly, Mitak.

  10. Gravatar

    Johan

    05 November 2012

    Hi Ryan, you can also use coordinates as start- or endpoint in the route calculation. See this tutorial for a code example:

    http://www.dreamdealer.nl/tutorials/getting_directions_with_google_maps.html

Previous Page 2 of 3 Next