"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Calculate the Distance Between Two Markers in Google Maps V3?

How to Calculate the Distance Between Two Markers in Google Maps V3?

Published on 2024-12-22
Browse:924

How to Calculate the Distance Between Two Markers in Google Maps V3?

How to Calculate Distance Between Markers in Google Maps V3

Calculating the distance between two points on a map is a common task, and Google Maps V3 provides a comprehensive API for doing so. One of the most straightforward methods is to use the Haversine formula, which calculates the distance between two geographic coordinates taking into account the Earth's curvature.

The Haversine Formula

The Haversine formula can be implemented in JavaScript as follows:

var rad = function(x) {
  return x * Math.PI / 180;
};

var getDistance = function(p1, p2) {
  var R = 6378137; // Earth's mean radius in meter
  var dLat = rad(p2.lat() - p1.lat());
  var dLong = rad(p2.lng() - p1.lng());
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2)  
    Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) *
    Math.sin(dLong / 2) * Math.sin(dLong / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;
  return d; // returns the distance in meter
};

Example Usage

To use the above formula to calculate the distance between two markers on a Google Map, simply pass the coordinates of the markers as arguments to the getDistance function. For example:

var marker1 = new google.maps.Marker({
  position: new google.maps.LatLng(51.508742, -0.120850),
  map: map
});

var marker2 = new google.maps.Marker({
  position: new google.maps.LatLng(40.712784, -74.005941),
  map: map
});

var distance = getDistance(marker1.getPosition(), marker2.getPosition());

The distance variable will now contain the distance between the two markers in meters.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3