Haversine Distance Calculator
Compute great-circle distance in kilometers between coordinates and build a latitude and longitude bounding box for prefiltering.
Code
package main
import (
"fmt"
"math"
)
const earthRadiusKm = 6371.0088
type Point struct {
Lat float64
Lon float64
}
func HaversineKm(a, b Point) float64 {
phi1 := a.Lat * math.Pi / 180
phi2 := b.Lat * math.Pi / 180
dPhi := (b.Lat - a.Lat) * math.Pi / 180
dLambda := (b.Lon - a.Lon) * math.Pi / 180
h := math.Sin(dPhi/2)*math.Sin(dPhi/2) +
math.Cos(phi1)*math.Cos(phi2)*math.Sin(dLambda/2)*math.Sin(dLambda/2)
return 2 * earthRadiusKm * math.Asin(math.Sqrt(math.Min(1, h)))
}
func BoundingBox(center Point, radiusKm float64) (minLat, minLon, maxLat, maxLon float64) {
latDelta := radiusKm / 111.32
cosine := math.Cos(center.Lat * math.Pi / 180)
var lonDelta float64
if math.Abs(cosine) < 1e-6 {
lonDelta = 180
} else {
lonDelta = radiusKm / (111.32 * cosine)
}
return center.Lat - latDelta, center.Lon - lonDelta, center.Lat + latDelta, center.Lon + lonDelta
}
func main() {
london := Point{Lat: 51.5074, Lon: -0.1278}
paris := Point{Lat: 48.8566, Lon: 2.3522}
fmt.Printf("london-paris: %.1f km\n", HaversineKm(london, paris))
minLat, minLon, maxLat, maxLon := BoundingBox(london, 10)
fmt.Printf("box: lat %.4f..%.4f lon %.4f..%.4f\n", minLat, maxLat, minLon, maxLon)
fmt.Println("inside box:", HaversineKm(london, Point{Lat: 51.55, Lon: -0.10}) < 10)
}How the snippet works
Structurally, expect the functions HaversineKm, BoundingBox and main and nothing else.
Using it
Signature: func HaversineKm(a, b Point) float64
Running the file prints labeled results such as london-paris:, box: lat, inside box: — each operation’s effect is visible in the output.
The demo flow inside main is HaversineKm and BoundingBox — run the file to see it end to end.
Key statements
return center.Lat - latDelta, center.Lon - lonDelta, center.Lat + latDelta, center.Lon + lonDelta
return 2 * earthRadiusKm * math.Asin(math.Sqrt(math.Min(1, h)))
Interactive Tools for This Topic
GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
FAQ
- What does Haversine Distance Calculator print when run?
- Run it as a complete program — the output lines carry labels such as `london-paris:`, `box: lat`, `inside box:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.