Skip to main content

How to calculate the distance between 2 markers (coordinates) in Google Maps with JavaScript

One of the most recurrent needs of developers when working with Google Maps, is how to obtain the distance between 2 different points on the map, usually defined by Markers or just by plain coordinates, for example given the following code:

var map, markerA, markerB;

// Callback executed when Google Maps script has been loaded
function initMap() {
    // 1. Initialize map
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10,
        center: {
            lat: 6.066385702972249, 
            lng: -74.07493328924413
        }
    });

    // 2. Put first marker in Bucaramanga
    markerA = new google.maps.Marker({
        position: {
            lat: 7.099473939079819, 
            lng: -73.10677064354888
        },
        map: map,
        icon: {
            url: 'http://maps.google.com/mapfiles/kml/pushpin/red-pushpin.png'
        },
        title: "Marker A"
    });

    // 3. Put second marker in Bogota
    markerB = new google.maps.Marker({
        position: {
            lat: 4.710993389138328, 
            lng: -74.07209873199463
        },
        map: map,
        icon: {
            url: 'http://maps.google.com/mapfiles/kml/pushpin/red-pushpin.png'
        },
        title: "Marker B"
    });
}   

This will place the 2 markers that appear on the picture of this article. According to Google, we can know that the flight distance from Bucaramanga to Bogota is about 280 Kilometers:

Bucaramanga - Bogota Flight Distance

So we will theorically expect an approximated value from our methods to obtain the distance between the 2 coordinates. In this article, we will show you 2 ways to obtain the distance between 2 markers or coordinates with JavaScript in Google Maps.

A. Using Google Geometry Module

By default, Google provides a custom way to obtain the distance between 2 points on the map using the Geometry library. You need to include this library by appending the &libraries get parameter to the request URL of the Google Maps JS API:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=initMap&libraries=geometry"></script>

Once you are sure that have loaded this library, you can now obtain the distance between 2 coordinates (LatLng object) from Google Maps through the google.maps.geometry.spherical.computeDistanceBetween method. For example, if you want to obtain the distance between 2 markers, you may simply run the following instruction:

// Obtain the distance in meters by the computeDistanceBetween method
// From the Google Maps extension
var distanceInMeters = google.maps.geometry.spherical.computeDistanceBetween(
    markerA.getPosition(),
    markerB.getPosition()
);

// Outputs: Distance in Meters:  286562.7470149898
console.log("Distance in Meters: ", distanceInMeters);

// Outputs: Distance in Kilometers:  286.5627470149898
console.log("Distance in Kilometers: ", (distanceInMeters * 0.001));

As you can see, the computeDistanceBetween method expects as first and second argument a LatLng object. It will compute the distance from those 2 parameters and return the value in meters. Is up to you to change the units mathematically to Miles or Kilometers. Alternatively if you are not using markers, you may provide the mentioned LatLng object as arguments with the direct coordinates:

// Obtain the distance in meters by the computeDistanceBetween method
// From the Google Maps extension using plain coordinates
var distanceInMeters = google.maps.geometry.spherical.computeDistanceBetween(
    new google.maps.LatLng({
        lat: 7.099473939079819, 
        lng: -73.10677064354888
    }),
    new google.maps.LatLng({
        lat: 4.710993389138328, 
        lng: -74.07209873199463
    })
);

// Outputs: Distance in Meters:  286562.7470149898
console.log("Distance in Meters: ", distanceInMeters);

// Outputs: Distance in Kilometers:  286.5627470149898
console.log("Distance in Kilometers: ", (distanceInMeters * 0.001));

B. Using the Haversine formula

If instead of relying on Google Maps, you can calculate the same distance based on the Haversine Formula, an important equation used in navigation, this provides great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".

To start, include the 2 following functions in your code:

/**
 * Converts degrees to radians.
 * 
 * @param degrees Number of degrees.
 */
function degreesToRadians(degrees){
    return degrees * Math.PI / 180;
}

/**
 * Returns the distance between 2 points of coordinates in Google Maps
 * 
 * @see https://stackoverflow.com/a/1502821/4241030
 * @param lat1 Latitude of the point A
 * @param lng1 Longitude of the point A
 * @param lat2 Latitude of the point B
 * @param lng2 Longitude of the point B
 */
function getDistanceBetweenPoints(lat1, lng1, lat2, lng2){
    // The radius of the planet earth in meters
    let R = 6378137;
    let dLat = degreesToRadians(lat2 - lat1);
    let dLong = degreesToRadians(lng2 - lng1);
    let a = Math.sin(dLat / 2)
            *
            Math.sin(dLat / 2) 
            +
            Math.cos(degreesToRadians(lat1)) 
            * 
            Math.cos(degreesToRadians(lat1)) 
            *
            Math.sin(dLong / 2) 
            * 
            Math.sin(dLong / 2);

    let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    let distance = R * c;

    return distance;
}

The first function allows you to convert a degree into radians, necessary in the function of interest, the getDistanceBetweenPoints method. In this case, with a slightly modification from the original snippet of RosettaCode. The function receives four arguments that correspond respectively to the latitude and longitude values of both points. This solution doesn't rely on Google Maps so it can be used in other projects as well:

// Obtain the distance in meters using the haversine formula
var distanceInMeters = getDistanceBetweenPoints(
    // LatA
    7.099473939079819,
    // LongA
    -73.10677064354888,
    // LatB
    4.710993389138328,
    // LongB
    -74.07209873199463
);

// Outputs: Distance in Meters:  286476.96153465303
console.log("Distance in Meters: ", distanceInMeters);

// Outputs: Distance in Kilometers:  286.476961534653
console.log("Distance in Kilometers: ", (distanceInMeters * 0.001));

Happy coding !

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...