How to Build a Distance Finder with Google Maps API

 Posted in Tutorials 594 days ago Written by: Irina Borozan
  • Buffer
  •  71
  • Buffer

Google maps is a free web mapping service application provided by Google. It offers lots of cool features (showing various map types, plotting points, showing routes, geocoding addresses). You can also add all these features to your website using the Google Maps APIs provided by Google. In this tutorial I will show you how to add some of these features to your site. I will be using the Google Maps Javascript API v3 (the newest version).

How to Build a Distance Finder with Google Maps API

What are we going to build?

We’ll make a distance finder. We’ll add a Google map to our site, plot two points on it (the user will be able to choose the addresses for these points), compute the distance between them and show the quickest route between them.

You can see the demo of application here. Also, you can download the source code using this link.

Prerequisites

The first thing you need to do in order to use the API from Google is requesting an API key. You can do this here. It’s easy and free!

Creating the web form for getting the two addresses

We’ll create a simple html form for the user to write the two addresses. We’ll add two input boxes and a button to the form. When the user presses the “Show” button, the map with the two locations will be shown.

Here’s the code for this:

<table align="center" valign="center">
<tr>
   <td colspan="7" align="center"><b>Find the distance between two locations</b></td>
</tr>
<tr>
   &nbsp;
</tr>
<tr>
   <td>First address:</td>
   &nbsp;
   <input name="<span class=" type="text" />address1" id="address1" size="50"/>
   &nbsp;
   <td>Second address:</td>
   &nbsp;
   <input name="<span class=" type="text" />address2" id="address2" size="50"/>
</tr>
<tr>
   &nbsp;
</tr>
<tr>
   <td colspan="7" align="center"><input type="button" value="Show" onclick="initialize();"/></td>
</tr>
</table>

The ‘initialize’ JavaScript function will be called when pressing the button. The function will show the map. In the next section I’ll show you how.

We also need to add a div tag to our page, where the map will be shown:

<div id="map_canvas" style="width:70%; height:54%"></div>

We will also need two div tags for showing the distances we will compute:

<div style="width:100%; height:10%" id="distance_direct"></div>
<div style="width:100%; height:10%" id="distance_road"></div>

Showing the map

The first thing we need to do is to find the coordinates (latitude and longitude) for the two addresses. Luckily, Google Maps will help us! Here’s what we have to do:

We’ll use the geocoder object for this. First, we’ll have to create a new geocoder object.

geocoder = new google.maps.Geocoder();

After this, we’ll get the two address values from the form. Like this:

address1 = document.getElementById("address1").value;
address2 = document.getElementById("address2").value;

Then, we’ll use the following code to call the geocode method on the geocoder object. We’ll pass it the addresses one by one and save the results in the variables called location1 and location2 (these will hold the coordinates of the two addresses).

if (geocoder)
{
   geocoder.geocode( { 'address': address1}, function(results, status)
   {
      if (status == google.maps.GeocoderStatus.OK)
      {
         //location of first address (latitude + longitude)
         location1 = results[0].geometry.location;
      } else
      {
         alert("Geocode was not successful for the following reason: " + status);
      }
   });
   geocoder.geocode( { 'address': address2}, function(results, status)
   {
      if (status == google.maps.GeocoderStatus.OK)
      {
         //location of second address (latitude + longitude)
         location2 = results[0].geometry.location;
         // calling the showMap() function to create and show the map
         showMap();
      } else
      {
        alert("Geocode was not successful for the following reason: " + status);
      }
   });
}

You will notice that we’ve called the showMap() function when the coordinates for the second address are retrieved. This function will set the options for the map and show it.

We’ll now compute the coordinates for the center of the map. The center point will be between our two points.

latlng = new google.maps.LatLng((location1.lat()+location2.lat())/2,(location1.lng()+location2.lng())/2);

Next, we’ll show the map. We have to create a new map object and pass it some parameters (set using the mapOptions variable): the zoom level, the center and the type of the map.

var mapOptions =
{
   zoom: 1,
   center: latlng,
   mapTypeId: google.maps.MapTypeId.HYBRID
};

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

The next thing we’ll do is to show the quickest route between our locations. We’ll use a DirectionsService object from google maps for this. Here’s how the code looks:

directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer(
{
   suppressMarkers: true,
   suppressInfoWindows: true
});
directionsDisplay.setMap(map);
var request = {
   origin:location1,
   destination:location2,
   travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status)
{
   if (status == google.maps.DirectionsStatus.OK)
   {
      directionsDisplay.setDirections(response);
      distance = "The distance between the two points on the chosen route is: "+response.routes[0].legs[0].distance.text;
      distance += "The aproximative driving time is: "+response.routes[0].legs[0].duration.text;
      document.getElementById("distance_road").innerHTML = distance;
   }
});

We’ve first created the objects we need. We then set some options for displaying the route, we’ve chosen not to show markers and info boxes (we’ll create our own ones);

suppressMarkers: true,
suppressInfoWindows: true

We’ve created a request object and set the origin and destination for the route and also the travel mode:

