Straight-line distance
If you only need the distance over the Earth's surface between two points, compute it locally with the Haversine formula. It is fast, needs no network call and ignores roads entirely.
function haversineKm(a, b) {
const R = 6371.0088; // mean Earth radius in km
const rad = (deg) => (deg * Math.PI) / 180;
const dLat = rad(b.lat - a.lat);
const dLon = rad(b.lon - a.lon);
const h =
Math.sin(dLat / 2) ** 2 +
Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLon / 2) ** 2;
return 2 * R * Math.asin(Math.sqrt(h));
}
haversineKm({ lat: 51.5033635, lon: -0.1276248 }, { lat: 51.5079, lon: -0.0877 }); Road distance
For driving, deliveries and logistics, road distance is usually what you want. A routing API follows the road network for the chosen travel mode and returns distance, estimated duration and the route geometry. The road distance is always at least as long as the straight-line distance.
Calculate road distance with Mapsi
POST an origin and destination to /v1/route. The response includes distance_km, duration_sec, per-leg figures and a polyline field. Despite its name, polyline holds a GeoJSON LineString, so you can add it directly
to a map without decoding anything.
API
Calculate route distance
POST /v1/routecurl -X POST \
-H "Content-Type: application/json" \
-H "X-API-Key: YOUR_MAPSI_API_KEY" \
https://mapsi.dev/v1/route \
-d '{"origin":{"lat":51.5033635,"lon":-0.1276248},"destination":{"lat":51.5079,"lon":-0.0877},"mode":"auto","units":"km"}'const response = await fetch("https://mapsi.dev/v1/route", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-API-Key": "YOUR_MAPSI_API_KEY"
},
body: JSON.stringify({
"origin": {
"lat": 51.5033635,
"lon": -0.1276248
},
"destination": {
"lat": 51.5079,
"lon": -0.0877
},
"mode": "auto",
"units": "km"
})
});
const data = await response.json();
console.log(data.distance_km, data.duration_sec);import requests
response = requests.post(
"https://mapsi.dev/v1/route",
headers={"X-API-Key": "YOUR_MAPSI_API_KEY"},
json={
"origin": {
"lat": 51.5033635,
"lon": -0.1276248
},
"destination": {
"lat": 51.5079,
"lon": -0.0877
},
"mode": "auto",
"units": "km"
},
)
data = response.json()
print(data){
"success": true,
"waypoint_count": 2,
"distance_km": 4.15,
"duration_sec": 512,
"legs": [{ "from": 0, "to": 1, "distance_km": 4.15, "duration_sec": 512 }],
"polyline": {
"type": "LineString",
"coordinates": [[-0.127645, 51.503251], [-0.127566, 51.503246], ...]
}
}