Skip to content
Snippets Groups Projects
Commit 4b4a686d authored by Alex Reisner's avatar Alex Reisner
Browse files

Add Geocoder::Result and Geocoder.search.

parent 9e60bd92
No related branches found
No related tags found
No related merge requests found
......@@ -178,8 +178,6 @@ If anyone has a more elegant solution to this problem I am very interested in se
* also need to make sure 'mysql2' is supported
* make 'near' scope work with AR associations
* http://stackoverflow.com/questions/3266358/geocoder-rails-plugin-near-search-problem-with-activerecord
* unobtrusively add ability to get a result with more data (Geocoder object?)
* the default usage should remain dead simple
Copyright (c) 2009-11 Alex Reisner, released under the MIT license
require "geocoder/calculations"
require "geocoder/lookup"
require "geocoder/result"
require "geocoder/active_record"
module Geocoder
extend self
##
# Takes a search string (eg: "Mississippi Coast Coliseumf, Biloxi, MS") for
# geocoding, or coordinates (latitude, longitude) for reverse geocoding.
# Returns a Geocoder::Result object.
#
def search(*args)
if args.size == 2
Lookup.search(args[0], args[1], true)
else
Lookup.search(args[0], false)
end
end
end
##
# Add geocoded_by method to ActiveRecord::Base so Geocoder is accessible.
#
......
......@@ -29,10 +29,14 @@ module Geocoder
##
# Query Google for geographic information about the given phrase.
# Returns a Result object containing all data returned by Google.
# Returns an array of Geocoder::Result objects.
#
def search(query, reverse = false)
# TODO
[].tap do |results|
if doc = parsed_response(query, reverse)
doc['results'].each{ |r| results << Result.new(r) }
end
end
end
......
module Geocoder
class Result
attr_accessor :data
##
# Takes a hash of result data from a parsed Google result document.
#
def initialize(data)
@data = data
end
def types
@data['types']
end
def formatted_address
@data['formatted_address']
end
def address_components
@data['address_components']
end
##
# Get address components of a given type. Valid types are defined in
# Google's Geocoding API documentation and include (among others):
#
# :street_number
# :locality
# :neighborhood
# :route
# :postal_code
#
def address_components_of_type(type)
address_components.select{ |c| c['types'].include?(type.to_s) }
end
def geometry
@data['geometry']
end
end
end
......@@ -27,4 +27,10 @@ class GeocoderTest < Test::Unit::TestCase
l.fetch_coordinates
end
end
def test_result_address_components_of_type
results = Geocoder::Lookup.search("Madison Square Garden, New York, NY")
assert_equal "Manhattan",
results.first.address_components_of_type(:sublocality).first['long_name']
end
end
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment