Skip to content
This repository

Google places for address function

Processed Results

Gmaps4rails.places_for_address(address, key, keyword = nil, radius = 7500, lang="en", raw = false) retrieves an Array of Hash of Google Places records.

Please note: Since Google Places only works as radius search around given geo coordinates, you have to pass a geocodeable 'address' to this method which gets geocoded first. After that, a Places search with radius 'radius' (given in meters) is perfomed.

Also Google Places requires an API key (parameter 'key'). This just doesn't work without it.

Hint: If you leave keyword to be nil then it returns all Places around that address.

Each hash is made up: lat, lng, name, reference, vicinity, full_data retrieved by Google. The field 'full_data' includes everything Google Places offers (see Google Places API Docs for details).

Here is an example:

Gmaps4rails.places_for_address('Queenstown, New Zealand', '<your_api_key>', 'Bungy')
=> [
    {:lat=>-45.03087, :lng=>168.660103, :name=>"AJ Hackett Bungy Queenstown", :reference=>"CoQBcwAAAEKxQUafrE834-akE3Y1m8Yu5a6N0QsIxc2umZnWnSKDSMbFNMsXOJ9iSh1gvfV7Lgai6qcNTQQ2rkhpX988A6rz9HHsRVGvNuxYdBAVwVJDvXZUSOf6dnpnqWlQ6F9y2ASjXEPzfioTb0fiYVFyvb1XifUIOS8PXbN-T60IoTVyEhC8V5V30viXelcPM8-aZDNMGhRjoJySWw66-57dv2oL_HIC8k7-ww", :vicinity=>"Crn of Camp and Shotover Street, Queenstown", :full_data=>{"geometry"=>{"location"=>{"lat"=>-45.03087, "lng"=>168.660103}}, "icon"=>"http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png", "id"=>"b53345c3885269e14d9701fe039e5c3234c8dea1", "name"=>"AJ Hackett Bungy Queenstown", "opening_hours"=>{"open_now"=>false}, "rating"=>4.8, "reference"=>"CoQBcwAAAEKxQUafrE834-akE3Y1m8Yu5a6N0QsIxc2umZnWnSKDSMbFNMsXOJ9iSh1gvfV7Lgai6qcNTQQ2rkhpX988A6rz9HHsRVGvNuxYdBAVwVJDvXZUSOf6dnpnqWlQ6F9y2ASjXEPzfioTb0fiYVFyvb1XifUIOS8PXbN-T60IoTVyEhC8V5V30viXelcPM8-aZDNMGhRjoJySWw66-57dv2oL_HIC8k7-ww", "types"=>["establishment"], "vicinity"=>"Crn of Camp and Shotover Street, Queenstown"}},
    {:lat=>-45.030741, :lng=>168.660017, :name=>"The Bungy Shop", :reference=>"CnRmAAAAq0mcE2lqx4qzzW2l-XPN85gYDLmRa8bidcnx1PH8otrvJaCX3trga3dNbJytltJO2HsvYcTM9jfhhDU2JHVS6v_8JiJcZ220_RRiUj7BU2HiF8vY8Nbva5yY-7AKyKJUuezvFak5DYs9Twtowiy7PBIQO-F3m7lPYBu8qn-CP57p5RoUU5UmAByhWLjrSHd2vwtxvOda89k", :vicinity=>"The Station, Corner of Camp & Shotover Streets, Queenstown", :full_data=>{"geometry"=>{"location"=>{"lat"=>-45.030741, "lng"=>168.660017}}, "icon"=>"http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png", "id"=>"7ea7bedf7a62279e32677ea6543b9a3a4c1173c0", "name"=>"The Bungy Shop", "reference"=>"CnRmAAAAq0mcE2lqx4qzzW2l-XPN85gYDLmRa8bidcnx1PH8otrvJaCX3trga3dNbJytltJO2HsvYcTM9jfhhDU2JHVS6v_8JiJcZ220_RRiUj7BU2HiF8vY8Nbva5yY-7AKyKJUuezvFak5DYs9Twtowiy7PBIQO-F3m7lPYBu8qn-CP57p5RoUU5UmAByhWLjrSHd2vwtxvOda89k", "types"=>["establishment"], "vicinity"=>"The Station, Corner of Camp & Shotover Streets, Queenstown"}}
    #many other results...
   ]

Raw results from Google

Gmaps4rails.places_for_address('Queenstown, New Zealand', '<your_api_key>', 'Bungy', 7500, 'en', true)

Exceptions

It could raise four kinds of exception:

  1. GeocodeStatus Basically, Google can't find the address provided: raise Gmaps4rails::GeocodeStatus, "The adress you passed seems invalid, status was: #{parse["status"]}. Request was: #{request}"

  2. GeocodeNetStatus No Http Success for Geocoder call. raise Gmaps4rails::GeocodeNetStatus, "The request sent to google was invalid (not http success): #{request}. Response was: #{resp}"

  3. PlacesStatus Basically, Google couldn't find any Places results for given parameters. raise Gmaps4rails::PlacesStatus, "The address you passed seems invalid, status was: #{parse["status"]}.

  4. PlacesNetStatus No Http Success for Places call. raise Gmaps4rails::PlacesNetStatus, "The request sent to google was invalid (not http success): #{request}.

Google places (for lat/lng) function

Processed Results

