Tom Hammond
Tom Hammond

Reputation: 6080

Rails Comparing Latitude/Longitude

Let's say I have 1000 objects that have a latitude/longitude value.

What I'd like to do is send up a user's latitude/longitude and return the 50 closest objects. I know how I could do that with one value - if I had just a latitude, but location seems different with the two values so I'm not sure how I'd do that.

What would be the best way to accomplish that? Feel free to point me to a tutorial or anything - I'm very new to using location in rails :).

Upvotes: 1

Views: 834

Answers (2)

Steve Wilhelm
Steve Wilhelm

Reputation: 6260

This is a classic computer science problem called the nearest neighbor problem. See this wikipedia article for two popular solutions.

The article describes the point with x, y coordinates. You can just substitute longitude for x and latitude for y.

Upvotes: 1

lurker
lurker

Reputation: 58224

There isn't any detail in the original question regarding data representation, but let's suppose you have a list of lat/long values in the form, [lat, long] in a list, locations. Let's suppose further you have a metric method for the distance between them, dist(lat, long).

Then this will collect all of the location pair combinations and their respective distances as a collection of triples, [dist, p1, p2]:

location.combination(2).collect { |p| [dist(p[0], p[1]), p[0], p[1]] }

You can then sort this which will order by distance, and pick off the top 50:

location.combination(2).collect { |p| [dist(p[0], p[1]), p[0], p[1]] }.sort.first(50)

You'd have to see if it works with 1,000 objects, as this will create 999,000 combinations initially and I don't know what the Ruby array capacity is.

Upvotes: 1

Related Questions