4

How would you get locations that are nearby your current location with geocoder gem for ruby on rails 3.2.x?

I know that to find locations near one of your other locations you would use

@myClass.nearbys(50)

but I would like them nearby the browsers location (request.location) instead of nearby another one of my locations.

Such that it would be similar to

request.location.nearby(50)

or something to that effect.

How can this be achieved?

Thanks

Chris Valentine
  • 1,557
  • 1
  • 19
  • 36

1 Answers1

7

If you have the longitude and latitude of the user's location, you can make a query like so

location_info = request.location

@locations = Location.near([location_info.latitude, location_info.longitude], radius_distance_you_want_to_include)

It would also be expected that your table, i.e. in the above example Location there should be lat and lon fields.

Is this something you were looking for?

EDIT: I'm not sure if request.location will work in the model. In case it doesn't, you can always set it as a parameter into a model method inside your controller so that your logic stays separated. But if you can, keep request.location in the model.

thank_you
  • 11,001
  • 19
  • 101
  • 185
  • Yes, if I can find out how to get longitude/latitude from request.location. – Chris Valentine Apr 19 '13 at 16:55
  • Ahh so that's what you want. Ok let me look into that then. – thank_you Apr 19 '13 at 17:00
  • I think it is just request.location.longitude, and request.location.latitude, but trying to test that. – Chris Valentine Apr 19 '13 at 17:07
  • 1
    That should do it. Those attributes do exist for `request.location`. What you can do is run `request.location.inspect` to see what's exactly being returned on your test environment. However, be aware that some user's may deny websites access to their geo coordinates. Updated my answer with the latest code as well. – thank_you Apr 19 '13 at 17:17
  • Yes thanks this helped. I also had issues due to my local development IP address actually being 127.0.0.1 but should be able to get around that with something similar to this http://stackoverflow.com/questions/6115589/geocoder-how-to-test-locally-when-ip-is-127-0-0-1 – Chris Valentine Apr 19 '13 at 17:52
  • this solution for overriding IP during testing seemed simplest. http://blog.corykaufman.com/2012/09/11/geocode-localhost.html – Chris Valentine Apr 19 '13 at 19:15