Created
October 16, 2011 20:53
-
-
Save ajokela/1291406 to your computer and use it in GitHub Desktop.
Ruby/Rails - Distance between latitude/longitude points
This file contains hidden or 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
GeoName.find_by_sql("SELECT ordered.* FROM (SELECT gn.*, round(distance.d * 6371.0, 2) AS distance_km, round(distance.d * 6371.0 * 0.621371192, 2) as distance_miles FROM | |
(SELECT (2*atan2(sqrt(calcs.a), sqrt(1-calcs.a)))::numeric d, calcs.id FROM | |
(SELECT (sin(consts.dlat/2) * sin(consts.dlat/2) + sin(consts.dlon/2) * sin(consts.dlon/2) * cos(consts.lat1) * cos(consts.lat2)) as a, consts.id FROM | |
(SELECT f.id, abs((#{self.exif_data.latitude} - f.latitude)*(#{Math::PI}/180)) AS dlat, | |
abs((#{self.exif_data.longitude} - f.longitude)*(#{Math::PI}/180)) AS dlon, | |
#{self.exif_data.latitude} * (#{Math::PI}/180) as lat1, | |
f.latitude * (#{Math::PI}/180) as lat2 FROM geo_names f) consts) calcs) distance, | |
geo_names gn WHERE gn.id = distance.id ORDER BY distance.d ASC LIMIT 10) ordered ORDER BY random() LIMIT 1") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment