Calculates the straight-line distance on a sphere. Fast and simple.
function haversine(lat1, lon1, lat2, lon2) {
const R = 6371; // Earth radius in km
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLon = (lon2 - lon1) * Math.PI / 180;
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1 * Math.PI / 180) *
Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
Pros: Fast, simple, good for short distances
Cons: Assumes Earth is a perfect sphere (it's actually an ellipsoid)
Calculates distance on an ellipsoid (Earth's actual shape). More accurate.
function vincenty(lat1, lon1, lat2, lon2) {
const a = 6378137, b = 6356752.314245, f = 1/298.257223563;
const L = (lon2 - lon1) * Math.PI / 180;
const U1 = Math.atan((1 - f) * Math.tan(lat1 * Math.PI / 180));
const U2 = Math.atan((1 - f) * Math.tan(lat2 * Math.PI / 180));
// ... iterative calculation (complex)
return distance / 1000; // Convert to km
}
Pros: Very accurate for geodetic calculations
Cons: More complex, slower computation
Calculates the actual route distance following roads. Best for towing services!
// Using OSRM (Open Source Routing Machine) API
const url = `https://router.project-osrm.org/route/v1/driving/
${lon1},${lat1};${lon2},${lat2}?overview=false`;
fetch(url)
.then(res => res.json())
.then(data => {
const distance = data.routes[0].distance / 1000;
console.log('Road distance:', distance, 'km');
});
Pros: Real-world accurate, includes road network
Cons: Requires API call, slower, needs internet
--
Use Road Distance (Method 3) for the most accurate pricing because:
Fallback: Use Haversine as a quick estimate or backup when API is unavailable.