Get a google maps API key, and store in your app under GOOGLE_MAPS_API_KEY
GOOGLE_MAPS_API_KEY = ‘your_api_key’
directions = GoogleDirections.new(origin, destination)
where origin and destination are strings of addresses or places that Google can find an address for. Example: “816 Meridian St., 37207”
Get drive time or distance of whole trip
drive_time_in_minutes = directions.drive_time_in_minutes
distance_in_miles = directions.distance_in_miles
Get the XML Google returns with every turn, or the API call URL
xml = directions.xml
xml_call = directions.xml_call
If Google can’t recognize your places, the distance_in_miles and drive_time_in_minutes will each return 0. You can call
directions.statusand it should return “NOT_FOUND” (directions.status will also return any other Google API call statuses)
If Google thinks you’ve hit their API too many times in day, or too rapidly, for your given IP address and API key; they might return OVER_QUERY_LIMIT. In this case distance_in_miles and drive_time_in_minutes will each return 0. You can call
directions.statusand it should return “OVER_QUERY_LIMIT”
- gem install google_directions
- add config.gem “google_directions” to your environment.rb file
- gem ‘google_directions’ in your Gemfile
bundle installfrom command line
script/plugin install git://github.com/joshcrews/google-directions-ruby.git
rails plugin install git://github.com/joshcrews/google-directions-ruby.git
Tested on Rails 2.3.8
Not yet tested on Rails 3. It probably is Rails 3 compatible, because it’s just a single class with a few methods. It’s probably compatible with every ruby project ever.
Google maps API key
You’ll need a Google Map API key
Include it as the constant GOOGLE_MAPS_API_KEY in an app configuration file (environment.rb, config/initializers/api_keys.rb)
Need turn-by-turn directions?
Not yet included in this gem, but you can do it with nokogiri to parse the XML that comes back when you do
And then nokogiri can cycle through each and you can pick out what you need.
Anyone can use this code in any way.