Last active
August 29, 2015 14:16
-
-
Save lorenzosinisi/857fb435d02b95d16c74 to your computer and use it in GitHub Desktop.
Heversine Rails to check if there are people around me
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def distance loc1, loc2 | |
rad_per_deg = Math::PI/180 # PI / 180 | |
rkm = 6371 # Earth radius in kilometers | |
rm = rkm * 1000 # Radius in meters | |
dlat_rad = (loc2[0]-loc1[0]) * rad_per_deg # Delta, converted to rad | |
dlon_rad = (loc2[1]-loc1[1]) * rad_per_deg | |
lat1_rad, lon1_rad = loc1.map {|i| i * rad_per_deg } | |
lat2_rad, lon2_rad = loc2.map {|i| i * rad_per_deg } | |
a = Math.sin(dlat_rad/2)**2 + Math.cos(lat1_rad) * Math.cos(lat2_rad) * Math.sin(dlon_rad/2)**2 | |
c = 2 * Math::atan2(Math::sqrt(a), Math::sqrt(1-a)) | |
rm * c # Delta in meters | |
end | |
people = [[52.4920692, 13.40], [52.4920893, 0.40], [52.4920894, 13.40], [52.4920895, 0.40]] | |
mylocation = [52.5038, 13.41] | |
people.each do |lat, lon| | |
if (distance mylocation, [lat, lon]) < 50000 | |
puts "#{lat} and #{lon} is close here" | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment