Haversine Distance

Calculate distance between two GPS coordinates.

Code

General
R = 6371
to_rad = ->(d) { d * Math::PI / 180 }
dLat, dLon = to_rad.call(lat2 - lat1), to_rad.call(lon2 - lon1)
a = Math.sin(dLat/2)**2 + Math.cos(to_rad.call(lat1)) * Math.cos(to_rad.call(lat2)) * Math.sin(dLon/2)**2
return (R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))).round(2)

Parameters

Latitude 1 (degrees)

Longitude 1 (degrees)

Latitude 2 (degrees)

Longitude 2 (degrees)

Server

More Ruby Snippets