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

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

Patricia Arquette
Release: 2024-11-30 05:49:14
Original
353 people have browsed it

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

Calculating Distance Between Two Markers in Google Maps V3

Determining the distance between two points denoted by markers in Google Maps V3 is a common task faced by developers. This article provides a comprehensive solution to effectively calculate this distance.

To calculate the distance, you can leverage the Haversine formula. This formula accurately accounts for the curvature of the Earth, resulting in reliable distance calculations.

The implementation involves the following steps:

  1. Convert Latitudes and Longitudes to Radians:

    var rad = function(x) {
      return x * Math.PI / 180;
    };
    Copy after login
  2. Calculate Latitude and Longitude Differences:

    var dLat = rad(p2.lat() - p1.lat());
    var dLong = rad(p2.lng() - p1.lng());
    Copy after login
  3. Apply Haversine Formula:

    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);
    
    // Calculate the central angle
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    
    // Calculate the distance in meters
    var d = R * c;
    return d; // Distance in meters
    Copy after login
  4. Example Usage:

    var distance = getDistance(marker1, marker2);
    Copy after login

This method provides a robust way to calculate the distance between two markers on Google Maps V3, allowing developers to accurately display distances between locations on their maps.

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