简体   繁体   中英

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

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

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.

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.

# app/models/user.rb
geocoded_by :ip_address,
  :latitude => :lat, :longitude => :lon
after_validation :geocode

Snippet from geocoder site .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM