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.


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">
    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>
    To: <br />
    <input type="text" id="routeEnd" value="ridderhof 69, oss">
  <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">

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".

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="//"></script>
<script type="text/javascript" src=""></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
  // point the directions to the container for the direction details
  // 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
          // call the calcRoute function to start calculating the route
    } 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
      // display the direction details in the container
    } 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.

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!


Previous Page 1 of 3 Next
  1. Gravatar

    Aswini kumar Panigrahi

    26 October 2018

    Can u send the full assembled code along with the links

  2. Gravatar


    18 September 2018


  3. Gravatar


    23 March 2018

    Where should i use my API key to display the map and it was showing
    You have included the Google Maps API multiple times on this page. This may cause unexpected errors.

    Instead of giving (value="ridderhof 69, oss" and value="ridderhof 69, oss") i want to give geolocation latitude and longitude Can you plese help me ?????

  4. Gravatar


    27 February 2018

    its very useful for me, very thanks

  5. Gravatar

    Nico Boots

    27 April 2017

    Dag Johan,
    Ik heb via plak en knippen alle code in een pagina gezet en naar mijn server geupload. Ik zie een fractie van een seconde een google map, maar daarna meteen de foutmelding: "Google Maps is niet correct geladen op deze pagina. Zie de JavaScript-console voor technische details." De pagina kun je terugvinden op
    Ik kwam op je blog omdat ik voor de gasten van mijn B&B een app wil maken waarin ze alle interessante plaatsen hier in de omgeving kunnen vinden met info, èn met de mogelijkheid om een routebeschrijving hoe daar te komen. Ik ben een volstrekte leek m.b.t. java of jquery. Het is me tot nu toe niet gelukt. Kun jij een suggestie geven hoe dit aan te pakken?

  6. Gravatar

    Sagar B Paithankar

    18 April 2017

    Directions service does not display route in ionic on device?

  7. Gravatar


    19 August 2016

    Hi, firstly thank you soo much for this example. I have question for you can you help me please.
    How can i route to road again and again, while my travel still continue.

  8. Gravatar


    11 May 2016

    Nice but it does not work for me.
    I want to build in a web page a route to a given location
    So the user shares his Geolocation and gets route planned automaticaly to a specific point.
    But it wont work

  9. Gravatar


    22 December 2015


  10. Gravatar


    22 December 2015

    Very nice

Previous Page 1 of 3 Next