Detecting User Location with Rails

So building my little web app (An Arabic tool to convert Arabic numbers to their text representation), I needed to detect user’s country to improve the site usability by improving the defaults.

After
researching, found this to be the simplest way possible. It does not
even require a database. As you will be connecting to third party
database.

– Create an account at IPInfoDB.com

– Once you register, you will get your api key.

– Download geo-ip Ruby Gem (gem has not been updated since March 2012, but it is still working like a charm with even with latest Rails 4)

– Now, all you need to do is to create an initializer file in the folder config/initializers (call it geo-ip):

GeoIp.api_key = ‘YOUR_API_KEY’

– Then you can get the ip of the user by this rails method:

user_ip = request.remote_ip

– From the received ip, you can now get location info of users by calling methods of the geo-ip gem:

country = GeoIp.geolocation(user_ip, :precision => :country)

For all geo ip methods, please the check out the gem documentation

Google Map Marker

Google Map Marker (Photo credit: [ Mooi ])

Advertisements

One response to “Detecting User Location with Rails

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: