Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Support for distance nearby(s) object for mongodb. #254

Open
maqen opened this Issue · 14 comments

4 participants

@maqen

Missing support for distance on results from obj.nearbys when using mongoid as data mapper.

Something similar to support in ActiveRecord would be great.

@maqen

https://github.com/ryanong/mongoid_spacial/blob/master/lib/mongoid_spacial/spacial/geo_near_results.rb

Maybe someone who is more hacker than me can use something from this?

@chopper

+1

@chopper

Are there any good workarounds for this?

@alexreisner
Owner

As a workaround you could implement a method on your model like this:

def distance_from(point)
  Geocoder::Calculations.distance_between([self.lat, self.lon], point)
end

The point argument can be a [lat,lon] array.

@chopper

Thanks @alexreisner. I'm not quite sure how to combine that with the geo_near query though.. i.e. how do I pass in the point argument to each of my models in the result set of my query? Do you have an example by any chance?

@alexreisner
Owner
some_place = [40.2345, -75.234]
nearby_place = Place.near(some_place).first
nearby_place.distance_from(some_place)
# => 23.5230984

Does that help?

@chopper

Hm not 100%. Basically I want to run a query to get every place in my db near a given location. Then I would like every resulting object to have a distance, which I then serialize. How would I go about that? i.e. how do I do the above, but for a list of objects that are returned by the query?

@alexreisner
Owner
some_place = [40.2345, -75.234]
nearby_places = Place.near(some_place)
nearby_places.map{ |place| place.distance_from(some_place) }

That will return an array of distances. Does that do it?

@chopper
@ghost

I get that the previous suggestion was faux code but since we are storing the lat and long in an array in Mongoid the correct implementation would be:

def distance_from(point)
  Geocoder::Calculations.distance_between([self.coordinates[1], self.coordinates[0]], point)
end

For those who need it.

@alexreisner
Owner

@chemicalfire Correct, thanks.

@chhopper It sounds like you'll need to store some_place in each object and implement a method called distance which calls distance_from with the correct argument.

@chopper

I see - I'll give that a shot and will report back. Just curious - Is there a reason this isn't implemented for Monogoid the way it is for Active Record?

@alexreisner
Owner

It's not simple to implement like it is in ActiveRecord, and I haven't put in the time to really investigate. Would welcome a pull request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.