/google-directions

Ruby-wrapper for Google Directions API. Can return the drive time and driving distance between two places.

Primary LanguageRuby

Usage

directions = GoogleDirections.new(origin, destination, key: "GOOGLE_API_KEY")

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

Error situations

status: NOT_FOUND

If Google can’t recognize your places, the distance_in_miles and drive_time_in_minutes will each return 0. You can call

directions.status
and it should return “NOT_FOUND” (directions.status will also return any other Google API call statuses)

status: OVER_QUERY_LIMIT

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.status
and it should return “OVER_QUERY_LIMIT”

Installation

gem

rails 3.0/4.0

  1. gem ‘google_directions’ in your Gemfile
  2. bundle install
    from command line

Compatibility

Tested on Rails 2.3.8
Tested on Rails 4.0.1

Google maps API key

You’ll need a Google Map API key for using this service. You can get one here:

https://developers.google.com/maps/signup?csw=1

After you got the key, you need to add it to your request like this:

directions = GoogleDirections.new(origin, destination, key: "GOOGLE_API_KEY")

If you have a premium aka paid google maps account, you need to enter the private_key,
client and channel into that hash.

directions = GoogleDirections.new(origin, destination, private_key: "PRIVATE_KEY", client: "CLIENT_NAME", channel: "CHANNEL_NAME")

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

GoogleDirections.new(origin, destination).xml

And then nokogiri can cycle through each and you can pick out what you need.

License

Anyone can use this code in any way.