Skip to content

Instantly share code, notes, and snippets.

@rossnelson
Created October 5, 2011 21:45
Show Gist options
  • Save rossnelson/1265834 to your computer and use it in GitHub Desktop.
Save rossnelson/1265834 to your computer and use it in GitHub Desktop.
Google Places
# "https://maps.googleapis.com/maps/api/place/search/json?key=AIzaSyDKpxPRiMFWSaF99KRLnGf6EiJPTGzuIvk&location=-33.966136,151.102687&name=harbour&radius=500&sensor=false&types=food"
search = Google::PlacesSearch.new({
:lat => "-33.966136",
:lng => "151.102687",
:radius => "500",
:types => "food",
:name => "harbour",
:sensor => "false",
:key => "AIzaSyDKpxPRiMFWSaF99KRLnGf6EiJPTGzuIvk",
:user_ip => "184.60.81.8"
})
module Google
class Place
attr_accessor :geometry, :icon, :google_id, :name, :reference, :types, :vicinity, :place_h
def initialize(place={})
@place_h = place
@geometry = place['geometry']
@icon = place['icon']
@google_id = place['id']
@name = place['name']
@types = place['types']
@vicinity = place['vicinity']
end
end
end
module Google
class PlacesSearch
require "net/https"
require "uri"
require "json"
require "cgi"
require "addressable/uri"
attr_reader :query
##
# Initialize a new Google Places search with the specified query
#
# search = Google::PlacesSearch.new({
# :lat => -33.966136,
# :lng => 151.102687,
# :radius => 500,
# :types => "food",
# :name => "harbour",
# :sensor => "false",
# :key => "AIzaSyDKpxPRiMFWSaF99KRLnGf6EiJPTGzuIvk",
# :user_ip => "184.60.81.8"
# })
#
def initialize(query={})
@query = query
end
##
# Return new array of Google::PlacesSearch objects with json hash as attributes
#
def places
@places ||= parse_json
end
##
# Retrive json utilizing Google Places API
#
def document
uri = URI.parse(query_string(@query))
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
response.body
end
##
# Bulid url from Google::PlacesSearch instance @query attribute
#
def query_string(query)
values = {
:location => "#{query[:lat]},#{query[:lng]}",
:radius => query[:radius],
:types => query[:types],
:name => query[:name],
:sensor => query[:sensor],
:key => "AIzaSyDKpxPRiMFWSaF99KRLnGf6EiJPTGzuIvk",
:userIp => query[:user_ip]
}
uri = Addressable::URI.new
uri.query_values = values
"https://maps.googleapis.com/maps/api/place/search/json?" + CGI::unescape(uri.query)
end
##
# Parse returned json and initialize an array of Google::Place objects
#
def parse_json
attributes = JSON.parse(document)
places = []
attributes['results'].each do |place|
places << Google::Place.new(place)
end
places
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment