Location-based search with Sphinx and acts_as_geocodable
Sphinx, everybody’s favorite search engine, has support for location-based search, giving you geo-aware, full-text searching. So now you can find all of the garage sales on Saturday within 20 miles that have LPs and a reel mower.
All you need to do is add latitude and longitude (in radians) to the index, allowing you to limit the results to records within a distance of a point. The hardest part is getting the coordinates, but acts_as_geocodable makes that really easy.
The three lines that start with
has add the geocode id, and the latitude and longitude in radians to the index. Our index doesn’t need the geocode id, but we have to add it so that ThinkingSphinx properly joins the geocodes table.
After you rebuild the index and start the daemon, you can search for records by location. Here’s an example of taking a zip code from a user and finding all records with in 20 miles. (Note: you will need to grab the latest version, 0.2.9, of Graticule for this next bit of code to work)
After looking up the coordinates of the zip code that the user entered, we do a search with the
:geo parameter, limiting the results using the special
@geodist condition. We have to pass in a range of floats that represent the distance of the points in meters
(and since the US is in the stone age, I’m converting from miles).
That’s all there is to it. Now go write some cool location-based search and comment here about it.