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

How to Calculate the Distance Between Two Points Using Google Maps V3?

Susan Sarandon
Susan SarandonOriginal
2024-11-29 09:09:13913browse

How to Calculate the Distance Between Two Points Using Google Maps V3?

Determining Distance between Two Points using Google Maps V3

Calculating the distance between markers in Google Maps V3 can be achieved by leveraging the Haversine formula.

Haversine Formula:

To implement this formula, the following steps can be taken:

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
};

In this code:

  • rad() converts a value from degrees to radians.
  • getDistance() calculates the distance between two points p1 and p2 using the Haversine formula.
  • R is the Earth's mean radius.
  • dLat and dLong are the differences in latitude and longitude between the two points.
  • a is an intermediate value.
  • c is an intermediate value.
  • d is the distance in meters.

The above is the detailed content of How to Calculate the Distance Between Two Points Using 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