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

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

Susan Sarandon
Release: 2024-11-27 02:48:11
Original
387 people have browsed it

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

Calculating Distance Between Points in Google Maps V3

In Google Maps V3, the distance between two markers can be calculated using the Haversine formula. This formula takes into account the Earth's curvature to provide an accurate distance measurement.

Calculating the Distance

To calculate the distance between two points using the Haversine formula, follow these steps:

  1. Convert the latitudes and longitudes of the two points to radians using the rad function:
var rad = function(x) {
  return x * Math.PI / 180;
};
Copy after login
  1. Define a function that takes two points as input and returns the distance between them in meters:
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
};
Copy after login
  1. Call the getDistance function with the two points as arguments. The result will be the distance between the two points in meters.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template