Reputation: 1780
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
Upvotes: 11
Views: 7570
Reputation: 1003
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.
Upvotes: 8
Reputation: 3281
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.
Upvotes: 6
Reputation: 16629
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
Upvotes: 1
Reputation: 11967
# app/models/user.rb
geocoded_by :ip_address,
:latitude => :lat, :longitude => :lon
after_validation :geocode
Snippet from geocoder site.
Upvotes: 1