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:
Convert Latitudes and Longitudes to Radians:
var rad = function(x) { return x * Math.PI / 180; };
Calculate Latitude and Longitude Differences:
var dLat = rad(p2.lat() - p1.lat()); var dLong = rad(p2.lng() - p1.lng());
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
Example Usage:
var distance = getDistance(marker1, marker2);
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!