From ef8c4a2943fcc6521ec93b817086169418342a83 Mon Sep 17 00:00:00 2001 From: Ben Burwell Date: Thu, 19 Nov 2015 10:54:22 -0500 Subject: Add distance calculation --- database.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'database.go') diff --git a/database.go b/database.go index 964915c..f0016bc 100644 --- a/database.go +++ b/database.go @@ -2,6 +2,7 @@ package main import ( "encoding/csv" + "math" "os" "strconv" "strings" @@ -14,6 +15,24 @@ type ZipcodeDetails struct { State string `json:"state"` } +const EarthRadiusMiles float64 = 3960 +const EarthRadiusKm float64 = 6373 +const DegToRad float64 = math.Pi / 180 + +func (zip1 *ZipcodeDetails) DistanceTo(zip2 *ZipcodeDetails) (float64, float64) { + // the arc distance ψ = arccos(sin φ_1 sin φ_2 cos(θ_1-θ_2) + cos φ_1 cos φ_2) + // where + // φ_k = 90° - latitude_k + // θ_k = longitude_k + // (both in radians) + theta1 := zip1.Longitude * DegToRad + theta2 := zip2.Longitude * DegToRad + phi1 := (90 - zip1.Latitude) * DegToRad + phi2 := (90 - zip2.Latitude) * DegToRad + arc := math.Acos(math.Sin(phi1)*math.Sin(phi2)*math.Cos(theta1-theta2) + math.Cos(phi1)*math.Cos(phi2)) + return arc * EarthRadiusMiles, arc * EarthRadiusKm +} + type ZipcodeDatabase struct { Zipcodes map[string]*ZipcodeDetails } -- cgit v1.2.3