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

kinet
  • 1,790
  • 3
  • 20
  • 32

4 Answers4

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.

  • when i do this , console shows the empty result . while i'm on the planet earth ;) – Mani Sep 28 '15 at 10:12
  • When I follow this example, I get a NameError that says "request" is undefined. Why did you not have the same problem? – calyxofheld Aug 14 '16 at 20:46
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.

mridula
  • 3,203
  • 3
  • 32
  • 55
1
# app/models/user.rb
geocoded_by :ip_address,
  :latitude => :lat, :longitude => :lon
after_validation :geocode

Snippet from geocoder site.

Mikhail Nikalyukin
  • 11,867
  • 1
  • 46
  • 70
  • I'm actually looking for how it returns the "nearbys" method results for visitors, not users. – kinet Apr 09 '12 at 14:38
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

sameera207
  • 16,547
  • 19
  • 87
  • 152