Skip to content
Products
Solutions
By industry
By use case
Resources
Products
Solutions
By industry
By use case
Resources
Products
Solutions
By industry
By use case
Resources
How to calculate distances between points with the Maps JavaScript API
Sonia Rode
Software Engineer
Nov 7, 2019
Try Google Maps Platform
Unlock access to real-world data and insights with a monthly $200 Google Maps Platform credit.
Get started

There’s a lot your users can figure out about a place just by exploring your map–what’s nearby, whether the locations are relatively close to each other, and even roughly how far a place is based on the map’s scale. With Google Maps Platform you can take some of the guesswork out of the picture by quantifying distances via straight line distance and route distance. Each uses a different approach and solves for different user problems or actions. So today we’re explaining what each is, when to use one over the other, and how to get started. 

To make these points, we’ll plot some distances on a map with some handy JavaScript. And because to calculate any sort of distance requires point A and point B, we’ll start by adding two markers to a basic Google Map:

<!DOCTYPE html>
<html>
  <head>
    <style>
       /* Set the size of the div element that contains the map */
      #map {
        height: 400px;
        width: 600px;
       }
    </style>
  </head>
  <body>
    <!--The div elements for the map and message -->
    <div id="map"></div>
    <div id="msg"></div>
    <script>
// Initialize and add the map
var map;
function initMap() {
  // The map, centered on Central Park
  const center = {lat: 40.774102, lng: -73.971734};
  const options = {zoom: 15, scaleControl: true, center: center};
  map = new google.maps.Map(
      document.getElementById('map'), options);
  // Locations of landmarks
  const dakota = {lat: 40.7767644, lng: -73.9761399};
  const frick = {lat: 40.771209, lng: -73.9673991};
  // The markers for The Dakota and The Frick Collection
  var mk1 = new google.maps.Marker({position: dakota, map: map});
  var mk2 = new google.maps.Marker({position: frick, map: map});
}
    </script>
    <!--Load the API from the specified URL -- remember to replace YOUR_API_KEY-->
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>
Copied to clipboard!

Here we can see Central Park, as well as two nearby landmarks. The Dakota, perhaps most famous as John Lennon’s home. And The Frick Collection, an art gallery.

Distance1

Suppose these were both on a New York City tour. You might be interested to know how far it is from one to the other. We’ll answer that question with some 200 year-old number crunching.

**Calculate the straight line distance from latitude and longitude**The simplest method of calculating distance relies on some advanced-looking math. Known as the Haversine formula, it uses spherical trigonometry to determine the great circle distance between two points. Wikipedia has more on the formulation of this popular straight line distance approximation.

To visualize the calculation, we can draw a Polyline between the two markers. Add the following lines after the markers in the JavaScript:

// Draw a line showing the straight distance between the markers
  var line = new google.maps.Polyline({path: [dakota, frick], map: map});
Copied to clipboard!

Reload the map and you should see a dark, diagonal line connecting the two markers, from one side of Central Park to the other. Using the JavaScript equivalent of the Haversine formula, we can determine the length of the Polyline, the straight distance between our two markers.

Add this function to your JavaScript, before the initMap function:

function haversine_distance(mk1, mk2) {
      var R = 3958.8; // Radius of the Earth in miles
      var rlat1 = mk1.position.lat() * (Math.PI/180); // Convert degrees to radians
      var rlat2 = mk2.position.lat() * (Math.PI/180); // Convert degrees to radians
      var difflat = rlat2-rlat1; // Radian difference (latitudes)
      var difflon = (mk2.position.lng()-mk1.position.lng()) * (Math.PI/180); // Radian difference (longitudes)

      var d = 2 * R * Math.asin(Math.sqrt(Math.sin(difflat/2)*Math.sin(difflat/2)+Math.cos(rlat1)*Math.cos(rlat2)*Math.sin(difflon/2)*Math.sin(difflon/2)));
      return d;
    }
Copied to clipboard!

The function accepts two marker objects and returns the distance between them in miles. To use kilometers, set R = 6371.0710. Before applying the Haversine formula, the function converts each marker’s latitude and longitude points into radians.