Gmaps4rails.places(lat, lng, key, keyword = nil, radius = 7500, lang="en", raw = false, protocol = 'https') retrieves an Array of Hash of Google Places records.

This is the more direct version of Google Places Search. It allows you to search for Places around a given combination of latitude and longitude.

Returns the same data as the places_for_address method does, passing a nil value for keyword also gives you all Places around the lat/lng.

Exceptions

It could raise three kinds of exception:

  1. PlacesInvalidQuery Passed lat or lng were nil. raise Gmaps4rails::PlacesInvalidQuery, "You must provide at least a lat/lon for a Google places query"

  2. PlacesStatus Basically, Google couldn't find any Places results for given parameters. raise Gmaps4rails::PlacesStatus, "The address you passed seems invalid, status was: #{parse["status"]}.

  3. PlacesNetStatus No Http Success for Places call. raise Gmaps4rails::PlacesNetStatus, "The request sent to google was invalid (not http success): #{request}.

Geocode function

Processed Results

Gmaps4rails.geocode(address) retrieves an Array of Hash of potential coordinates.

Each hash is made up: latitude, longitude, matched_adress and bounds retrieved by Google.

Here is an example:

Gmaps4rails.geocode("Caroline")
=> [
    {:lat=>-9.9599095, :lng=>-150.2052861, :matched_address=>"Millennium Island, French Polynesia", :bounds=>{"northeast"=>{"lng"=>-150.1958942, "lat"=>-9.9033296}, "southwest"=>{"lng"=>-150.2351189, "lat"=>-10.0108617}}},
    {:lat=>44.72083, :lng=>-88.89139, :matched_address=>"Caroline, WI 54928, USA", :bounds=>nil}, 
    {:lat=>42.37833, :lng=>-76.29583, :matched_address=>"Caroline, NY 14817, USA", :bounds=>nil} 
    #many other results...
   ]

Raw results from Google

Gmaps4rails.geocode(address, true)

Exceptions

It could raise two kinds of exception:

  1. GeocodeStatus Basically, Google can't find the address provided: raise Gmaps4rails::GeocodeStatus, "The adress you passed seems invalid, status was: #{parse["status"]}. Request was: #{request}"

  2. GeocodeNetStatus No Http Success.

    raise Gmaps4rails::GeocodeNetStatus, "The request sent to google was invalid (not http success): #{request}. Response was: #{resp}"

to_gmaps4rails

There are 3 implementations of this method:

Model instance & Array

It creates the json to use to display your marker(s).

It now accepts a block as a parameter so that you can add whatever you want in the json (if you desire to add custom behaviors and information, all data will be gathered then).

Here is an example:

User.all.to_gmaps4rails do |user|
  "\"Data1\": \"#{user.data1}\", \"data2\": \"{user.data2}\""
end

Hash

After a Hash, it creates the javascript for a view. So use it within <script>.

The Hash format should look like the one you see in https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Display-Everything%21.

Destination function

Details here: http://code.google.com/apis/maps/documentation/directions/#RequestParameters

Gmaps4rails.destination(start_end, options={}, output="pretty")
  • start_end is a Hash: { "from" => "", "to" => "" }

  • options can contain the following data:

    • mode: "DRIVING", "WALKING" or "BICYCLING", default is "DRIVING"

    • waypoints: Array of strings containing your waypoints ["here", "there"], default is empty

    • avoid: Array which could contain at most ["tolls", "highways"], default is empty

    • units: String "METRIC" or "IMPERIAL", default is "METRIC"

    • region: String

    • language: String, default is "en"

  • output determines the way you want the result:

    • pretty: renders the result from Google with the polylines separated in a ready for use variable

    • clean: renders the result from Google without the encoded polylines

    • raw: renders the raw result from Google

Destination results

Result is an Array of legs (according to Google: "Each element in the legs array specifies a single leg of the journey from the origin to the destination in the calculated route.").

One leg contains several steps: "A step is the most atomic unit of a direction's route, containing a single step describing a specific, single instruction on the journey."

 [
  #leg1
  {
   "duration"  => { "text" => string, "value" => float },
   "distance"  => { "text" => string, "value" => float },
   "steps"     => Array of Hashes,
   "polylines" => json_containing_encoded_polylines        #depending on the value of 'output' you set
  },
  #leg2
  {
   "duration"  => { "text" => string, "value" => float },
   "distance"  => { "text" => string, "value" => float },
   "steps"     => Array of Hashes,
   "polylines" => json_containing_encoded_polylines
  }
  ...
 ]

Example:

Gmaps4rails.destination(
  {"from" => "Toulon, france", "to" => "marseille, france"}, 
  {
    "language"  => "fr", 
    "waypoints" => ["Cassis,france"],
    "mode"      => "DRIVING",
    "avoid"     => ["tolls", "highways"],
    "language"  => "fr"
  }, 
  "pretty"
  )

Errors

It could raise two kinds of exception:

  1. DirectionStatus Basically, Google can't find any path from the data you provided: raise Gmaps4rails::GeocodeStatus, "The query you passed seems invalid, status was: #{parse["status"]}. Request was: #{request}"

  2. DirectionNetStatus No Http Success.

    raise Gmaps4rails::DirectionNetStatus, "The request sent to google was invalid (not http success): #{request}. Response was: #{resp}"

Something went wrong with that request. Please try again.