Skip to content

Instantly share code, notes, and snippets.

@shayanjm
Created April 12, 2015 22:01
Show Gist options
  • Save shayanjm/644d895c1fad80b49919 to your computer and use it in GitHub Desktop.
Save shayanjm/644d895c1fad80b49919 to your computer and use it in GitHub Desktop.
"Reverse Haversine" Formula implementation in Clojure
; "Reverse haversine" to derive lat/long from start point, bearing (degrees clockwise from north), & distance (km)
; φ2 = asin( (sin φ1 ⋅ cos δ) + (cos φ1 ⋅ sin δ ⋅ cos θ) )
; λ2 = λ1 + atan2( sin θ ⋅ sin δ ⋅ cos φ1, cos δ − sin φ1 ⋅ sin φ2 )
; where φ is latitude, λ is longitude, θ is the bearing (clockwise from north), δ is the angular distance d/R; d being the distance travelled, R the earth’s radius
(defn reverse-haversine
"Implementation of the reverse of Haversine formula. Takes one set of latitude/longitude as a start point, a bearing, and a distance, and returns the resultant lat/long pair."
[{lon :lng lat :lat bearing :bearing distance :distance}]
(let [R 6378.137 ; Radius of Earth in km
lat1 (Math/toRadians lat)
lon1 (Math/toRadians lon)
angdist (/ distance R)
theta (Math/toRadians bearing)
lat2 (Math/toDegrees (Math/asin (+
(* (Math/sin lat1) (Math/cos angdist))
(* (Math/cos lat1) (Math/sin angdist) (Math/cos theta)))))
lon2 (Math/toDegrees (+ lon1
(Math/atan2
(* (Math/sin theta) (Math/sin angdist) (Math/cos lat1))
(- (Math/cos angdist) (* (Math/sin lat1) (Math/sin lat2))))))]
{:lat lat2
:lng lon2}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment