Rails 4 - How would I automatically detect a user&

2019-05-27 11:24发布

I currently have a working app and I would like to have Rails detect a visitor's location by the IP address and display the city and state on the homepage of my website. For example, it would display "Hello {Name} from City, State".

Visitors do not have to enter anything. I'm aware of things like GeoIP and Geocode. As far as I know about them, they are used to search for locations from IP or vice versa but they require manually inputting the info.

I need it to do it automatically as soon as the user visits my homepage. I have a Post Controller and a home page, and I just want to add some code to my home page's HAML to display the info. I plan to categorize user's posts based on location, which will be automatically filled in (I currently have a location field that user's must enter manually). If you can show me how to do that too, that would be great.

For a live example of what I'm needing, visit weather.com and you'll see your city (and the weather) on the homepage.

Additional info: I'm fairly new to Rails 4 (started 2 weeks ago) so please show me the simplest way and point me to video resources if possible.

3条回答
放荡不羁爱自由
2楼-- · 2019-05-27 11:59

One more solution is to use ruby gem for Yandex locator (https://tech.yandex.ru/locator/). Yandex locator is a service that finds mobile devices in a region delineated by a circle. The service returns longitude, latitude and precision. https://github.com/sergey-chechaev/yandex_locator

client = YandexLocator::Client.new(api_key: 'api key', version: '1.0')
result = client.lookup(ip: { address_v4: '178.247.233.3' })
result.position
# => {"altitude"=>0.0, "altitude_precision"=>30.0, "latitude"=>41.00892639160156, "longitude"=>28.96711158752441, "precision"=>100000.0, "type"=>"ip"}
查看更多
趁早两清
3楼-- · 2019-05-27 12:05

There are lots of services that provide RESTful JSON APIs which will give you location data based on the IP address, for example: http://www.telize.com/

All you need to do is in your controller, catch the source of the HTTP request (Rack::Request) via request.env['REMOTE_ADDR'] and feed to the Geo API.

查看更多
倾城 Initia
4楼-- · 2019-05-27 12:06

Add to the gemfile

gem 'geocoder'

run bundle install and restart your server

Put <%= request.location.city %> in the view you want the city name to appear in.

查看更多
登录 后发表回答