Fabian de Pabian
Fabian de Pabian

Reputation: 619

Finding a gps locations near another one based on a dynamic radius

I have aGpsLocation model, this model has a latitude, a longitude and a radius property.

I want to find a GpsLocation based on its latitude and longitude and radius.

So lets say i am on location [52, 4], i want to find a GpsLocation instance that has these exact coordinates or is radius meters away.

I am using the geocoder gem but the near function does not do the job. Also tried monkey patching the near function so i can use a database column instead of a variable inside the query but still no luck, there are some mechanics that transform the lat/long to a range when providing a radius parameter.

Any help is appreciated

Upvotes: 1

Views: 236

Answers (1)

Brian
Brian

Reputation: 5481

Calculating the distance between two points on a sphere can be done using the Haversine formula. There is a gem called haversine that can help. Or, if you're using PostgreSQL, there is also the earthdistance module.

However, you may find it easier to relax your definition of "near" somewhat, as dealing with circles can be annoying. Instead, consider using squares or rectangles.

Say you define "near" as within 10 miles. If you treat that as a plus or minus factor around the latitude and longitude of a given point, then you can do a simple query to find all nearby points at once, rather than a series of Haversine calculations. You query might look something like this:

# Only accurate in the U.S.
MILES_PER_LATITUDE = 69.0
MILES_PER_LONGITUDE = 55.0

min_latitude = thisLocation.latitude - (10.0 / MILES_PER_LATITUDE)
max_latitude = thisLocation.latitude + (10.0 / MILES_PER_LATITUDE)
min_longitude = thisLocation.longitude - (10.0 / MILES_PER_LONGITUDE)
max_longitude = thisLocation.longitude + (10.0 / MILES_PER_LONGITUDE)

nearby_points = GpsLocation.where(latitude: min_latitude..max_latitude).where(longitude: min_longitude..max_longitude)

Upvotes: 1

Related Questions