Skip to content

Instantly share code, notes, and snippets.

@robmiller
Last active February 3, 2021 16:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save robmiller/6081238 to your computer and use it in GitHub Desktop.
Save robmiller/6081238 to your computer and use it in GitHub Desktop.
Ruby/SQLite code for finding places within a certain distance from another place. In other words, Ruby code that adds a "DISTANCE(lat1, lon1, lat2, lon2)" to SQLite, allowing you to select records based on the distance between two points of latitude and longitude. Magic! Adapted from the ObjectiveC version here: http://daveaddey.com/?p=71
db = SQLite3::Database.new ":memory:"
# A sample SQLite table; all that's necessary is the lat and log fields
db.execute <<-SQL
CREATE TABLE users (
email VARCHAR(255),
lat FLOAT,
lon FLOAT
)
SQL
# Insert/load your records here, if you like. Personally, I'm loading a CSV file.
def deg2rad(degrees)
# radians = degrees * (pi / 180)
degrees * 0.01745327
end
db.create_function('distance', 4) do |func, lat1, lon1, lat2, lon2|
lat1rad = deg2rad(lat1)
lat2rad = deg2rad(lat2)
func.result = acos(sin(lat1rad) * sin(lat2rad) + cos(lat1rad) * cos(lat2rad) * cos(deg2rad(lon2) - deg2rad(lon1))) * 6378.1
end
# That's it. You can now find records within a certain distance:
users_near_chelsea = db.execute('SELECT COUNT(*) FROM users WHERE DISTANCE(lat, lon, 51.48282, -0.17406) <= 80')
# (In that case, records where the location is within 80km of a randomly selected point near our office.)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment