Getting Location in Ruby
While the HTML5 geolocation is great, its not available if you are only operating in a command line interface (CLI). Thus, I’d like to first point out a way to get location when your ruby program is command line only.
Location in CLI Only Environment
This is a very simple way to get surprisingly accurate (at least in my few tests in NYC) location information using the IP of the computer running the Ruby app, Nokogiri web scraping, and one’s IP address.
You will need gem ‘nokogiri’ and to require ‘open-uri’
1 2 3 4 5 6 7 8
This will query the site http://freegeoip.net/json which in turn determines your public IP address and matches it against a database. Nokogiri then scrapes this result and then I use a Ruby regex match object to parse out the latitude and a longitude. Finally I return an array containing latidue and longitude.
I found that http://freegeoip.net/json was fairly accurate. There is a gem called geocoder that seems to use the same database but it seemed to do a lot more and required active record. When I created this, I already was using nokogiri in the project so this was an easy add on and just seemed simpler.
Location using HTML5 in a Sinatra environment
The user then clicks the Submit Location button which will do a post request to the server at the address specified in the form’s action attribute. Sinatra can then grab lat and long from the parmas variable and render a new page using erb or preform a redirect.
I’ll note that there may be a better way to do the following but this method seemed good enough and was within the scope of my current knowledge.
This methods assume you are running a Ruby Sintra web based frame work.
First, you would set a
get controller for your page that will request the location from the user’s browser using html. I used by root index page for this.
1 2 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
Setup up a post controller that receives the post request from the form submission.
1 2 3 4 5 6
The parmas var is automatically passed to the post method in Sinatra and you can then extract the lat and lon by calling the symbol version of their names as they were labled in the form. You can then pass the location info to another method or make them directly available to the erb template.
Using both HTML5 Geolocation with an IP based fallback
1 2 3 4 5 6 7 8 9 10 11
HTML5 Geolocation code based on http://www.w3schools.com/ templates