Rails 4 - How would I automatically detect a user's location and display it on the web app?

孤街醉人 提交于 2019-12-06 07:03:14

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.

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.

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"}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!