Using the geocoder gem for rails, how do i get the visitor's city?
Asked Answered
K

4

11

https://github.com/alexreisner/geocoder

I can't find documentation to show the visitor's city from ip address? I know how to with HTML5, but I would like to use the value geocoder has. Thanks

Komatik answered 9/4, 2012 at 14:12 Comment(0)
P
8

It took a couple of hours for me to realize that the answer is pretty simple:

request.location.city

Geocoder page has this example but I thought that I would need to declare request but no, nothing more is needed.

If you don't have Geocoder you have to install the gem but nothing besides that.

Pigment answered 19/12, 2013 at 20:36 Comment(2)
when i do this , console shows the empty result . while i'm on the planet earth ;)Chrystel
When I follow this example, I get a NameError that says "request" is undefined. Why did you not have the same problem?Does
N
6

How I did it was -

location = Geokit::Geocoders::IpGeocoder.geocode(source_ip)
city = location.city
country = location.country

Here, source_ip is a string object.

Notum answered 9/4, 2012 at 16:56 Comment(0)
S
1
# app/models/user.rb
geocoded_by :ip_address,
  :latitude => :lat, :longitude => :lon
after_validation :geocode

Snippet from geocoder site.

Smile answered 9/4, 2012 at 14:33 Comment(1)
I'm actually looking for how it returns the "nearbys" method results for visitors, not users.Komatik
R
1

You could do it in 2 different ways

1) If you could get visitors city/ address as a string then geocoder will automatically convert that in to latitude and longitude

class Message < ActiveRecord::Base
  geocoded_by :full_address
  after_validation :geocode

  def full_address
    "#{city}, Sri Lanka"
  end

end

2) Or else you will have to track the ip of the visitor, example is in the home page on the 'geocoder' gem

NOTE: And you could use near by method as follows

<Active Record Object List>.near(<City Name>, <distance>, :order => :distance)

Ex: @messages = @messages.near("colombo", 10, :order => :distance)

and there is a super-duper screen cast by ryan in railscasts

Ratio answered 9/4, 2012 at 15:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.