diff options
author | Ben Burwell <ben@benburwell.com> | 2015-11-19 11:02:12 -0500 |
---|---|---|
committer | Ben Burwell <ben@benburwell.com> | 2015-11-19 11:02:12 -0500 |
commit | 81f58028b6e7473a78d8de0070bd6511287fbe0a (patch) | |
tree | 7b41af196f9a549d2067826aebcc6c1f26998776 /database.go | |
parent | fe22af7afdd2cffbd8395c7151f6e957db36f065 (diff) | |
parent | 5be5fe170fd317a0ed5b85b513ccf3f52e433521 (diff) |
Merge pull request #1 from benburwell/distance-calc
Add distance calculation functionality
Diffstat (limited to 'database.go')
-rw-r--r-- | database.go | 19 |
1 files changed, 19 insertions, 0 deletions
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 } |