To call the function and report the distance below the map, add this code below your Polyline in the initMap function:

// Calculate and display the distance between markers
  var distance = haversine_distance(mk1, mk2);
  document.getElementById('msg').innerHTML = "Distance between markers: " + distance.toFixed(2) + " mi.";
Copied to clipboard!

Load the map and you’ll see the following:

DistanceBtwn2Markers

Now we know the straight line distance between The Dakota and The Frick Collection is 0.60 miles (rounded to two decimal places using the JavaScript toFixed function).

Of course, unless you’re a pigeon, your jaunt between the two locations is likely to be longer. A quick glance at the map shows there is no road or even pathway straight across Central Park. The Haversine formula is useful for basic proximity, but is insufficient for many use cases, especially within cities. For a more accurate travel distance, we’ll need to use another feature of the Maps JavaScript API.

**Get Directions with the Maps JavaScript API**When the straight line distance is not adequate, you’ll need more than a formula to determine the travel distance. Driving directions are one of the most popular features in Google Maps, so it’s unsurprising that it’s also made available via an API. You can use the Directions API for server-side requests, or the Directions Service in the Maps JavaScript API for client-side requests on the web.

Since our JavaScript map is already set, we’ll continue by using the Directions Service. Paste the following at the end of your initMap function:

let directionsService = new google.maps.DirectionsService();
  let directionsRenderer = new google.maps.DirectionsRenderer();
  directionsRenderer.setMap(map); // Existing map object displays directions
  // Create route from existing points used for markers
  const route = {
      origin: dakota,
      destination: frick,
      travelMode: 'DRIVING'
  }

  directionsService.route(route,
    function(response, status) { // anonymous function to capture directions
      if (status !== 'OK') {
        window.alert('Directions request failed due to ' + status);
        return;
      } else {
        directionsRenderer.setDirections(response); // Add route to the map
        var directionsData = response.routes[0].legs[0]; // Get data about the mapped route
        if (!directionsData) {
          window.alert('Directions request failed');
          return;
        }
        else {
          document.getElementById('msg').innerHTML += " Driving distance is " + directionsData.distance.text + " (" + directionsData.duration.text + ").";
        }
      }
    });
Copied to clipboard!

After a successful call to the directions service, you’ll have the route added to the map. The message below the map is also extended to include the distance.

DistanceDriving

With a quick visual inspection, it’s clear that driving directions are much farther than the straight line distance. We can dig into the data that comes back in the response to find driving distance (1.6 miles, two and a half times farther), as well as the estimated duration. Here’s a JSON representation of the relevant section from the response:

"routes": [{
  "legs": [
    {
      "distance": {
        "text": "1.6 mi",
        value: 2619
      },
      {
        "duration": {
          "text": "9 mins",
          value: 516
        }
      }
    }
  ]
}]
Copied to clipboard!

While our example used driving directions, you can also pass other values to the travelMode field in your route object. The directions service can also accept  BICYCLING, TRANSIT, and WALKING values. Try adjusting the mode and running the code again to see how the directions result changes.

Which distance should I use?The two distance types in this post are useful in different scenarios. To give your users the best experience, you should use each in the appropriate situation.

You can use straight line distance to make quick calculations without a call to an external service. You’ll need to include the Haversine function used in this tutorial, but all you need are map coordinates to get an accurate result within the browser. However, as the name suggests, the distance will be a simple straight line. Roads, obstructions, and traffic are not factored into straight line distance.

Route distance, on the other hand, will return the distance along a route, including necessary turns and an understanding of the area’s traffic patterns. Due to the complexity of these calculations, route distance requires a call to the Directions Service, which will also return the duration of the route and even the path to plot visually on a map.

Whether you’re measuring distances around the globe or across town, use one of these approaches to help your users better understand their surroundings and make decisions. To explore even more tools for helping users get from here to there, check out the Google Maps Platform Routes APIs. And for more information on Google Maps Platform, visit our website.

Clay cityscape
Clay cityscape
Google Maps Platform
Get going with Google Maps Platform