Ruby Geocoder how to set a minimum .near distance

亡梦爱人 提交于 2019-12-11 02:07:43

问题


Using Alex Reisner's Ruby Geocoder and finding the .near method very useful. One question we have is how can we set it so that we can search for objects between distance x and distance y from the origin (at the moment the .near method only sets the max distance it seems): documentation here

We're looking for something like:

places = Place.near("Washington", min_distance, max_distance).reorder("score")

or some way of modifying the query so that we get the same effect without using .reorder (which we're using to sort on another "score" field)

The end result we want is the ability to have places ordered by score which are between x and y miles from the origin.


回答1:


AFAIK it is not natively implemented.

If using ActiveRecord, you can try to use Geocoder's private class methods (see from line 105 to 147) to roll your own "reverse" method, with an algorithm that should be more or less :

  • calculate bounding box for mininum distance query with Geocoder::Calculations#bounding_box
  • build SQL to find all records in bounding box AND with #distance_sql(lat,lon,options) >= min_distance

stuff this logic inside a where scope, chain it to near, and voilà! If you feel lazy you can even just copy/paste the whole method and just change the <= predicate.

On a side note, it would be great to file a feature request at geocoder's github, as i think it would be quick to implement for them.




回答2:


The query generated by Geocoder includes a distance column so all you need to do is add a condition for the minimum distance, for example:

Venue.near("Washington", max_distance).having("distance >= ?", min_distance)

Note that you need to use HAVING, not WHERE.



来源:https://stackoverflow.com/questions/14624669/ruby-geocoder-how-to-set-a-minimum-near-distance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!