Search code examples
ruby-on-rails-3geolocationthinking-sphinx

Thinking Sphinx geodist search returns locations in a different city


I have Thinking Sphinx indexing locations all over the US and I need to find locations closest to a certain lat/lon. In the simplest example, I use the lat/lon of a particular city (lat/lon pulled from Google Maps API) and do a search, sorting by the closest location first.

The problem is, when I search for locations in New York City, it gives me results in Austin, Texas. When I search for location in Austin, I get Jersey Shore, Penn. Each city search gives me results in a completely different city. I'm not even sure where to begin with a problem like this.

Here is my index definition. (The location has an associated city object that also has a lat/lon, hence the location.latitude)

Location:

Thinking Sphinx

define_index do
    indexes :name
    indexes :description
    indexes city.name, :as => :city_name

    has "RADIANS(locations.latitude)",  :as => :latitude,  :type => :float
    has "RADIANS(locations.longitude)", :as => :longitude, :type => :float

    set_property :latitude_attr => :latitude, :longitude_attr => :longitude

    # set_property :delta => true
end

###############################################################

Without setting the latitude_attr property, I kept getting the error:

Sphinx Daemon returned error: index location_core: unknown latitude attribute 'latitude'

Search command: Location.search(:geo => [city.latitude, city.longitude], :order => "@geodist ASC, @relevance DESC", :per_page => 5)

Any help that can be provided to get me going in the right direction is appreciated.


Solution

  • "RADIANS(locations.latitude)" converts from degrees, which you are probably using in your database, so you have to convert :geo => [city.latitude, city.longitude] to Radians too. i.e.

    :geo => Geocoder::Calculations.to_radians([city.latitude, city.longitude])
    

    So i think its "working" because both is now degrees OR your database fields were Radians anyway and the convertion was not needed. But docs are saying:

    Keep in mind, though, that Sphinx needs these values to be floats, and tracking positions by radians instead of degrees. If this isn’t the case in your own database (which isn’t a surprise – most people store the values as degrees), then you’ll need to manually convert columns for the attributes:

    http://pat.github.com/ts/en/geosearching.html