Keywords: Haversine formula | geographic distance calculation | Google Maps API
Abstract: This article provides an in-depth exploration of the Haversine formula for calculating distances between two points on the Earth's surface, analyzing the reasons for discrepancies between formula results and Google Maps displayed distances. Through detailed mathematical analysis and JavaScript implementation examples, it explains the fundamental differences between straight-line distance and driving distance, while introducing more precise alternatives including Lambert's formula and Google Maps API integration. The article includes complete code examples and practical test data to help developers understand appropriate use cases for different distance calculation methods.
Introduction
When developing location-based applications, accurately calculating distances between two points is a common requirement. Many developers encounter situations where distances calculated using the Haversine formula differ significantly from those displayed by Google Maps. This article uses a specific case study to deeply analyze the reasons for these discrepancies and explores the principles and applications of different distance calculation methods.
Problem Context and Case Analysis
Consider this practical scenario: calculating the distance between two coordinate points in Sweden, Point A at 59.3293371,13.4877472 and Point B at 59.3225525,13.4619422. A developer's JavaScript function implementing the Haversine formula returns 1.6 kilometers, while Google Maps shows a driving distance of 2.2 kilometers.
Here is the original problematic code implementation:
function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
var R = 6371; // Earth radius in kilometers
var dLat = deg2rad(lat2-lat1);
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in kilometers
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180);
}
Haversine Formula Principle Analysis
The Haversine formula is a mathematical method for calculating great-circle distances between two points on a sphere. A great circle is the largest circle that can be drawn on a sphere, passing through its center, and the great-circle distance represents the shortest path between two points on the sphere's surface.
The core mathematical principles are based on spherical trigonometry:
- First convert latitude and longitude differences to radians
- Use the haversine function to calculate the central angle
- Convert angular distance to linear distance using Earth's radius
An improved code implementation follows:
function calculateGreatCircleDistance(latitude1, longitude1, latitude2, longitude2) {
const EARTH_RADIUS_KM = 6371;
// Convert degrees to radians
const toRadians = (degrees) => degrees * Math.PI / 180;
const lat1Rad = toRadians(latitude1);
const lat2Rad = toRadians(latitude2);
const deltaLat = toRadians(latitude2 - latitude1);
const deltaLon = toRadians(longitude2 - longitude1);
// Haversine formula calculation
const a = Math.sin(deltaLat/2) * Math.sin(deltaLat/2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(deltaLon/2) * Math.sin(deltaLon/2);
const centralAngle = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
const distance = EARTH_RADIUS_KM * centralAngle;
return distance;
}
Root Causes of Distance Discrepancies
The Haversine formula calculates "straight-line distance" or "great-circle distance" - the shortest path between two points on a sphere's surface. This distance is often called "as the crow flies" distance, assuming unobstructed direct flight.
Google Maps displays 2.2 kilometers as driving distance, which considers:
- Actual road network layout and curvature
- Traffic regulations and one-way restrictions
- Terrain variations and obstacle avoidance
- Specific route planning algorithms
Using the improved function to calculate our case coordinates:
const distance = calculateGreatCircleDistance(59.3293371, 13.4877472, 59.3225525, 13.4619422);
console.log(distance.toFixed(3)); // Output: 1.652
This result matches Wolfram Alpha's calculation, validating the Haversine formula's correctness.
More Precise Distance Calculation Methods
Lambert's Formula
Since Earth is not a perfect sphere but an ellipsoid, using Lambert's formula provides higher accuracy. Lambert's formula accounts for Earth's flattening, achieving precision within 10 meters over thousands of kilometers.
Basic form of Lambert's formula:
function lambertDistance(lat1, lon1, lat2, lon2) {
const EQUATORIAL_RADIUS = 6378137; // Earth equatorial radius in meters
const FLATTENING = 1/298.257223563; // Earth flattening
// Complex ellipsoid calculation process
// Includes reduced latitude calculation, central angle computation
// Implementation involves extensive mathematical operations
return distance; // Returns more precise distance
}
Google Maps API Integration
For applications requiring actual route distances, directly using mapping APIs is recommended:
// Google Maps Geometry library distance calculation
const distance = google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(lat1, lng1),
new google.maps.LatLng(lat2, lng2)
);
// Google Maps Directions API for driving distance
const directionsService = new google.maps.DirectionsService();
directionsService.route({
origin: new google.maps.LatLng(lat1, lng1),
destination: new google.maps.LatLng(lat2, lng2),
travelMode: google.maps.TravelMode.DRIVING
}, function(result, status) {
if (status === google.maps.DirectionsStatus.OK) {
const drivingDistance = result.routes[0].legs[0].distance.value / 1000; // Convert to kilometers
console.log(drivingDistance);
}
});
Application Scenarios and Selection Guidelines
Choose appropriate distance calculation methods based on application requirements:
- Haversine Formula: Suitable for straight-line distance estimation, proximity searches, geofencing
- Lambert's Formula: Scientific applications requiring high-precision distance calculations
- Mapping APIs: Navigation and logistics applications needing actual route distances
Additional considerations in practical development:
- Earth radius selection affects calculation accuracy
- Coordinate system consistency (WGS84, etc.)
- Numerical computation precision handling
Conclusion
The Haversine formula is effective for calculating straight-line distances between points on Earth's surface, but its results fundamentally differ from actual driving distances. Developers should select appropriate distance calculation methods based on specific application scenarios: Haversine formula suffices for straight-line estimation, while mapping APIs should be used for actual navigation requirements. Understanding these differences helps develop more accurate and practical location-based applications.