var request = {
   origin:location1,
   destination:location2,
   travelMode: google.maps.DirectionsTravelMode.DRIVING
};

We’ve then called the route function and obtained a response from the server. Using this response we’ve plotted the route on the map and written some info (the total distance and aproximative driving time) in one of the divs we’ve created:

directionsDisplay.setDirections(response);
distance = "The distance between the two points on the chosen route is: "+response.routes[0].legs[0].distance.text;
distance += "The aproximative driving time is: "+response.routes[0].legs[0].duration.text;
document.getElementById("distance_road").innerHTML = distance;

We’ll also show a line between our points and compute the distance between them (the distance on a straight line, in kilometers). To show a line we’ll use a Polyline object from google maps and set some options for it (the map it belongs to, the path, the width, the opacity and the color):

var line = new google.maps.Polyline({
   map: map,
   path: [location1, location2],
   strokeWeight: 7,
   strokeOpacity: 0.8,
   strokeColor: "#FFAA00"
});

We’ll now compute the distance between two points using their coordinates and show the result inside the other div tag we’ve created.

var R = 6371;
var dLat = toRad(location2.lat()-location1.lat());
var dLon = toRad(location2.lng()-location1.lng());
var dLat1 = toRad(location1.lat());
var dLat2 = toRad(location2.lat());
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(dLat1) * Math.cos(dLat1) *
        Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;

document.getElementById("distance_direct").innerHTML = "The distance between the two points (in a straight line) is: "+d;

The last thing we’ll do is show a marker and an info window for each location. We’ll create two marker objects (the options we’ll set are: the map it belongs to, the coordinates and a title):

var marker1 = new google.maps.Marker({
   map: map,
   position: location1,
   title: "First location"
});

var marker2 = new google.maps.Marker({
   map: map,
   position: location2,
   title: "Second location"
});

Next, we’ll create variables to hold the texts to print in the info windows, create two info window objects (we’ll add the texts to them using the content option) and we’ll add two event listeners which will show the appropriate info window when the user clicks on the markers:

// create the text to be shown in the infowindows

var text1 = '
<div id="content">'+</div>
  '<h1 id="firstHeading">First location'+
  '<div id="bodyContent">'+
  '<p>Coordinates: '+location1+'</p>'+
  '<p>Address: '+address1+'</p>'+
  '</div>'+
  '</div>';

var text2 = '
<div id="content">'+</div>
  '<h1 id="firstHeading">Second location'+
  '<div id="bodyContent">'+
  '<p>Coordinates: '+location2+'</p>'+
  '<p>Address: '+address2+'</p>'+
  '</div>'+
  '</div>';

// create info boxes for the two markers
var infowindow1 = new google.maps.InfoWindow({
   content: text1
});
var infowindow2 = new google.maps.InfoWindow({
   content: text2
});

// add action events so the info windows will be shown when the marker is clicked
google.maps.event.addListener(marker1, 'click', function() {
   infowindow1.open(map,marker1);
});

google.maps.event.addListener(marker2, 'click', function() {
   infowindow2.open(map,marker2);
});

And we’re done! We now have a distance finder! Let me know if you have any questions!

 Did you enjoy this article and found it useful?

