Home >Web Front-end >JS Tutorial >How to Calculate the Distance Between Two Markers in Google Maps V3?

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 14:54:12854browse

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.

The above is the detailed content of How to Calculate the Distance Between Two Markers in Google Maps V3?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn