Haversine Distance Calculator

Compute great-circle distance in kilometers between coordinates and build a latitude and longitude bounding box for prefiltering.

GoData Integrity

Code

snippet
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)
}