Irina is a software developer from Bucharest, Romania. She enjoys working on various programming projects. She likes spending her spare time reading, hiking, travelling, skating or playing tennis. She also blogs a bit. You can find her online in her home on the internet and on twitter.
Free Website
 

 71 Brilliant Comments - Join Discussion Now!

  • pove

    Posted 420 days ago
    38

    Great tuto! Thanks! For Spanish people, try to find the rou from “Vete” to “Cagar”, it exists!

    ;-)

    Reply
  • Abdullasoudi

    Posted 473 days ago
    37

    Great !! Thanks to you…

    Reply
  • shaun

    Posted 516 days ago
    35

    very nice thanks but how do i output distance in miles and not km ? is it possible

    Reply
    • Irina

      Posted 515 days ago
      36

      You would just have to compute the return values from gmaps from kms to miles :)

      Reply
  • Ryan

    Posted 518 days ago
    32

    Hi Irina

    Do you know how i can get the google formatted address? Basically take the address entered and get the address back from google formatted correctly?

    Thanks in advance
    Ryan

    Reply
    • Irina Borozan

      Posted 516 days ago
      34

      Hello

      That’s a really good idea! I haven’t thought of doing this before, but I will definitely look into it. I don’t know if there are any converters available though. You might need to write your own.

      I’ll let you know if I find anything useful!

      Reply
  • Ryan

    Posted 518 days ago
    31

    Hi Irina

    What an awesome tutorial thank you. Pehaps you can point me in the right direction:

    When a user starts typing in an address i would like it to automatically dropdown a suggested list of addresses. The same as it works for google map directions.

    If you can point me in the right direction It would be greatly appreciated.

    thanks
    Ryan

    Reply
    • Irina Borozan

      Posted 516 days ago
      33

      Hello

      You would need to use some code for that auto-complete. There are loads of libraries (in javascript, jquery) available. Here’s an example: http://www.phpguru.org/static/AutoComplete.html

      The library you choose to use depends on the programming language your app is written in and on the location of the data you want to show in the drop down.

      I hope this helps!

      Reply
  • bago

    Posted 582 days ago
    30

    very nice and very usable!!!
    a little hint: why don’t u convert the distance in a more useful way? i.e. in km

    Reply
  • leonid

    Posted 584 days ago
    29

    it`s great lesson!
    thanks.

    Reply
  • niks

    Posted 587 days ago
    28

    Hey. Great tutorial. I have always used google maps. Its interesting to see that there is lot more to it.

    Reply
  • hackxue

    Posted 588 days ago
    25

    Irina,Good work!
    I wanna to know if it could show the bus line!?

    Reply
  • shafi

    Posted 589 days ago
    24

    Hi!
    Yep, Nice article, helped me alot.

    Thanks.

    Reply
    • Irina

      Posted 588 days ago
      26

      I’m glad you liked it!

      Reply
  • daniele

    Posted 592 days ago
    22

    i had to do this time ago for a website.
    don’t store the address, but use the lat and the long instead

    first of all i looped a php page that reads the addresses from the db, find lat and long via google geolocation and then store it into the db. starting from this moment you can always geolocate the point in the google maps reading its coordinates

    Reply
    • Irina

      Posted 591 days ago
      23

      That’s a good idea!

      Reply
  • Irina

    Posted 593 days ago
    20

    Thank you all for the tips and ideas! I might be adding some to my next google maps tutorial :)

    Reply
  • Omer Rosenbaum

    Posted 593 days ago
    17

    Hi Irina!
    Great stuff you made there. I want to continue developing it and combine it with MySql.
    What I am trying to do is to get the 2 addresses into a DB. So far I haven’t had much success. Could you or anyone else can try to prepare such thing?

    Reply
    • Irina

      Posted 593 days ago
      21

      That’s a good idea! I am probably going to write another tutorial on google maps and I could also add this to it.

      In the meantime, if you need some help with what you’ve tried so far, send me a message or something and I could help you.

      Reply
  • Shawn McConnell

    Posted 593 days ago
    15

    Irina, nice tutorial I have done something similar on my site but I just outline the locations of where I have previously worked on my resume page. this helps potential people see the general area I work in.

    Shawn,

    Reply
    • Irina

      Posted 593 days ago
      19

      Thats a good idea of using google maps! :)

      Reply
  • emil

    Posted 593 days ago
    14

    Multumesc pentru tutorial. Daca se poate traseu si cu ruta din 1, 2 puncte de trecere.
    Emil

    Reply
    • Irina

      Posted 593 days ago
      18

      Bună idee :)

      It’s not very difficult to add more points on a route as you said, you just have to multiply to code for the textboxes and markers :)

      Reply
  • Irina

    Posted 594 days ago
    13

    I’ve just found out google maps turns 5 today! Nice coincidence!

    They’ve made a map with applications made by users and I’ve added mine there :)

    Reply
  • Matt

    Posted 594 days ago
    10

    Nice tutorial! One question: why do you set the zoom level at 1? Wouldn’t it be better to make the zoom level high enough to show just the area with the two points defined by the user?

    Reply
    • Irina Borozan

      Posted 594 days ago
      12

      I’ve left it at 1 because if google can find a route between the two addresses, it automatically adjusts the zoom level when showing the route.

      Reply
      • Matt

        Posted 593 days ago
        16

        Ah, excellent. Thanks!

        Reply
  • Frank Bailey

    Posted 594 days ago
    9

    Hi Irina, this is a great tutorial, thanks a ton! I’d just like to know if you might be able to provide a quick example of how we might be able to allow the user to click a point on the map to use as either the destination or origin, rather than entering and then geocoding the address?

    Reply
    • Irina Borozan

      Posted 594 days ago
      11

      Hey, good idea! You’ll see something similar to this in the second part of the tutorial, which will be posted in a couple of days ;) I’m glad you enjoyed this one!

      Reply
  • Saad Bassi

    Posted 594 days ago
    8

    Really awesome Tut Irina. Thumbs up. :)

    Reply
  • Irina

    Posted 594 days ago
    7

    Thanks for all the comments and tips! I’m glad you like it :)

    Reply
  • aditya

    Posted 594 days ago
    5

    this is very nice post

    Reply
  • Andrea

    Posted 594 days ago
    4

    Very interesting, You should complete it adding driving directions!

    Reply
    • Saad Bassi

      Posted 594 days ago
      6

      Stay Tuned for the 2nd part coming on Thursday.:)

      Reply
  • George Chatzimanolis

    Posted 594 days ago
    3

    THANKS!!! It is an excellent tutorial.

    Reply
  • Pierre

    Posted 594 days ago
    2

    Nice tut! Thanks.
    I saw a website using Google Maps like your tutorial, providing this kind of tool: http://distancity.com

    Reply
  • Bojan

    Posted 594 days ago
    1

    Hi!
    Very nice article, a small digression, you don’t need an API key if you’re using Googla Maps API v3. (You also didn’t use an API key in example provided with post.)
    Regards

    Reply
1 2 3

 Add Your Own Brilliant Comment:

Tags allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

US