glebm-geokit 1.5.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,21 @@
1
+ History.txt
2
+ Manifest.txt
3
+ README.markdown
4
+ Rakefile
5
+ geokit.gemspec
6
+ lib/geokit.rb
7
+ lib/geokit/geocoders.rb
8
+ lib/geokit/mappable.rb
9
+ test/test_base_geocoder.rb
10
+ test/test_bounds.rb
11
+ test/test_ca_geocoder.rb
12
+ test/test_geoloc.rb
13
+ test/test_geoplugin_geocoder.rb
14
+ test/test_google_geocoder.rb
15
+ test/test_google_reverse_geocoder.rb
16
+ test/test_inflector.rb
17
+ test/test_ipgeocoder.rb
18
+ test/test_latlng.rb
19
+ test/test_multi_geocoder.rb
20
+ test/test_us_geocoder.rb
21
+ test/test_yahoo_geocoder.rb
@@ -0,0 +1,273 @@
1
+ ## GEOKIT GEM DESCRIPTION
2
+
3
+ The Geokit gem provides:
4
+
5
+ * Distance calculations between two points on the earth. Calculate the distance in miles, kilometers, or nautical miles, with all the trigonometry abstracted away by GeoKit.
6
+ * Geocoding from multiple providers. It supports Google, Yahoo, Geocoder.us, and Geocoder.ca geocoders, and others. It provides a uniform response structure from all of them.
7
+ It also provides a fail-over mechanism, in case your input fails to geocode in one service.
8
+ * Rectangular bounds calculations: is a point within a given rectangular bounds?
9
+ * Heading and midpoint calculations
10
+
11
+ Combine this gem with the [geokit-rails plugin](http://github.com/andre/geokit-rails/tree/master) to get location-based finders for your Rails app.
12
+
13
+ * Geokit Documentation at Rubyforge [http://geokit.rubyforge.org](http://geokit.rubyforge.org).
14
+ * Repository at Github: [http://github.com/andre/geokit-gem/tree/master](http://github.com/andre/geokit-gem/tree/master).
15
+ * Follow the Google Group for updates and discussion on Geokit: [http://groups.google.com/group/geokit](http://groups.google.com/group/geokit)
16
+
17
+ ## INSTALL
18
+
19
+ sudo gem install glebm-geokit
20
+
21
+ ## QUICK START
22
+
23
+ irb> require 'rubygems'
24
+ irb> require 'geokit'
25
+ irb> a=Geokit::Geocoders::YahooGeocoder.geocode '140 Market St, San Francisco, CA'
26
+ irb> a.ll
27
+ => 37.79363,-122.396116
28
+ irb> b=Geokit::Geocoders::YahooGeocoder.geocode '789 Geary St, San Francisco, CA'
29
+ irb> b.ll
30
+ => 37.786217,-122.41619
31
+ irb> a.distance_to(b)
32
+ => 1.21120007413626
33
+ irb> a.heading_to(b)
34
+ => 244.959832435678
35
+ irb(main):006:0> c=a.midpoint_to(b) # what's halfway from a to b?
36
+ irb> c.ll
37
+ => "37.7899239257175,-122.406153503469"
38
+ irb(main):008:0> d=c.endpoint(90,10) # what's 10 miles to the east of c?
39
+ irb> d.ll
40
+ => "37.7897825005142,-122.223214776155"
41
+
42
+ FYI, that `.ll` method means "latitude longitude".
43
+
44
+ See the RDOC more more ... there are also operations on rectangular bounds (e.g., determining if a point is within bounds, find the center, etc).
45
+
46
+ ## CONFIGURATION
47
+
48
+ If you're using this gem by itself, here are the configuration options:
49
+
50
+ # These defaults are used in Geokit::Mappable.distance_to and in acts_as_mappable
51
+ Geokit::default_units = :miles
52
+ Geokit::default_formula = :sphere
53
+
54
+ # This is the timeout value in seconds to be used for calls to the geocoder web
55
+ # services. For no timeout at all, comment out the setting. The timeout unit
56
+ # is in seconds.
57
+ Geokit::Geocoders::request_timeout = 3
58
+
59
+ # These settings are used if web service calls must be routed through a proxy.
60
+ # These setting can be nil if not needed, otherwise, addr and port must be
61
+ # filled in at a minimum. If the proxy requires authentication, the username
62
+ # and password can be provided as well.
63
+ Geokit::Geocoders::proxy_addr = nil
64
+ Geokit::Geocoders::proxy_port = nil
65
+ Geokit::Geocoders::proxy_user = nil
66
+ Geokit::Geocoders::proxy_pass = nil
67
+
68
+ # This is your yahoo application key for the Yahoo Geocoder.
69
+ # See http://developer.yahoo.com/faq/index.html#appid
70
+ # and http://developer.yahoo.com/maps/rest/V1/geocode.html
71
+ Geokit::Geocoders::yahoo = 'REPLACE_WITH_YOUR_YAHOO_KEY'
72
+
73
+ # This is your Google Maps geocoder key.
74
+ # See http://www.google.com/apis/maps/signup.html
75
+ # and http://www.google.com/apis/maps/documentation/#Geocoding_Examples
76
+ Geokit::Geocoders::google = 'REPLACE_WITH_YOUR_GOOGLE_KEY'
77
+
78
+ # You can also set multiple API KEYS for different domains that may be directed to this same application.
79
+ # The domain from which the current user is being directed will automatically be updated for Geokit via
80
+ # the GeocoderControl class, which gets it's begin filter mixed into the ActionController.
81
+ # You define these keys with a Hash as follows:
82
+ #Geokit::Geocoders::google = { 'rubyonrails.org' => 'RUBY_ON_RAILS_API_KEY', 'ruby-docs.org' => 'RUBY_DOCS_API_KEY' }
83
+
84
+ # This is your username and password for geocoder.us.
85
+ # To use the free service, the value can be set to nil or false. For
86
+ # usage tied to an account, the value should be set to username:password.
87
+ # See http://geocoder.us
88
+ # and http://geocoder.us/user/signup
89
+ Geokit::Geocoders::geocoder_us = false
90
+
91
+ # This is your authorization key for geocoder.ca.
92
+ # To use the free service, the value can be set to nil or false. For
93
+ # usage tied to an account, set the value to the key obtained from
94
+ # Geocoder.ca.
95
+ # See http://geocoder.ca
96
+ # and http://geocoder.ca/?register=1
97
+ Geokit::Geocoders::geocoder_ca = false
98
+
99
+ # require "external_geocoder.rb"
100
+ # Please see the section "writing your own geocoders" for more information.
101
+ # Geokit::Geocoders::external_key = 'REPLACE_WITH_YOUR_API_KEY'
102
+
103
+ # This is the order in which the geocoders are called in a failover scenario
104
+ # If you only want to use a single geocoder, put a single symbol in the array.
105
+ # Valid symbols are :google, :yahoo, :us, and :ca.
106
+ # Be aware that there are Terms of Use restrictions on how you can use the
107
+ # various geocoders. Make sure you read up on relevant Terms of Use for each
108
+ # geocoder you are going to use.
109
+ Geokit::Geocoders::provider_order = [:google,:us]
110
+
111
+ # The IP provider order. Valid symbols are :ip,:geo_plugin.
112
+ # As before, make sure you read up on relevant Terms of Use for each.
113
+ # Geokit::Geocoders::ip_provider_order = [:external,:geo_plugin,:ip]
114
+
115
+ If you're using this gem with the [geokit-rails plugin](http://github.com/andre/geokit-rails/tree/master), the plugin
116
+ creates a template with these settings and places it in `config/initializers/geokit_config.rb`.
117
+
118
+ ## SUPPORTED GEOCODERS
119
+
120
+ ### "regular" address geocoders
121
+ * Yahoo Geocoder - requires an API key.
122
+ * Geocoder.us - may require authentication if performing more than the free request limit.
123
+ * Geocoder.ca - for Canada; may require authentication as well.
124
+ * Geonames - a free geocoder
125
+
126
+ ### address geocoders that also provide reverse geocoding
127
+ * Google Geocoder - requires an API key. Also supports multiple results and bounding box/country code biasing.
128
+
129
+ ### IP address geocoders
130
+ * IP Geocoder - geocodes an IP address using hostip.info's web service.
131
+ * Geoplugin.net -- another IP address geocoder
132
+
133
+ ### Google Geocoder Tricks
134
+
135
+ The Google Geocoder sports a number of useful tricks that elevate it a little bit above the rest of the currently supported geocoders. For starters, it returns a `suggested_bounds` property for all your geocoded results, so you can more easily decide where and how to center a map on the places you geocode. Here's a quick example:
136
+
137
+ irb> res = Geokit::Geocoders::GoogleGeocoder.geocode('140 Market St, San Francisco, CA')
138
+ irb> pp res.suggested_bounds
139
+ #<Geokit::Bounds:0x53b36c
140
+ @ne=#<Geokit::LatLng:0x53b204 @lat=37.7968528, @lng=-122.3926933>,
141
+ @sw=#<Geokit::LatLng:0x53b2b8 @lat=37.7905576, @lng=-122.3989885>>
142
+
143
+ In addition, you can use viewport or country code biasing to make sure the geocoders prefers results within a specific area. Say we wanted to geocode the city of Syracuse in Italy. A normal geocoding query would look like this:
144
+
145
+ irb> res = Geokit::Geocoder::GoogleGeocoder.geocode('Syracuse')
146
+ irb> res.full_address
147
+ => "Syracuse, NY, USA"
148
+
149
+ Not exactly what we were looking for. We know that Syracuse is in Italy, so we can tell the Google Geocoder to prefer results from Italy first, and then wander the Syracuses of the world. To do that, we have to pass Italy's ccTLD (country code top-level domain) to the `:bias` option of the `geocode` method. You can find a comprehensive list of all ccTLDs here: http://en.wikipedia.org/wiki/CcTLD.
150
+
151
+ irb> res = Geokit::Geocoder::GoogleGeocoder.geocode('Syracuse', :bias => 'it')
152
+ irb> res.full_address
153
+ => "Syracuse, Italy"
154
+
155
+ Alternatively, we can speficy the geocoding bias as a bounding box object. Say we wanted to geocode the Winnetka district in Los Angeles.
156
+
157
+ irb> res = Geokit::Geocoder::GoogleGeocoder.geocode('Winnetka')
158
+ irb> res.full_address
159
+ => "Winnetka, IL, USA"
160
+
161
+ Not it. What we can do is tell the geocoder to return results only from in and around LA.
162
+
163
+ irb> la_bounds = Geokit::Geocoder::GoogleGeocoder.geocode('Los Angeles').suggested_bounds
164
+ irb> res = Geokit::Geocoder::GoogleGeocoder.geocode('Winnetka', :bias => la_bounds)
165
+ irb> res.full_address
166
+ => "Winnetka, California, USA"
167
+
168
+
169
+ ### The Multigeocoder
170
+ Multi Geocoder - provides failover for the physical location geocoders, and also IP address geocoders. Its configured by setting Geokit::Geocoders::provider_order, and Geokit::Geocoders::ip_provider_order. You should call the Multi-Geocoder with its :geocode method, supplying one address parameter which is either a real street address, or an ip address. For example:
171
+
172
+ Geokit::Geocoders::MultiGeocoder.geocode("900 Sycamore Drive")
173
+
174
+ Geokit::Geocoders::MultiGeocoder.geocode("12.12.12.12")
175
+
176
+ ## MULTIPLE RESULTS
177
+ Some geocoding services will return multple results if the there isn't one clear result.
178
+ Geoloc can capture multiple results through its "all" method. Currently only the Google geocoder
179
+ supports multiple results:
180
+
181
+ irb> geo=Geokit::Geocoders::GoogleGeocoder.geocode("900 Sycamore Drive")
182
+ irb> geo.full_address
183
+ => "900 Sycamore Dr, Arkadelphia, AR 71923, USA"
184
+ irb> geo.all.size
185
+ irb> geo.all.each { |e| puts e.full_address }
186
+ 900 Sycamore Dr, Arkadelphia, AR 71923, USA
187
+ 900 Sycamore Dr, Burkburnett, TX 76354, USA
188
+ 900 Sycamore Dr, TN 38361, USA
189
+ ....
190
+
191
+ geo.all is just an array of additional Geolocs, so do what you want with it. If you call .all on a
192
+ geoloc that doesn't have any additional results, you will get an array of one.
193
+
194
+
195
+ ## NOTES ON WHAT'S WHERE
196
+
197
+ mappable.rb contains the Mappable module, which provides basic
198
+ distance calculation methods, i.e., calculating the distance
199
+ between two points.
200
+
201
+ mappable.rb also contains LatLng, GeoLoc, and Bounds.
202
+ LatLng is a simple container for latitude and longitude, but
203
+ it's made more powerful by mixing in the above-mentioned Mappable
204
+ module -- therefore, you can calculate easily the distance between two
205
+ LatLng ojbects with `distance = first.distance_to(other)`
206
+
207
+ GeoLoc (also in mappable.rb) represents an address or location which
208
+ has been geocoded. You can get the city, zipcode, street address, etc.
209
+ from a GeoLoc object. GeoLoc extends LatLng, so you also get lat/lng
210
+ AND the Mappable modeule goodness for free.
211
+
212
+ geocoders.rb contains all the geocoder implemenations. All the gercoders
213
+ inherit from a common base (class Geocoder) and implement the private method
214
+ do_geocode.
215
+
216
+ ## WRITING YOUR OWN GEOCODERS
217
+
218
+ If you would like to write your own geocoders, you can do so by requiring 'geokit' or 'geokit/geocoders.rb' in a new file and subclassing the base class (which is class "Geocoder").
219
+ You must then also require such extenal file back in your main geokit configuration.
220
+
221
+ require "geokit"
222
+
223
+ module Geokit
224
+ module Geocoders
225
+
226
+ # Should be overriden as Geokit::Geocoders::external_key in your configuration file
227
+ @@external_key = 'REPLACE_WITH_YOUR_API_KEY'
228
+ __define_accessors
229
+
230
+ # Replace name 'External' (below) with the name of your custom geocoder class
231
+ # and use :external to specify this geocoder in your list of geocoders.
232
+ class ExternalGeocoder < Geocoder
233
+ private
234
+ def self.do_geocode(address, options = {})
235
+ # Main geocoding method
236
+ end
237
+
238
+ def self.parse_http_resp(body) # :nodoc:
239
+ # Helper method to parse http response. See geokit/geocoders.rb.
240
+ end
241
+ end
242
+
243
+ end
244
+ end
245
+
246
+ ## GOOGLE GROUP
247
+
248
+ Follow the Google Group for updates and discussion on Geokit: http://groups.google.com/group/geokit
249
+
250
+ ## LICENSE
251
+
252
+ (The MIT License)
253
+
254
+ Copyright (c) 2007-2009 Andre Lewis and Bill Eisenhauer
255
+
256
+ Permission is hereby granted, free of charge, to any person obtaining
257
+ a copy of this software and associated documentation files (the
258
+ 'Software'), to deal in the Software without restriction, including
259
+ without limitation the rights to use, copy, modify, merge, publish,
260
+ distribute, sublicense, and/or sell copies of the Software, and to
261
+ permit persons to whom the Software is furnished to do so, subject to
262
+ the following conditions:
263
+
264
+ The above copyright notice and this permission notice shall be
265
+ included in all copies or substantial portions of the Software.
266
+
267
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
268
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
269
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
270
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
271
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
272
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
273
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,22 @@
1
+ # -*- ruby -*-
2
+
3
+ require 'rubygems'
4
+ require 'hoe'
5
+ require './lib/geokit.rb'
6
+
7
+ # undefined method `empty?' for nil:NilClass
8
+ # /Library/Ruby/Site/1.8/rubygems/specification.rb:886:in `validate'
9
+ class NilClass
10
+ def empty?
11
+ true
12
+ end
13
+ end
14
+
15
+ project=Hoe.new('geokit', Geokit::VERSION) do |p|
16
+ #p.rubyforge_name = 'geokit' # if different than lowercase project name
17
+ p.developer('Andre Lewis', 'andre@earthcode.com')
18
+ p.summary="Geokit provides geocoding and distance calculation in an easy-to-use API"
19
+ end
20
+
21
+
22
+ # vim: syntax=Ruby
@@ -0,0 +1,31 @@
1
+ module Geokit
2
+ VERSION = '1.5.2'
3
+ # These defaults are used in Geokit::Mappable.distance_to and in acts_as_mappable
4
+ @@default_units = :miles
5
+ @@default_formula = :sphere
6
+
7
+ [:default_units, :default_formula].each do |sym|
8
+ class_eval <<-EOS, __FILE__, __LINE__
9
+ def self.#{sym}
10
+ if defined?(#{sym.to_s.upcase})
11
+ #{sym.to_s.upcase}
12
+ else
13
+ @@#{sym}
14
+ end
15
+ end
16
+
17
+ def self.#{sym}=(obj)
18
+ @@#{sym} = obj
19
+ end
20
+ EOS
21
+ end
22
+ end
23
+
24
+ path = File.expand_path(File.dirname(__FILE__))
25
+ $:.unshift path unless $:.include?(path)
26
+ require 'geokit/geocoders'
27
+ require 'geokit/mappable'
28
+
29
+ # make old-style module name "GeoKit" equivalent to new-style "Geokit"
30
+ GeoKit=Geokit
31
+
@@ -0,0 +1,727 @@
1
+ require 'net/http'
2
+ require 'ipaddr'
3
+ require 'rexml/document'
4
+ require 'yaml'
5
+ require 'timeout'
6
+ require 'logger'
7
+ require 'iconv'
8
+ require 'uri'
9
+
10
+ module Geokit
11
+
12
+ class GeokitError < StandardError; end
13
+
14
+ class BadKeyError < GeokitError; end
15
+
16
+ class GeocoderServiceError < GeokitError; end
17
+
18
+ class TimeoutError < GeocoderServiceError; end
19
+ class InvalidResponseError < GeocoderServiceError; end
20
+
21
+ class InvalidStatusCodeError < GeocoderServiceError; end
22
+ class TooManyQueriesError < GeocoderServiceError; end
23
+
24
+ module Inflector
25
+
26
+ extend self
27
+
28
+ def titleize(word)
29
+ humanize(underscore(word)).gsub(/\b([a-z])/u) { $1.capitalize }
30
+ end
31
+
32
+ def underscore(camel_cased_word)
33
+ camel_cased_word.to_s.gsub(/::/, '/').
34
+ gsub(/([A-Z]+)([A-Z][a-z])/u,'\1_\2').
35
+ gsub(/([a-z\d])([A-Z])/u,'\1_\2').
36
+ tr("-", "_").
37
+ downcase
38
+ end
39
+
40
+ def humanize(lower_case_and_underscored_word)
41
+ lower_case_and_underscored_word.to_s.gsub(/_id$/, "").gsub(/_/, " ").capitalize
42
+ end
43
+
44
+ def snake_case(s)
45
+ return s.downcase if s =~ /^[A-Z]+$/u
46
+ s.gsub(/([A-Z]+)(?=[A-Z][a-z]?)|\B[A-Z]/u, '_\&') =~ /_*(.*)/
47
+ return $+.downcase
48
+
49
+ end
50
+
51
+ def url_escape(s)
52
+ URI::escape(s)
53
+ end
54
+
55
+ def camelize(str)
56
+ str.split('_').map {|w| w.capitalize}.join
57
+ end
58
+ end
59
+
60
+ # Contains a range of geocoders:
61
+ #
62
+ # ### "regular" address geocoders
63
+ # * Yahoo Geocoder - requires an API key.
64
+ # * Geocoder.us - may require authentication if performing more than the free request limit.
65
+ # * Geocoder.ca - for Canada; may require authentication as well.
66
+ # * Geonames - a free geocoder
67
+ #
68
+ # ### address geocoders that also provide reverse geocoding
69
+ # * Google Geocoder - requires an API key.
70
+ #
71
+ # ### IP address geocoders
72
+ # * IP Geocoder - geocodes an IP address using hostip.info's web service.
73
+ # * Geoplugin.net -- another IP address geocoder
74
+ #
75
+ # ### The Multigeocoder
76
+ # * Multi Geocoder - provides failover for the physical location geocoders.
77
+ #
78
+ # Some of these geocoders require configuration. You don't have to provide it here. See the README.
79
+ module Geocoders
80
+ @@proxy_addr = nil
81
+ @@proxy_port = nil
82
+ @@proxy_user = nil
83
+ @@proxy_pass = nil
84
+ @@request_timeout = nil
85
+ @@yahoo = 'REPLACE_WITH_YOUR_YAHOO_KEY'
86
+ @@google = 'REPLACE_WITH_YOUR_GOOGLE_KEY'
87
+ @@geocoder_us = false
88
+ @@geocoder_ca = false
89
+ @@geonames = false
90
+ @@provider_order = [:google,:us]
91
+ @@ip_provider_order = [:geo_plugin,:ip]
92
+ @@logger=Logger.new(STDOUT)
93
+ @@logger.level=Logger::INFO
94
+ @@domain = nil
95
+
96
+ def self.__define_accessors
97
+ class_variables.each do |v|
98
+ sym = v.to_s.delete("@").to_sym
99
+ unless self.respond_to? sym
100
+ module_eval <<-EOS, __FILE__, __LINE__
101
+ def self.#{sym}
102
+ value = if defined?(#{sym.to_s.upcase})
103
+ #{sym.to_s.upcase}
104
+ else
105
+ @@#{sym}
106
+ end
107
+ if value.is_a?(Hash)
108
+ value = (self.domain.nil? ? nil : value[self.domain]) || value.values.first
109
+ end
110
+ value
111
+ end
112
+
113
+ def self.#{sym}=(obj)
114
+ @@#{sym} = obj
115
+ end
116
+ EOS
117
+ end
118
+ end
119
+ end
120
+
121
+ __define_accessors
122
+
123
+ # Error which is thrown in the event a geocoding error occurs.
124
+ class GeocodeError < StandardError; end
125
+
126
+ # -------------------------------------------------------------------------------------------
127
+ # Geocoder Base class -- every geocoder should inherit from this
128
+ # -------------------------------------------------------------------------------------------
129
+
130
+ # The Geocoder base class which defines the interface to be used by all
131
+ # other geocoders.
132
+ class Geocoder
133
+ # Main method which calls the do_geocode template method which subclasses
134
+ # are responsible for implementing. Returns a populated GeoLoc or a
135
+ # nil one with a failed success code.
136
+ def self.geocode(address, options = {})
137
+ do_geocode(Iconv.iconv('UTF-8//IGNORE', 'UTF-8', address).to_s, options)
138
+ end
139
+ # Main method which calls the do_reverse_geocode template method which subclasses
140
+ # are responsible for implementing. Returns a populated GeoLoc or
141
+ # nil one with a failed success code.
142
+ def self.reverse_geocode(latlng, options = {})
143
+ do_reverse_geocode(latlng, options)
144
+ end
145
+
146
+ # Call the geocoder service using the timeout if configured.
147
+ def self.call_geocoder_service(url)
148
+ logger.debug "Geocoding:: #{url}"
149
+ Timeout::timeout(Geokit::Geocoders::request_timeout) { return self.do_get(url) } if Geokit::Geocoders::request_timeout
150
+ return self.do_get(url)
151
+ rescue TimeoutError, Timeout::Error
152
+ raise Geokit::TimeoutError
153
+ end
154
+
155
+ # Not all geocoders can do reverse geocoding. So, unless the subclass explicitly overrides this method,
156
+ # a call to reverse_geocode will return an empty GeoLoc. If you happen to be using MultiGeocoder,
157
+ # this will cause it to failover to the next geocoder, which will hopefully be one which supports reverse geocoding.
158
+ def self.do_reverse_geocode(latlng, options = {})
159
+ return nil
160
+ end
161
+
162
+ protected
163
+
164
+ def self.logger()
165
+ Geokit::Geocoders::logger
166
+ end
167
+
168
+ private
169
+
170
+ # Wraps the geocoder call around a proxy if necessary.
171
+ def self.do_get(url)
172
+ uri = URI.parse(url)
173
+ req = Net::HTTP::Get.new(url)
174
+ req.basic_auth(uri.user, uri.password) if uri.userinfo
175
+ res = Net::HTTP::Proxy(GeoKit::Geocoders::proxy_addr,
176
+ GeoKit::Geocoders::proxy_port,
177
+ GeoKit::Geocoders::proxy_user,
178
+ GeoKit::Geocoders::proxy_pass).start(uri.host, uri.port) { |http| http.get(uri.path + "?" + uri.query) }
179
+ return res
180
+ end
181
+
182
+ # Adds subclass' geocode method making it conveniently available through
183
+ # the base class.
184
+ def self.inherited(clazz)
185
+ class_name = clazz.name.split('::').last
186
+ src = <<-END_SRC
187
+ def self.#{Geokit::Inflector.underscore(class_name)}(address, options = {})
188
+ #{class_name}.geocode(address, options)
189
+ end
190
+ END_SRC
191
+ class_eval(src)
192
+ end
193
+ end
194
+
195
+ # -------------------------------------------------------------------------------------------
196
+ # "Regular" Address geocoders
197
+ # -------------------------------------------------------------------------------------------
198
+
199
+ # Geocoder CA geocoder implementation. Requires the Geokit::Geocoders::GEOCODER_CA variable to
200
+ # contain true or false based upon whether authentication is to occur. Conforms to the
201
+ # interface set by the Geocoder class.
202
+ #
203
+ # Returns a response like:
204
+ # <?xml version="1.0" encoding="UTF-8" ?>
205
+ # <geodata>
206
+ # <latt>49.243086</latt>
207
+ # <longt>-123.153684</longt>
208
+ # </geodata>
209
+ class CaGeocoder < Geocoder
210
+
211
+ private
212
+
213
+ # Template method which does the geocode lookup.
214
+ def self.do_geocode(address, options = {})
215
+ raise ArgumentError('Geocoder.ca requires a GeoLoc argument') unless address.is_a?(GeoLoc)
216
+ url = construct_request(address)
217
+ res = self.call_geocoder_service(url)
218
+ return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
219
+ xml = res.body
220
+ logger.debug "Geocoder.ca geocoding. Address: #{address}. Result: #{xml}"
221
+ # Parse the document.
222
+ doc = REXML::Document.new(xml)
223
+ address.lat = doc.elements['//latt'].text
224
+ address.lng = doc.elements['//longt'].text
225
+ address.success = true
226
+ return address
227
+ rescue
228
+ logger.error "Caught an error during Geocoder.ca geocoding call: "+$!
229
+ return GeoLoc.new
230
+ end
231
+
232
+ # Formats the request in the format acceptable by the CA geocoder.
233
+ def self.construct_request(location)
234
+ url = ""
235
+ url += add_ampersand(url) + "stno=#{location.street_number}" if location.street_address
236
+ url += add_ampersand(url) + "addresst=#{Geokit::Inflector::url_escape(location.street_name)}" if location.street_address
237
+ url += add_ampersand(url) + "city=#{Geokit::Inflector::url_escape(location.city)}" if location.city
238
+ url += add_ampersand(url) + "prov=#{location.state}" if location.state
239
+ url += add_ampersand(url) + "postal=#{location.zip}" if location.zip
240
+ url += add_ampersand(url) + "auth=#{Geokit::Geocoders::geocoder_ca}" if Geokit::Geocoders::geocoder_ca
241
+ url += add_ampersand(url) + "geoit=xml"
242
+ 'http://geocoder.ca/?' + url
243
+ end
244
+
245
+ def self.add_ampersand(url)
246
+ url && url.length > 0 ? "&" : ""
247
+ end
248
+ end
249
+
250
+ # Geocoder Us geocoder implementation. Requires the Geokit::Geocoders::GEOCODER_US variable to
251
+ # contain true or false based upon whether authentication is to occur. Conforms to the
252
+ # interface set by the Geocoder class.
253
+ class UsGeocoder < Geocoder
254
+
255
+ private
256
+ def self.do_geocode(address, options = {})
257
+ address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
258
+
259
+ query = (address_str =~ /^\d{5}(?:-\d{4})?$/ ? "zip" : "address") + "=#{Geokit::Inflector::url_escape(address_str)}"
260
+ url = if GeoKit::Geocoders::geocoder_us
261
+ "http://#{GeoKit::Geocoders::geocoder_us}@geocoder.us/member/service/csv/geocode"
262
+ else
263
+ "http://geocoder.us/service/csv/geocode"
264
+ end
265
+
266
+ url = "#{url}?#{query}"
267
+ res = self.call_geocoder_service(url)
268
+
269
+ return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
270
+ data = res.body
271
+ logger.debug "Geocoder.us geocoding. Address: #{address}. Result: #{data}"
272
+ array = data.chomp.split(',')
273
+
274
+ if array.length == 5
275
+ res=GeoLoc.new
276
+ res.lat,res.lng,res.city,res.state,res.zip=array
277
+ res.country_code='US'
278
+ res.success=true
279
+ return res
280
+ elsif array.length == 6
281
+ res=GeoLoc.new
282
+ res.lat,res.lng,res.street_address,res.city,res.state,res.zip=array
283
+ res.country_code='US'
284
+ res.success=true
285
+ return res
286
+ else
287
+ logger.info "geocoder.us was unable to geocode address: "+address
288
+ return GeoLoc.new
289
+ end
290
+ rescue
291
+ logger.error "Caught an error during geocoder.us geocoding call: "+$!
292
+ return GeoLoc.new
293
+
294
+ end
295
+ end
296
+
297
+ # Yahoo geocoder implementation. Requires the Geokit::Geocoders::YAHOO variable to
298
+ # contain a Yahoo API key. Conforms to the interface set by the Geocoder class.
299
+ class YahooGeocoder < Geocoder
300
+
301
+ private
302
+
303
+ # Template method which does the geocode lookup.
304
+ def self.do_geocode(address, options = {})
305
+ address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
306
+ url="http://api.local.yahoo.com/MapsService/V1/geocode?appid=#{Geokit::Geocoders::yahoo}&location=#{Geokit::Inflector::url_escape(address_str)}"
307
+ res = self.call_geocoder_service(url)
308
+ return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
309
+ xml = res.body
310
+ doc = REXML::Document.new(xml)
311
+ logger.debug "Yahoo geocoding. Address: #{address}. Result: #{xml}"
312
+
313
+ if doc.elements['//ResultSet']
314
+ res=GeoLoc.new
315
+
316
+ #basic
317
+ res.lat=doc.elements['//Latitude'].text
318
+ res.lng=doc.elements['//Longitude'].text
319
+ res.country_code=doc.elements['//Country'].text
320
+ res.provider='yahoo'
321
+
322
+ #extended - false if not available
323
+ res.city=doc.elements['//City'].text if doc.elements['//City'] && doc.elements['//City'].text != nil
324
+ res.state=doc.elements['//State'].text if doc.elements['//State'] && doc.elements['//State'].text != nil
325
+ res.zip=doc.elements['//Zip'].text if doc.elements['//Zip'] && doc.elements['//Zip'].text != nil
326
+ res.street_address=doc.elements['//Address'].text if doc.elements['//Address'] && doc.elements['//Address'].text != nil
327
+ res.precision=doc.elements['//Result'].attributes['precision'] if doc.elements['//Result']
328
+ # set the accuracy as google does (added by Andruby)
329
+ res.accuracy=%w{unknown country state state city zip zip+4 street address building}.index(res.precision)
330
+ res.success=true
331
+ return res
332
+ else
333
+ logger.info "Yahoo was unable to geocode address: "+address
334
+ return GeoLoc.new
335
+ end
336
+
337
+ rescue
338
+ logger.info "Caught an error during Yahoo geocoding call: "+$!
339
+ return GeoLoc.new
340
+ end
341
+ end
342
+
343
+ # Another geocoding web service
344
+ # http://www.geonames.org
345
+ class GeonamesGeocoder < Geocoder
346
+
347
+ private
348
+
349
+ # Template method which does the geocode lookup.
350
+ def self.do_geocode(address, options = {})
351
+ address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
352
+ # geonames need a space seperated search string
353
+ address_str.gsub!(/,/, " ")
354
+ params = "/postalCodeSearch?placename=#{Geokit::Inflector::url_escape(address_str)}&maxRows=10"
355
+
356
+ if(GeoKit::Geocoders::geonames)
357
+ url = "http://ws.geonames.net#{params}&username=#{GeoKit::Geocoders::geonames}"
358
+ else
359
+ url = "http://ws.geonames.org#{params}"
360
+ end
361
+
362
+ res = self.call_geocoder_service(url)
363
+
364
+ return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
365
+
366
+ xml=res.body
367
+ logger.debug "Geonames geocoding. Address: #{address}. Result: #{xml}"
368
+ doc=REXML::Document.new(xml)
369
+
370
+ if(doc.elements['//geonames/totalResultsCount'].text.to_i > 0)
371
+ res=GeoLoc.new
372
+
373
+ # only take the first result
374
+ res.lat=doc.elements['//code/lat'].text if doc.elements['//code/lat']
375
+ res.lng=doc.elements['//code/lng'].text if doc.elements['//code/lng']
376
+ res.country_code=doc.elements['//code/countryCode'].text if doc.elements['//code/countryCode']
377
+ res.provider='genomes'
378
+ res.city=doc.elements['//code/name'].text if doc.elements['//code/name']
379
+ res.state=doc.elements['//code/adminName1'].text if doc.elements['//code/adminName1']
380
+ res.zip=doc.elements['//code/postalcode'].text if doc.elements['//code/postalcode']
381
+ res.success=true
382
+ return res
383
+ else
384
+ logger.info "Geonames was unable to geocode address: "+address
385
+ return GeoLoc.new
386
+ end
387
+
388
+ rescue
389
+ logger.error "Caught an error during Geonames geocoding call: "+$!
390
+ end
391
+ end
392
+
393
+ # -------------------------------------------------------------------------------------------
394
+ # Address geocoders that also provide reverse geocoding
395
+ # -------------------------------------------------------------------------------------------
396
+
397
+ # Google geocoder implementation. Requires the Geokit::Geocoders::GOOGLE variable to
398
+ # contain a Google API key. Conforms to the interface set by the Geocoder class.
399
+ class GoogleGeocoder < Geocoder
400
+
401
+ private
402
+
403
+ # Template method which does the reverse-geocode lookup.
404
+ def self.do_reverse_geocode(latlng, options = {})
405
+ lang_str = options[:lang].blank? ? '' : "&hl=#{options[:lang]}"
406
+ latlng=LatLng.normalize(latlng)
407
+ res = self.call_geocoder_service("http://maps.google.com/maps/geo?q=#{Geokit::Inflector::url_escape(latlng.ll)}&output=xml#{lang_str}&key=#{Geokit::Geocoders::google}&oe=utf-8")
408
+ # res = Net::HTTP.get_response(URI.parse("http://maps.google.com/maps/geo?ll=#{Geokit::Inflector::url_escape(address_str)}&output=xml&key=#{Geokit::Geocoders::google}&oe=utf-8"))
409
+ unless (res.is_a?(Net::HTTPSuccess) || res.is_a?(Net::HTTPOK))
410
+ raise Geokit::InvalidResponseError
411
+ end
412
+ xml = res.body
413
+ xml = xml.force_encoding(Encoding::UTF_8) if xml.respond_to?(:force_encoding)
414
+ logger.debug "Google reverse-geocoding. LL: #{latlng}. Result: #{xml}"
415
+ return self.xml2GeoLoc(xml)
416
+ end
417
+
418
+ # Template method which does the geocode lookup.
419
+ #
420
+ # Supports viewport/country code biasing
421
+ #
422
+ # ==== OPTIONS
423
+ # * :bias - This option makes the Google Geocoder return results biased to a particular
424
+ # country or viewport. Country code biasing is achieved by passing the ccTLD
425
+ # ('uk' for .co.uk, for example) as a :bias value. For a list of ccTLD's,
426
+ # look here: http://en.wikipedia.org/wiki/CcTLD. By default, the geocoder
427
+ # will be biased to results within the US (ccTLD .com).
428
+ #
429
+ # If you'd like the Google Geocoder to prefer results within a given viewport,
430
+ # you can pass a Geokit::Bounds object as the :bias value.
431
+ #
432
+ # ==== EXAMPLES
433
+ # # By default, the geocoder will return Syracuse, NY
434
+ # Geokit::Geocoders::GoogleGeocoder.geocode('Syracuse').country_code # => 'US'
435
+ # # With country code biasing, it returns Syracuse in Sicily, Italy
436
+ # Geokit::Geocoders::GoogleGeocoder.geocode('Syracuse', :bias => :it).country_code # => 'IT'
437
+ #
438
+ # # By default, the geocoder will return Winnetka, IL
439
+ # Geokit::Geocoders::GoogleGeocoder.geocode('Winnetka').state # => 'IL'
440
+ # # When biased to an bounding box around California, it will now return the Winnetka neighbourhood, CA
441
+ # bounds = Geokit::Bounds.normalize([34.074081, -118.694401], [34.321129, -118.399487])
442
+ # Geokit::Geocoders::GoogleGeocoder.geocode('Winnetka', :bias => bounds).state # => 'CA'
443
+
444
+ GOOGLE_STATUS_CODES = {
445
+ 200 => "G_GEO_SUCCESS",
446
+ # InvalidStatusCodeError
447
+ 400 => "G_GEO_BAD_REQUEST",
448
+ 500 => "G_GEO_SERVER_ERROR",
449
+ 601 => "G_GEO_MISSING_QUERY",
450
+ # UnableToGeocodeError
451
+ 602 => "G_GEO_UNKNOWN_ADDRESS",
452
+ 603 => "G_GEO_UNAVAILABLE_ADDRESS",
453
+ 604 => "G_GEO_UNKNOWN_DIRECTIONS",
454
+ # BadKey
455
+ 610 => "G_GEO_BAD_KEY",
456
+ # TooManyQueriesError
457
+ 620 => "G_GEO_TOO_MANY_QUERIES",
458
+ }
459
+
460
+ def self.do_geocode(address, options = {})
461
+ bias_str = options[:bias] ? construct_bias_string_from_options(options[:bias]) : ''
462
+ lang_str = options[:lang].blank? ? '' : "&hl=#{options[:lang]}"
463
+ address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
464
+ res = self.call_geocoder_service("http://maps.google.com/maps/geo?q=#{Geokit::Inflector::url_escape(address_str)}&output=xml#{bias_str}#{lang_str}&key=#{Geokit::Geocoders::google}&oe=utf-8")
465
+ unless res.is_a?(Net::HTTPSuccess)
466
+ raise Geokit::InvalidResponseError
467
+ end
468
+ xml = res.body
469
+ xml = xml.force_encoding(Encoding::UTF_8) if xml.respond_to?(:force_encoding)
470
+ address = address.force_encoding(Encoding::UTF_8) if address.respond_to?(:force_encoding)
471
+ logger.debug "Google geocoding. Address: #{address}. Result: #{xml}"
472
+ return self.xml2GeoLoc(xml, address)
473
+ end
474
+
475
+ def self.construct_bias_string_from_options(bias)
476
+ if bias.is_a?(String) or bias.is_a?(Symbol)
477
+ # country code biasing
478
+ "&gl=#{bias.to_s.downcase}"
479
+ elsif bias.is_a?(Bounds)
480
+ # viewport biasing
481
+ "&ll=#{bias.center.ll}&spn=#{bias.to_span.ll}"
482
+ end
483
+ end
484
+
485
+ def self.xml2GeoLoc(xml, address="")
486
+ doc=REXML::Document.new(xml)
487
+
488
+ response_code = doc.elements['//kml/Response/Status/code'].text.to_i rescue nil
489
+ if response_code == 200 # G_GEO_SUCCESS
490
+ geoloc = nil
491
+ # Google can return multiple results as //Placemark elements.
492
+ # iterate through each and extract each placemark as a geoloc
493
+ doc.each_element('//Placemark') do |e|
494
+ extracted_geoloc = extract_placemark(e) # g is now an instance of GeoLoc
495
+ if geoloc.nil?
496
+ # first time through, geoloc is still nil, so we make it the geoloc we just extracted
497
+ geoloc = extracted_geoloc
498
+ else
499
+ # second (and subsequent) iterations, we push additional
500
+ # geolocs onto "geoloc.all"
501
+ geoloc.all.push(extracted_geoloc)
502
+ end
503
+ end
504
+ return geoloc
505
+ else
506
+ logger.info "Google was unable to geocode address: #{address}. Response code: #{response_code} #{GOOGLE_STATUS_CODES[response_code]}"
507
+
508
+ if [602, 603, 604].include?(response_code)
509
+ # G_GEO_UNKNOWN_ADDRESS, G_GEO_UNAVAILABLE_ADDRESS, G_GEO_UNKNOWN_DIRECTIONS
510
+ return nil
511
+ elsif [400, 500, 601].include?(response_code)
512
+ # G_GEO_BAD_REQUEST, G_GEO_SERVER_ERROR, G_GEO_MISSING_QUERY, G_GEO_BAD_KEY
513
+ raise Geokit::InvalidStatusCodeError.new(GOOGLE_STATUS_CODES[response_code])
514
+ elsif response_code == 620
515
+ # G_GEO_TOO_MANY_QUERIES
516
+ raise Geokit::TooManyQueriesError.new(GOOGLE_STATUS_CODES[response_code])
517
+ elsif response_code == 610
518
+ # G_GEO_BAD_KEY
519
+ raise Geokit::BadKeyError.new(GOOGLE_STATUS_CODES[response_code])
520
+ else
521
+ raise Geokit::GeokitError
522
+ end
523
+ end
524
+ end
525
+
526
+ # extracts a single geoloc from a //placemark element in the google results xml
527
+ def self.extract_placemark(doc)
528
+ res = GeoLoc.new
529
+ coordinates=doc.elements['.//coordinates'].text.to_s.split(',')
530
+
531
+ #basics
532
+ res.lat=coordinates[1]
533
+ res.lng=coordinates[0]
534
+ res.country_code=doc.elements['.//CountryNameCode'].text if doc.elements['.//CountryNameCode']
535
+ res.provider='google'
536
+
537
+ #extended -- false if not not available
538
+ res.city = doc.elements['.//LocalityName'].text if doc.elements['.//LocalityName']
539
+ res.state = doc.elements['.//AdministrativeAreaName'].text if doc.elements['.//AdministrativeAreaName']
540
+ res.province = doc.elements['.//SubAdministrativeAreaName'].text if doc.elements['.//SubAdministrativeAreaName']
541
+ res.full_address = doc.elements['.//address'].text if doc.elements['.//address'] # google provides it
542
+ res.zip = doc.elements['.//PostalCodeNumber'].text if doc.elements['.//PostalCodeNumber']
543
+ res.street_address = doc.elements['.//ThoroughfareName'].text if doc.elements['.//ThoroughfareName']
544
+ res.country = doc.elements['.//CountryName'].text if doc.elements['.//CountryName']
545
+ res.district = doc.elements['.//DependentLocalityName'].text if doc.elements['.//DependentLocalityName']
546
+ # Translate accuracy into Yahoo-style token address, street, zip, zip+4, city, state, country
547
+ # For Google, 1=low accuracy, 8=high accuracy
548
+ address_details=doc.elements['.//*[local-name() = "AddressDetails"]']
549
+ res.accuracy = address_details ? address_details.attributes['Accuracy'].to_i : 0
550
+ res.precision=%w{unknown country state state city zip zip+4 street address building}[res.accuracy]
551
+
552
+ # google returns a set of suggested boundaries for the geocoded result
553
+ if suggested_bounds = doc.elements['//LatLonBox']
554
+ res.suggested_bounds = Bounds.normalize(
555
+ [suggested_bounds.attributes['south'], suggested_bounds.attributes['west']],
556
+ [suggested_bounds.attributes['north'], suggested_bounds.attributes['east']])
557
+ end
558
+
559
+ res.success=true
560
+
561
+ return res
562
+ end
563
+ end
564
+
565
+
566
+ # -------------------------------------------------------------------------------------------
567
+ # IP Geocoders
568
+ # -------------------------------------------------------------------------------------------
569
+
570
+ # Provides geocoding based upon an IP address. The underlying web service is geoplugin.net
571
+ class GeoPluginGeocoder < Geocoder
572
+ private
573
+
574
+ def self.do_geocode(ip, options = {})
575
+ return GeoLoc.new unless /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})?$/.match(ip)
576
+ response = self.call_geocoder_service("http://www.geoplugin.net/xml.gp?ip=#{ip}")
577
+ return response.is_a?(Net::HTTPSuccess) ? parse_xml(response.body) : GeoLoc.new
578
+ rescue
579
+ logger.error "Caught an error during GeoPluginGeocoder geocoding call: "+$!
580
+ return GeoLoc.new
581
+ end
582
+
583
+ def self.parse_xml(xml)
584
+ xml = REXML::Document.new(xml)
585
+ geo = GeoLoc.new
586
+ geo.provider='geoPlugin'
587
+ geo.city = xml.elements['//geoplugin_city'].text
588
+ geo.state = xml.elements['//geoplugin_region'].text
589
+ geo.country_code = xml.elements['//geoplugin_countryCode'].text
590
+ geo.lat = xml.elements['//geoplugin_latitude'].text.to_f
591
+ geo.lng = xml.elements['//geoplugin_longitude'].text.to_f
592
+ geo.success = !!geo.city && !geo.city.empty?
593
+ return geo
594
+ end
595
+ end
596
+
597
+ # Provides geocoding based upon an IP address. The underlying web service is a hostip.info
598
+ # which sources their data through a combination of publicly available information as well
599
+ # as community contributions.
600
+ class IpGeocoder < Geocoder
601
+
602
+ # A number of non-routable IP ranges.
603
+ #
604
+ # --
605
+ # Sources for these:
606
+ # RFC 3330: Special-Use IPv4 Addresses
607
+ # The bogon list: http://www.cymru.com/Documents/bogon-list.html
608
+
609
+ NON_ROUTABLE_IP_RANGES = [
610
+ IPAddr.new('0.0.0.0/8'), # "This" Network
611
+ IPAddr.new('10.0.0.0/8'), # Private-Use Networks
612
+ IPAddr.new('14.0.0.0/8'), # Public-Data Networks
613
+ IPAddr.new('127.0.0.0/8'), # Loopback
614
+ IPAddr.new('169.254.0.0/16'), # Link local
615
+ IPAddr.new('172.16.0.0/12'), # Private-Use Networks
616
+ IPAddr.new('192.0.2.0/24'), # Test-Net
617
+ IPAddr.new('192.168.0.0/16'), # Private-Use Networks
618
+ IPAddr.new('198.18.0.0/15'), # Network Interconnect Device Benchmark Testing
619
+ IPAddr.new('224.0.0.0/4'), # Multicast
620
+ IPAddr.new('240.0.0.0/4') # Reserved for future use
621
+ ].freeze
622
+
623
+ private
624
+
625
+ # Given an IP address, returns a GeoLoc instance which contains latitude,
626
+ # longitude, city, and country code. Sets the success attribute to false if the ip
627
+ # parameter does not match an ip address.
628
+ def self.do_geocode(ip, options = {})
629
+ return GeoLoc.new unless /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})?$/.match(ip)
630
+ return GeoLoc.new if self.private_ip_address?(ip)
631
+ url = "http://api.hostip.info/get_html.php?ip=#{ip}&position=true"
632
+ response = self.call_geocoder_service(url)
633
+ response.is_a?(Net::HTTPSuccess) ? parse_body(response.body) : GeoLoc.new
634
+ rescue
635
+ logger.error "Caught an error during HostIp geocoding call: "+$!
636
+ return GeoLoc.new
637
+ end
638
+
639
+ # Converts the body to YAML since its in the form of:
640
+ #
641
+ # Country: UNITED STATES (US)
642
+ # City: Sugar Grove, IL
643
+ # Latitude: 41.7696
644
+ # Longitude: -88.4588
645
+ #
646
+ # then instantiates a GeoLoc instance to populate with location data.
647
+ def self.parse_body(body) # :nodoc:
648
+ yaml = YAML.load(body)
649
+ res = GeoLoc.new
650
+ res.provider = 'hostip'
651
+ res.city, res.state = yaml['City'].split(', ')
652
+ country, res.country_code = yaml['Country'].split(' (')
653
+ res.lat = yaml['Latitude']
654
+ res.lng = yaml['Longitude']
655
+ res.country_code.chop!
656
+ res.success = !(res.city =~ /\(.+\)/)
657
+ res
658
+ end
659
+
660
+ # Checks whether the IP address belongs to a private address range.
661
+ #
662
+ # This function is used to reduce the number of useless queries made to
663
+ # the geocoding service. Such queries can occur frequently during
664
+ # integration tests.
665
+ def self.private_ip_address?(ip)
666
+ return NON_ROUTABLE_IP_RANGES.any? { |range| range.include?(ip) }
667
+ end
668
+ end
669
+
670
+ # -------------------------------------------------------------------------------------------
671
+ # The Multi Geocoder
672
+ # -------------------------------------------------------------------------------------------
673
+
674
+ # Provides methods to geocode with a variety of geocoding service providers, plus failover
675
+ # among providers in the order you configure. When 2nd parameter is set 'true', perform
676
+ # ip location lookup with 'address' as the ip address.
677
+ #
678
+ # Goal:
679
+ # - homogenize the results of multiple geocoders
680
+ #
681
+ # Limitations:
682
+ # - currently only provides the first result. Sometimes geocoders will return multiple results.
683
+ # - currently discards the "accuracy" component of the geocoding calls
684
+ class MultiGeocoder < Geocoder
685
+
686
+ private
687
+ # This method will call one or more geocoders in the order specified in the
688
+ # configuration until one of the geocoders work.
689
+ #
690
+ # The failover approach is crucial for production-grade apps, but is rarely used.
691
+ # 98% of your geocoding calls will be successful with the first call
692
+ def self.do_geocode(address, options = {})
693
+ geocode_ip = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.match(address)
694
+ provider_order = geocode_ip ? Geokit::Geocoders::ip_provider_order : Geokit::Geocoders::provider_order
695
+
696
+ provider_order.each do |provider|
697
+ begin
698
+ klass = Geokit::Geocoders.const_get "#{Geokit::Inflector::camelize(provider.to_s)}Geocoder"
699
+ res = klass.send :geocode, address, options
700
+ return res if res.success?
701
+ rescue
702
+ logger.error("Something has gone very wrong during geocoding, OR you have configured an invalid class name in Geokit::Geocoders::provider_order. Address: #{address}. Provider: #{provider}")
703
+ end
704
+ end
705
+ # If we get here, we failed completely.
706
+ GeoLoc.new
707
+ end
708
+
709
+ # This method will call one or more geocoders in the order specified in the
710
+ # configuration until one of the geocoders work, only this time it's going
711
+ # to try to reverse geocode a geographical point.
712
+ def self.do_reverse_geocode(latlng, options = {})
713
+ Geokit::Geocoders::provider_order.each do |provider|
714
+ begin
715
+ klass = Geokit::Geocoders.const_get "#{Geokit::Inflector::camelize(provider.to_s)}Geocoder"
716
+ res = klass.send :reverse_geocode, latlng, options
717
+ return res if res.success?
718
+ rescue
719
+ logger.error("Something has gone very wrong during reverse geocoding, OR you have configured an invalid class name in Geokit::Geocoders::provider_order. LatLng: #{latlng}. Provider: #{provider}")
720
+ end
721
+ end
722
+ # If we get here, we failed completely.
723
+ GeoLoc.new
724
+ end
725
+ end
726
+ end
727
+ end