keeguon-geokit 1.6.6

Sign up to get free protection for your applications and to get access to all the features.
data/README.markdown ADDED
@@ -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 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::Geocoders::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::Geocoders::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::Geocoders::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::Geocoders::GoogleGeocoder.geocode('Los Angeles').suggested_bounds
164
+ irb> res = Geokit::Geocoders::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.
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require 'rake/testtask'
3
+
4
+ task :default => :test
5
+
6
+ Rake::TestTask.new do |t|
7
+ t.libs << "test"
8
+ t.test_files = FileList['test/test*.rb']
9
+ t.verbose = true
10
+ end
data/lib/geokit.rb ADDED
@@ -0,0 +1,29 @@
1
+ module Geokit
2
+ # These defaults are used in Geokit::Mappable.distance_to and in acts_as_mappable
3
+ @@default_units = :miles
4
+ @@default_formula = :sphere
5
+
6
+ [:default_units, :default_formula].each do |sym|
7
+ class_eval <<-EOS, __FILE__, __LINE__
8
+ def self.#{sym}
9
+ if defined?(#{sym.to_s.upcase})
10
+ #{sym.to_s.upcase}
11
+ else
12
+ @@#{sym}
13
+ end
14
+ end
15
+
16
+ def self.#{sym}=(obj)
17
+ @@#{sym} = obj
18
+ end
19
+ EOS
20
+ end
21
+ end
22
+
23
+ path = File.expand_path(File.dirname(__FILE__))
24
+ $:.unshift path unless $:.include?(path)
25
+ require 'geokit/geocoders'
26
+ require 'geokit/mappable'
27
+
28
+ # make old-style module name "GeoKit" equivalent to new-style "Geokit"
29
+ GeoKit=Geokit
@@ -0,0 +1,930 @@
1
+ require 'net/http'
2
+ require 'ipaddr'
3
+ require 'rexml/document'
4
+ require 'yaml'
5
+ require 'timeout'
6
+ require 'logger'
7
+
8
+ require 'multi_json'
9
+
10
+ module Geokit
11
+
12
+ class TooManyQueriesError < StandardError; end
13
+
14
+ module Inflector
15
+
16
+ extend self
17
+
18
+ def titleize(word)
19
+ humanize(underscore(word)).gsub(/\b([a-z])/u) { $1.capitalize }
20
+ end
21
+
22
+ def underscore(camel_cased_word)
23
+ camel_cased_word.to_s.gsub(/::/, '/').
24
+ gsub(/([A-Z]+)([A-Z][a-z])/u,'\1_\2').
25
+ gsub(/([a-z\d])([A-Z])/u,'\1_\2').
26
+ tr("-", "_").
27
+ downcase
28
+ end
29
+
30
+ def humanize(lower_case_and_underscored_word)
31
+ lower_case_and_underscored_word.to_s.gsub(/_id$/, "").gsub(/_/, " ").capitalize
32
+ end
33
+
34
+ def snake_case(s)
35
+ return s.downcase if s =~ /^[A-Z]+$/u
36
+ s.gsub(/([A-Z]+)(?=[A-Z][a-z]?)|\B[A-Z]/u, '_\&') =~ /_*(.*)/
37
+ return $+.downcase
38
+
39
+ end
40
+
41
+ def url_escape(s)
42
+ s.gsub(/([^ a-zA-Z0-9_.-]+)/nu) do
43
+ '%' + $1.unpack('H2' * $1.size).join('%').upcase
44
+ end.tr(' ', '+')
45
+ end
46
+
47
+ def camelize(str)
48
+ str.split('_').map {|w| w.capitalize}.join
49
+ end
50
+ end
51
+
52
+ # Contains a range of geocoders:
53
+ #
54
+ # ### "regular" address geocoders
55
+ # * Yahoo Geocoder - requires an API key.
56
+ # * Geocoder.us - may require authentication if performing more than the free request limit.
57
+ # * Geocoder.ca - for Canada; may require authentication as well.
58
+ # * Geonames - a free geocoder
59
+ #
60
+ # ### address geocoders that also provide reverse geocoding
61
+ # * Google Geocoder - requires an API key.
62
+ #
63
+ # ### IP address geocoders
64
+ # * IP Geocoder - geocodes an IP address using hostip.info's web service.
65
+ # * Geoplugin.net -- another IP address geocoder
66
+ #
67
+ # ### The Multigeocoder
68
+ # * Multi Geocoder - provides failover for the physical location geocoders.
69
+ #
70
+ # Some of these geocoders require configuration. You don't have to provide it here. See the README.
71
+ module Geocoders
72
+ @@proxy_addr = nil
73
+ @@proxy_port = nil
74
+ @@proxy_user = nil
75
+ @@proxy_pass = nil
76
+ @@request_timeout = nil
77
+ @@yahoo = 'REPLACE_WITH_YOUR_YAHOO_KEY'
78
+ @@google = 'REPLACE_WITH_YOUR_GOOGLE_KEY'
79
+ @@geocoder_us = false
80
+ @@geocoder_ca = false
81
+ @@geonames = false
82
+ @@provider_order = [:google,:us]
83
+ @@ip_provider_order = [:geo_plugin,:ip]
84
+ @@logger=Logger.new(STDOUT)
85
+ @@logger.level=Logger::INFO
86
+ @@domain = nil
87
+
88
+ def self.__define_accessors
89
+ class_variables.each do |v|
90
+ sym = v.to_s.delete("@").to_sym
91
+ unless self.respond_to? sym
92
+ module_eval <<-EOS, __FILE__, __LINE__
93
+ def self.#{sym}
94
+ value = if defined?(#{sym.to_s.upcase})
95
+ #{sym.to_s.upcase}
96
+ else
97
+ @@#{sym}
98
+ end
99
+ if value.is_a?(Hash)
100
+ value = (self.domain.nil? ? nil : value[self.domain]) || value.values.first
101
+ end
102
+ value
103
+ end
104
+
105
+ def self.#{sym}=(obj)
106
+ @@#{sym} = obj
107
+ end
108
+ EOS
109
+ end
110
+ end
111
+ end
112
+
113
+ __define_accessors
114
+
115
+ # Error which is thrown in the event a geocoding error occurs.
116
+ class GeocodeError < StandardError; end
117
+
118
+ # -------------------------------------------------------------------------------------------
119
+ # Geocoder Base class -- every geocoder should inherit from this
120
+ # -------------------------------------------------------------------------------------------
121
+
122
+ # The Geocoder base class which defines the interface to be used by all
123
+ # other geocoders.
124
+ class Geocoder
125
+ # Main method which calls the do_geocode template method which subclasses
126
+ # are responsible for implementing. Returns a populated GeoLoc or an
127
+ # empty one with a failed success code.
128
+ def self.geocode(address, options = {})
129
+ res = do_geocode(address, options)
130
+ return res.nil? ? GeoLoc.new : res
131
+ end
132
+ # Main method which calls the do_reverse_geocode template method which subclasses
133
+ # are responsible for implementing. Returns a populated GeoLoc or an
134
+ # empty one with a failed success code.
135
+ def self.reverse_geocode(latlng)
136
+ res = do_reverse_geocode(latlng)
137
+ return res.success? ? res : GeoLoc.new
138
+ end
139
+
140
+ # Call the geocoder service using the timeout if configured.
141
+ def self.call_geocoder_service(url)
142
+ Timeout::timeout(Geokit::Geocoders::request_timeout) { return self.do_get(url) } if Geokit::Geocoders::request_timeout
143
+ return self.do_get(url)
144
+ rescue TimeoutError
145
+ return nil
146
+ end
147
+
148
+ # Not all geocoders can do reverse geocoding. So, unless the subclass explicitly overrides this method,
149
+ # a call to reverse_geocode will return an empty GeoLoc. If you happen to be using MultiGeocoder,
150
+ # this will cause it to failover to the next geocoder, which will hopefully be one which supports reverse geocoding.
151
+ def self.do_reverse_geocode(latlng)
152
+ return GeoLoc.new
153
+ end
154
+
155
+ protected
156
+
157
+ def self.logger()
158
+ Geokit::Geocoders::logger
159
+ end
160
+
161
+ private
162
+
163
+ # Wraps the geocoder call around a proxy if necessary.
164
+ def self.do_get(url)
165
+ uri = URI.parse(url)
166
+ req = Net::HTTP::Get.new(url)
167
+ req.basic_auth(uri.user, uri.password) if uri.userinfo
168
+ res = Net::HTTP::Proxy(GeoKit::Geocoders::proxy_addr,
169
+ GeoKit::Geocoders::proxy_port,
170
+ GeoKit::Geocoders::proxy_user,
171
+ GeoKit::Geocoders::proxy_pass).start(uri.host, uri.port) { |http| http.get(uri.path + "?" + uri.query) }
172
+ return res
173
+ end
174
+
175
+ # Adds subclass' geocode method making it conveniently available through
176
+ # the base class.
177
+ def self.inherited(clazz)
178
+ class_name = clazz.name.split('::').last
179
+ src = <<-END_SRC
180
+ def self.#{Geokit::Inflector.underscore(class_name)}(address, options = {})
181
+ #{class_name}.geocode(address, options)
182
+ end
183
+ END_SRC
184
+ class_eval(src)
185
+ end
186
+ end
187
+
188
+ # -------------------------------------------------------------------------------------------
189
+ # "Regular" Address geocoders
190
+ # -------------------------------------------------------------------------------------------
191
+
192
+ # Geocoder CA geocoder implementation. Requires the Geokit::Geocoders::GEOCODER_CA variable to
193
+ # contain true or false based upon whether authentication is to occur. Conforms to the
194
+ # interface set by the Geocoder class.
195
+ #
196
+ # Returns a response like:
197
+ # <?xml version="1.0" encoding="UTF-8" ?>
198
+ # <geodata>
199
+ # <latt>49.243086</latt>
200
+ # <longt>-123.153684</longt>
201
+ # </geodata>
202
+ class CaGeocoder < Geocoder
203
+
204
+ private
205
+
206
+ # Template method which does the geocode lookup.
207
+ def self.do_geocode(address, options = {})
208
+ raise ArgumentError('Geocoder.ca requires a GeoLoc argument') unless address.is_a?(GeoLoc)
209
+ url = construct_request(address)
210
+ res = self.call_geocoder_service(url)
211
+ return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
212
+ xml = res.body
213
+ logger.debug "Geocoder.ca geocoding. Address: #{address}. Result: #{xml}"
214
+ # Parse the document.
215
+ doc = REXML::Document.new(xml)
216
+ address.lat = doc.elements['//latt'].text
217
+ address.lng = doc.elements['//longt'].text
218
+ address.success = true
219
+ return address
220
+ rescue
221
+ logger.error "Caught an error during Geocoder.ca geocoding call: "+$!
222
+ return GeoLoc.new
223
+ end
224
+
225
+ # Formats the request in the format acceptable by the CA geocoder.
226
+ def self.construct_request(location)
227
+ url = ""
228
+ url += add_ampersand(url) + "stno=#{location.street_number}" if location.street_address
229
+ url += add_ampersand(url) + "addresst=#{Geokit::Inflector::url_escape(location.street_name)}" if location.street_address
230
+ url += add_ampersand(url) + "city=#{Geokit::Inflector::url_escape(location.city)}" if location.city
231
+ url += add_ampersand(url) + "prov=#{location.state}" if location.state
232
+ url += add_ampersand(url) + "postal=#{location.zip}" if location.zip
233
+ url += add_ampersand(url) + "auth=#{Geokit::Geocoders::geocoder_ca}" if Geokit::Geocoders::geocoder_ca
234
+ url += add_ampersand(url) + "geoit=xml"
235
+ 'http://geocoder.ca/?' + url
236
+ end
237
+
238
+ def self.add_ampersand(url)
239
+ url && url.length > 0 ? "&" : ""
240
+ end
241
+ end
242
+
243
+ # Geocoder Us geocoder implementation. Requires the Geokit::Geocoders::GEOCODER_US variable to
244
+ # contain true or false based upon whether authentication is to occur. Conforms to the
245
+ # interface set by the Geocoder class.
246
+ class UsGeocoder < Geocoder
247
+
248
+ private
249
+ def self.do_geocode(address, options = {})
250
+ address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
251
+
252
+ query = (address_str =~ /^\d{5}(?:-\d{4})?$/ ? "zip" : "address") + "=#{Geokit::Inflector::url_escape(address_str)}"
253
+ url = if GeoKit::Geocoders::geocoder_us
254
+ "http://#{GeoKit::Geocoders::geocoder_us}@geocoder.us/member/service/csv/geocode"
255
+ else
256
+ "http://geocoder.us/service/csv/geocode"
257
+ end
258
+
259
+ url = "#{url}?#{query}"
260
+ res = self.call_geocoder_service(url)
261
+
262
+ return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
263
+ data = res.body
264
+ logger.debug "Geocoder.us geocoding. Address: #{address}. Result: #{data}"
265
+ array = data.chomp.split(',')
266
+
267
+ if array.length == 5
268
+ res=GeoLoc.new
269
+ res.lat,res.lng,res.city,res.state,res.zip=array
270
+ res.country_code='US'
271
+ res.success=true
272
+ return res
273
+ elsif array.length == 6
274
+ res=GeoLoc.new
275
+ res.lat,res.lng,res.street_address,res.city,res.state,res.zip=array
276
+ res.country_code='US'
277
+ res.success=true
278
+ return res
279
+ else
280
+ logger.info "geocoder.us was unable to geocode address: "+address
281
+ return GeoLoc.new
282
+ end
283
+ rescue
284
+ logger.error "Caught an error during geocoder.us geocoding call: "+$!
285
+ return GeoLoc.new
286
+
287
+ end
288
+ end
289
+
290
+ # Yahoo geocoder implementation. Requires the Geokit::Geocoders::YAHOO variable to
291
+ # contain a Yahoo API key. Conforms to the interface set by the Geocoder class.
292
+ class YahooGeocoder < Geocoder
293
+
294
+ private
295
+
296
+ # Template method which does the geocode lookup.
297
+ def self.do_geocode(address, options = {})
298
+ address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
299
+ url="http://where.yahooapis.com/geocode?flags=J&appid=#{Geokit::Geocoders::yahoo}&q=#{Geokit::Inflector::url_escape(address_str)}"
300
+ res = self.call_geocoder_service(url)
301
+ return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
302
+ json = res.body
303
+ logger.debug "Yahoo geocoding. Address: #{address}. Result: #{json}"
304
+ return self.json2GeoLoc(json, address)
305
+ end
306
+
307
+ def self.json2GeoLoc(json, address)
308
+ results = MultiJson.decode(json)
309
+
310
+ if results['ResultSet']['Error'] == 0
311
+ geoloc = nil
312
+ results['ResultSet']['Results'].each do |result|
313
+ extracted_geoloc = extract_geoloc(result)
314
+ if geoloc.nil?
315
+ geoloc = extracted_geoloc
316
+ else
317
+ geoloc.all.push(extracted_geoloc)
318
+ end
319
+ end
320
+ return geoloc
321
+ else
322
+ logger.info "Yahoo was unable to geocode address: " + address
323
+ return GeoLoc.new
324
+ end
325
+ end
326
+
327
+ def self.extract_geoloc(result_json)
328
+ geoloc = GeoLoc.new
329
+
330
+ # basic
331
+ geoloc.lat = result_json['latitude']
332
+ geoloc.lng = result_json['longitude']
333
+ geoloc.country_code = result_json['countrycode']
334
+ geoloc.provider = 'yahoo'
335
+
336
+ # extended
337
+ geoloc.street_address = result_json['line1'].to_s.empty? ? nil : result_json['line1']
338
+ geoloc.city = result_json['city']
339
+ geoloc.state = geoloc.is_us? ? result_json['statecode'] : result_json['state']
340
+ geoloc.zip = result_json['postal']
341
+
342
+ geoloc.precision = case result_json['quality']
343
+ when 9,10 then 'country'
344
+ when 19..30 then 'state'
345
+ when 39,40 then 'city'
346
+ when 49,50 then 'neighborhood'
347
+ when 59,60,64 then 'zip'
348
+ when 74,75 then 'zip+4'
349
+ when 70..72 then 'street'
350
+ when 80..87 then 'address'
351
+ when 62,63,90,99 then 'building'
352
+ else 'unknown'
353
+ end
354
+
355
+ geoloc.accuracy = %w{unknown country state state city zip zip+4 street address building}.index(geoloc.precision)
356
+ geoloc.success = true
357
+
358
+ return geoloc
359
+ end
360
+ end
361
+
362
+ # Another geocoding web service
363
+ # http://www.geonames.org
364
+ class GeonamesGeocoder < Geocoder
365
+
366
+ private
367
+
368
+ # Template method which does the geocode lookup.
369
+ def self.do_geocode(address, options = {})
370
+ address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
371
+ # geonames need a space seperated search string
372
+ address_str.gsub!(/,/, " ")
373
+ params = "/postalCodeSearch?placename=#{Geokit::Inflector::url_escape(address_str)}&maxRows=10"
374
+
375
+ if(GeoKit::Geocoders::geonames)
376
+ url = "http://ws.geonames.net#{params}&username=#{GeoKit::Geocoders::geonames}"
377
+ else
378
+ url = "http://ws.geonames.org#{params}"
379
+ end
380
+
381
+ res = self.call_geocoder_service(url)
382
+
383
+ return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
384
+
385
+ xml=res.body
386
+ logger.debug "Geonames geocoding. Address: #{address}. Result: #{xml}"
387
+ doc=REXML::Document.new(xml)
388
+
389
+ if(doc.elements['//geonames/totalResultsCount'].text.to_i > 0)
390
+ res=GeoLoc.new
391
+
392
+ # only take the first result
393
+ res.lat=doc.elements['//code/lat'].text if doc.elements['//code/lat']
394
+ res.lng=doc.elements['//code/lng'].text if doc.elements['//code/lng']
395
+ res.country_code=doc.elements['//code/countryCode'].text if doc.elements['//code/countryCode']
396
+ res.provider='genomes'
397
+ res.city=doc.elements['//code/name'].text if doc.elements['//code/name']
398
+ res.state=doc.elements['//code/adminName1'].text if doc.elements['//code/adminName1']
399
+ res.zip=doc.elements['//code/postalcode'].text if doc.elements['//code/postalcode']
400
+ res.success=true
401
+ return res
402
+ else
403
+ logger.info "Geonames was unable to geocode address: "+address
404
+ return GeoLoc.new
405
+ end
406
+
407
+ rescue
408
+ logger.error "Caught an error during Geonames geocoding call: "+$!
409
+ end
410
+ end
411
+
412
+ # -------------------------------------------------------------------------------------------
413
+ # Address geocoders that also provide reverse geocoding
414
+ # -------------------------------------------------------------------------------------------
415
+
416
+ # Google geocoder implementation. Requires the Geokit::Geocoders::GOOGLE variable to
417
+ # contain a Google API key. Conforms to the interface set by the Geocoder class.
418
+ class GoogleGeocoder < Geocoder
419
+
420
+ private
421
+
422
+ # Template method which does the reverse-geocode lookup.
423
+ def self.do_reverse_geocode(latlng)
424
+ latlng=LatLng.normalize(latlng)
425
+ res = self.call_geocoder_service("http://maps.google.com/maps/geo?ll=#{Geokit::Inflector::url_escape(latlng.ll)}&output=xml&key=#{Geokit::Geocoders::google}&oe=utf-8")
426
+ # 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"))
427
+ return GeoLoc.new unless (res.is_a?(Net::HTTPSuccess) || res.is_a?(Net::HTTPOK))
428
+ xml = res.body
429
+ logger.debug "Google reverse-geocoding. LL: #{latlng}. Result: #{xml}"
430
+ return self.xml2GeoLoc(xml)
431
+ end
432
+
433
+ # Template method which does the geocode lookup.
434
+ #
435
+ # Supports viewport/country code biasing
436
+ #
437
+ # ==== OPTIONS
438
+ # * :bias - This option makes the Google Geocoder return results biased to a particular
439
+ # country or viewport. Country code biasing is achieved by passing the ccTLD
440
+ # ('uk' for .co.uk, for example) as a :bias value. For a list of ccTLD's,
441
+ # look here: http://en.wikipedia.org/wiki/CcTLD. By default, the geocoder
442
+ # will be biased to results within the US (ccTLD .com).
443
+ #
444
+ # If you'd like the Google Geocoder to prefer results within a given viewport,
445
+ # you can pass a Geokit::Bounds object as the :bias value.
446
+ #
447
+ # ==== EXAMPLES
448
+ # # By default, the geocoder will return Syracuse, NY
449
+ # Geokit::Geocoders::GoogleGeocoder.geocode('Syracuse').country_code # => 'US'
450
+ # # With country code biasing, it returns Syracuse in Sicily, Italy
451
+ # Geokit::Geocoders::GoogleGeocoder.geocode('Syracuse', :bias => :it).country_code # => 'IT'
452
+ #
453
+ # # By default, the geocoder will return Winnetka, IL
454
+ # Geokit::Geocoders::GoogleGeocoder.geocode('Winnetka').state # => 'IL'
455
+ # # When biased to an bounding box around California, it will now return the Winnetka neighbourhood, CA
456
+ # bounds = Geokit::Bounds.normalize([34.074081, -118.694401], [34.321129, -118.399487])
457
+ # Geokit::Geocoders::GoogleGeocoder.geocode('Winnetka', :bias => bounds).state # => 'CA'
458
+ def self.do_geocode(address, options = {})
459
+ bias_str = options[:bias] ? construct_bias_string_from_options(options[:bias]) : ''
460
+ address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
461
+ res = self.call_geocoder_service("http://maps.google.com/maps/geo?q=#{Geokit::Inflector::url_escape(address_str)}&output=xml#{bias_str}&key=#{Geokit::Geocoders::google}&oe=utf-8")
462
+ return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
463
+ xml = res.body
464
+ logger.debug "Google geocoding. Address: #{address}. Result: #{xml}"
465
+ return self.xml2GeoLoc(xml, address)
466
+ end
467
+
468
+ def self.construct_bias_string_from_options(bias)
469
+ if bias.is_a?(String) or bias.is_a?(Symbol)
470
+ # country code biasing
471
+ "&gl=#{bias.to_s.downcase}"
472
+ elsif bias.is_a?(Bounds)
473
+ # viewport biasing
474
+ "&ll=#{bias.center.ll}&spn=#{bias.to_span.ll}"
475
+ end
476
+ end
477
+
478
+ def self.xml2GeoLoc(xml, address="")
479
+ doc=REXML::Document.new(xml)
480
+
481
+ if doc.elements['//kml/Response/Status/code'].text == '200'
482
+ geoloc = nil
483
+ # Google can return multiple results as //Placemark elements.
484
+ # iterate through each and extract each placemark as a geoloc
485
+ doc.each_element('//Placemark') do |e|
486
+ extracted_geoloc = extract_placemark(e) # g is now an instance of GeoLoc
487
+ if geoloc.nil?
488
+ # first time through, geoloc is still nil, so we make it the geoloc we just extracted
489
+ geoloc = extracted_geoloc
490
+ else
491
+ # second (and subsequent) iterations, we push additional
492
+ # geolocs onto "geoloc.all"
493
+ geoloc.all.push(extracted_geoloc)
494
+ end
495
+ end
496
+ return geoloc
497
+ elsif doc.elements['//kml/Response/Status/code'].text == '620'
498
+ raise Geokit::TooManyQueriesError
499
+ else
500
+ logger.info "Google was unable to geocode address: "+address
501
+ return GeoLoc.new
502
+ end
503
+
504
+ rescue Geokit::TooManyQueriesError
505
+ # re-raise because of other rescue
506
+ raise Geokit::TooManyQueriesError, "Google returned a 620 status, too many queries. The given key has gone over the requests limit in the 24 hour period or has submitted too many requests in too short a period of time. If you're sending multiple requests in parallel or in a tight loop, use a timer or pause in your code to make sure you don't send the requests too quickly."
507
+ rescue
508
+ logger.error "Caught an error during Google geocoding call: "+$!
509
+ return GeoLoc.new
510
+ end
511
+
512
+ # extracts a single geoloc from a //placemark element in the google results xml
513
+ def self.extract_placemark(doc)
514
+ res = GeoLoc.new
515
+ coordinates=doc.elements['.//coordinates'].text.to_s.split(',')
516
+
517
+ #basics
518
+ res.lat=coordinates[1]
519
+ res.lng=coordinates[0]
520
+ res.country_code=doc.elements['.//CountryNameCode'].text if doc.elements['.//CountryNameCode']
521
+ res.provider='google'
522
+
523
+ #extended -- false if not not available
524
+ res.city = doc.elements['.//LocalityName'].text if doc.elements['.//LocalityName']
525
+ res.state = doc.elements['.//AdministrativeAreaName'].text if doc.elements['.//AdministrativeAreaName']
526
+ res.province = doc.elements['.//SubAdministrativeAreaName'].text if doc.elements['.//SubAdministrativeAreaName']
527
+ res.full_address = doc.elements['.//address'].text if doc.elements['.//address'] # google provides it
528
+ res.zip = doc.elements['.//PostalCodeNumber'].text if doc.elements['.//PostalCodeNumber']
529
+ res.street_address = doc.elements['.//ThoroughfareName'].text if doc.elements['.//ThoroughfareName']
530
+ res.country = doc.elements['.//CountryName'].text if doc.elements['.//CountryName']
531
+ res.district = doc.elements['.//DependentLocalityName'].text if doc.elements['.//DependentLocalityName']
532
+ # Translate accuracy into Yahoo-style token address, street, zip, zip+4, city, state, country
533
+ # For Google, 1=low accuracy, 8=high accuracy
534
+ address_details=doc.elements['.//*[local-name() = "AddressDetails"]']
535
+ res.accuracy = address_details ? address_details.attributes['Accuracy'].to_i : 0
536
+ res.precision=%w{unknown country state state city zip zip+4 street address building}[res.accuracy]
537
+
538
+ # google returns a set of suggested boundaries for the geocoded result
539
+ if suggested_bounds = doc.elements['//LatLonBox']
540
+ res.suggested_bounds = Bounds.normalize(
541
+ [suggested_bounds.attributes['south'], suggested_bounds.attributes['west']],
542
+ [suggested_bounds.attributes['north'], suggested_bounds.attributes['east']])
543
+ end
544
+
545
+ res.success=true
546
+
547
+ return res
548
+ end
549
+ end
550
+
551
+ class GoogleGeocoder3 < Geocoder
552
+
553
+ private
554
+ # Template method which does the reverse-geocode lookup.
555
+ def self.do_reverse_geocode(latlng)
556
+ latlng=LatLng.normalize(latlng)
557
+ res = self.call_geocoder_service("http://maps.google.com/maps/api/geocode/json?sensor=false&latlng=#{Geokit::Inflector::url_escape(latlng.ll)}")
558
+ return GeoLoc.new unless (res.is_a?(Net::HTTPSuccess) || res.is_a?(Net::HTTPOK))
559
+ json = res.body
560
+ logger.debug "Google reverse-geocoding. LL: #{latlng}. Result: #{json}"
561
+ return self.json2GeoLoc(json)
562
+ end
563
+
564
+ # Template method which does the geocode lookup.
565
+ #
566
+ # Supports viewport/country code biasing
567
+ #
568
+ # ==== OPTIONS
569
+ # * :bias - This option makes the Google Geocoder return results biased to a particular
570
+ # country or viewport. Country code biasing is achieved by passing the ccTLD
571
+ # ('uk' for .co.uk, for example) as a :bias value. For a list of ccTLD's,
572
+ # look here: http://en.wikipedia.org/wiki/CcTLD. By default, the geocoder
573
+ # will be biased to results within the US (ccTLD .com).
574
+ #
575
+ # If you'd like the Google Geocoder to prefer results within a given viewport,
576
+ # you can pass a Geokit::Bounds object as the :bias value.
577
+ #
578
+ # ==== EXAMPLES
579
+ # # By default, the geocoder will return Syracuse, NY
580
+ # Geokit::Geocoders::GoogleGeocoder.geocode('Syracuse').country_code # => 'US'
581
+ # # With country code biasing, it returns Syracuse in Sicily, Italy
582
+ # Geokit::Geocoders::GoogleGeocoder.geocode('Syracuse', :bias => :it).country_code # => 'IT'
583
+ #
584
+ # # By default, the geocoder will return Winnetka, IL
585
+ # Geokit::Geocoders::GoogleGeocoder.geocode('Winnetka').state # => 'IL'
586
+ # # When biased to an bounding box around California, it will now return the Winnetka neighbourhood, CA
587
+ # bounds = Geokit::Bounds.normalize([34.074081, -118.694401], [34.321129, -118.399487])
588
+ # Geokit::Geocoders::GoogleGeocoder.geocode('Winnetka', :bias => bounds).state # => 'CA'
589
+ def self.do_geocode(address, options = {})
590
+ bias_str = options[:bias] ? construct_bias_string_from_options(options[:bias]) : ''
591
+ address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
592
+
593
+ res = self.call_geocoder_service("http://maps.google.com/maps/api/geocode/json?sensor=false&address=#{Geokit::Inflector::url_escape(address_str)}#{bias_str}")
594
+ return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
595
+
596
+ json = res.body
597
+ logger.debug "Google geocoding. Address: #{address}. Result: #{CGI.escape(json)}"
598
+
599
+ return self.json2GeoLoc(json, address)
600
+ end
601
+
602
+ def self.construct_bias_string_from_options(bias)
603
+ if bias.is_a?(String) or bias.is_a?(Symbol)
604
+ # country code biasing
605
+ "&region=#{bias.to_s.downcase}"
606
+ elsif bias.is_a?(Bounds)
607
+ # viewport biasing
608
+ Geokit::Inflector::url_escape("&bounds=#{bias.sw.to_s}|#{bias.ne.to_s}")
609
+ end
610
+ end
611
+
612
+ def self.json2GeoLoc(json, address="")
613
+ ret=nil
614
+ results = MultiJson.decode(json)
615
+
616
+ if results['status'] == 'OVER_QUERY_LIMIT'
617
+ raise Geokit::TooManyQueriesError
618
+ end
619
+ if results['status'] == 'ZERO_RESULTS'
620
+ return GeoLoc.new
621
+ end
622
+ # this should probably be smarter.
623
+ if !results['status'] == 'OK'
624
+ raise Geokit::Geocoders::GeocodeError
625
+ end
626
+ # location_type stores additional data about the specified location.
627
+ # The following values are currently supported:
628
+ # "ROOFTOP" indicates that the returned result is a precise geocode
629
+ # for which we have location information accurate down to street
630
+ # address precision.
631
+ # "RANGE_INTERPOLATED" indicates that the returned result reflects an
632
+ # approximation (usually on a road) interpolated between two precise
633
+ # points (such as intersections). Interpolated results are generally
634
+ # returned when rooftop geocodes are unavailable for a street address.
635
+ # "GEOMETRIC_CENTER" indicates that the returned result is the
636
+ # geometric center of a result such as a polyline (for example, a
637
+ # street) or polygon (region).
638
+ # "APPROXIMATE" indicates that the returned result is approximate
639
+
640
+ # these do not map well. Perhaps we should guess better based on size
641
+ # of bounding box where it exists? Does it really matter?
642
+ accuracy = {
643
+ "ROOFTOP" => 9,
644
+ "RANGE_INTERPOLATED" => 8,
645
+ "GEOMETRIC_CENTER" => 5,
646
+ "APPROXIMATE" => 4
647
+ }
648
+
649
+ @unsorted = []
650
+
651
+ results['results'].each do |addr|
652
+ res = GeoLoc.new
653
+ res.provider = 'google3'
654
+ res.success = true
655
+ res.full_address = addr['formatted_address']
656
+
657
+ addr['address_components'].each do |comp|
658
+ case
659
+ when comp['types'].include?("subpremise")
660
+ res.sub_premise = comp['short_name']
661
+ when comp['types'].include?("street_number")
662
+ res.street_number = comp['short_name']
663
+ when comp['types'].include?("route")
664
+ res.street_name = comp['long_name']
665
+ when comp['types'].include?("locality")
666
+ res.city = comp['long_name']
667
+ when comp['types'].include?("administrative_area_level_1")
668
+ res.state = comp['short_name']
669
+ res.province = comp['short_name']
670
+ when comp['types'].include?("postal_code")
671
+ res.zip = comp['long_name']
672
+ when comp['types'].include?("country")
673
+ res.country_code = comp['short_name']
674
+ res.country = comp['long_name']
675
+ when comp['types'].include?("administrative_area_level_2")
676
+ res.district = comp['long_name']
677
+ end
678
+ end
679
+ if res.street_name
680
+ res.street_address=[res.street_number,res.street_name].join(' ').strip
681
+ end
682
+ res.accuracy = accuracy[addr['geometry']['location_type']]
683
+ res.precision=%w{unknown country state state city zip zip+4 street address building}[res.accuracy]
684
+ # try a few overrides where we can
685
+ if res.sub_premise
686
+ res.accuracy = 9
687
+ res.precision = 'building'
688
+ end
689
+ if res.street_name && res.precision=='city'
690
+ res.precision = 'street'
691
+ res.accuracy = 7
692
+ end
693
+
694
+ res.lat=addr['geometry']['location']['lat'].to_f
695
+ res.lng=addr['geometry']['location']['lng'].to_f
696
+
697
+ ne=Geokit::LatLng.new(
698
+ addr['geometry']['viewport']['northeast']['lat'].to_f,
699
+ addr['geometry']['viewport']['northeast']['lng'].to_f
700
+ )
701
+ sw=Geokit::LatLng.new(
702
+ addr['geometry']['viewport']['southwest']['lat'].to_f,
703
+ addr['geometry']['viewport']['southwest']['lng'].to_f
704
+ )
705
+ res.suggested_bounds = Geokit::Bounds.new(sw,ne)
706
+
707
+ @unsorted << res
708
+ end
709
+
710
+ all = @unsorted.sort_by { |a| a.accuracy }.reverse
711
+ encoded = all.first
712
+ encoded.all = all
713
+ return encoded
714
+ end
715
+ end
716
+
717
+ class FCCGeocoder < Geocoder
718
+
719
+ private
720
+ # Template method which does the reverse-geocode lookup.
721
+ def self.do_reverse_geocode(latlng)
722
+ latlng=LatLng.normalize(latlng)
723
+ res = self.call_geocoder_service("http://data.fcc.gov/api/block/find?format=json&latitude=#{Geokit::Inflector::url_escape(latlng.lat.to_s)}&longitude=#{Geokit::Inflector::url_escape(latlng.lng.to_s)}")
724
+ return GeoLoc.new unless (res.is_a?(Net::HTTPSuccess) || res.is_a?(Net::HTTPOK))
725
+ json = res.body
726
+ logger.debug "FCC reverse-geocoding. LL: #{latlng}. Result: #{json}"
727
+ return self.json2GeoLoc(json)
728
+ end
729
+
730
+ # Template method which does the geocode lookup.
731
+ #
732
+ # ==== EXAMPLES
733
+ # ll=GeoKit::LatLng.new(40, -85)
734
+ # Geokit::Geocoders::FCCGeocoder.geocode(ll) #
735
+
736
+ # JSON result looks like this
737
+ # => {"County"=>{"name"=>"Wayne", "FIPS"=>"18177"},
738
+ # "Block"=>{"FIPS"=>"181770103002004"},
739
+ # "executionTime"=>"0.099",
740
+ # "State"=>{"name"=>"Indiana", "code"=>"IN", "FIPS"=>"18"},
741
+ # "status"=>"OK"}
742
+
743
+ def self.json2GeoLoc(json, address="")
744
+ ret = nil
745
+ results = MultiJson.decode(json)
746
+
747
+ if results.has_key?('Err') and results['Err']["msg"] == 'There are no results for this location'
748
+ return GeoLoc.new
749
+ end
750
+ # this should probably be smarter.
751
+ if !results['status'] == 'OK'
752
+ raise Geokit::Geocoders::GeocodeError
753
+ end
754
+
755
+ res = GeoLoc.new
756
+ res.provider = 'fcc'
757
+ res.success = true
758
+ res.precision = 'block'
759
+ res.country_code = 'US'
760
+ res.district = results['County']['name']
761
+ res.district_fips = results['County']['FIPS']
762
+ res.state = results['State']['code']
763
+ res.state_fips = results['State']['FIPS']
764
+ res.block_fips = results['Block']['FIPS']
765
+
766
+ res
767
+ end
768
+ end
769
+ # -------------------------------------------------------------------------------------------
770
+ # IP Geocoders
771
+ # -------------------------------------------------------------------------------------------
772
+
773
+ # Provides geocoding based upon an IP address. The underlying web service is geoplugin.net
774
+ class GeoPluginGeocoder < Geocoder
775
+ private
776
+
777
+ def self.do_geocode(ip, options = {})
778
+ return GeoLoc.new unless /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})?$/.match(ip)
779
+ response = self.call_geocoder_service("http://www.geoplugin.net/xml.gp?ip=#{ip}")
780
+ return response.is_a?(Net::HTTPSuccess) ? parse_xml(response.body) : GeoLoc.new
781
+ rescue
782
+ logger.error "Caught an error during GeoPluginGeocoder geocoding call: "+$!
783
+ return GeoLoc.new
784
+ end
785
+
786
+ def self.parse_xml(xml)
787
+ xml = REXML::Document.new(xml)
788
+ geo = GeoLoc.new
789
+ geo.provider='geoPlugin'
790
+ geo.city = xml.elements['//geoplugin_city'].text
791
+ geo.state = xml.elements['//geoplugin_region'].text
792
+ geo.country_code = xml.elements['//geoplugin_countryCode'].text
793
+ geo.lat = xml.elements['//geoplugin_latitude'].text.to_f
794
+ geo.lng = xml.elements['//geoplugin_longitude'].text.to_f
795
+ geo.success = !!geo.city && !geo.city.empty?
796
+ return geo
797
+ end
798
+ end
799
+
800
+ # Provides geocoding based upon an IP address. The underlying web service is a hostip.info
801
+ # which sources their data through a combination of publicly available information as well
802
+ # as community contributions.
803
+ class IpGeocoder < Geocoder
804
+
805
+ # A number of non-routable IP ranges.
806
+ #
807
+ # --
808
+ # Sources for these:
809
+ # RFC 3330: Special-Use IPv4 Addresses
810
+ # The bogon list: http://www.cymru.com/Documents/bogon-list.html
811
+
812
+ NON_ROUTABLE_IP_RANGES = [
813
+ IPAddr.new('0.0.0.0/8'), # "This" Network
814
+ IPAddr.new('10.0.0.0/8'), # Private-Use Networks
815
+ IPAddr.new('14.0.0.0/8'), # Public-Data Networks
816
+ IPAddr.new('127.0.0.0/8'), # Loopback
817
+ IPAddr.new('169.254.0.0/16'), # Link local
818
+ IPAddr.new('172.16.0.0/12'), # Private-Use Networks
819
+ IPAddr.new('192.0.2.0/24'), # Test-Net
820
+ IPAddr.new('192.168.0.0/16'), # Private-Use Networks
821
+ IPAddr.new('198.18.0.0/15'), # Network Interconnect Device Benchmark Testing
822
+ IPAddr.new('224.0.0.0/4'), # Multicast
823
+ IPAddr.new('240.0.0.0/4') # Reserved for future use
824
+ ].freeze
825
+
826
+ private
827
+
828
+ # Given an IP address, returns a GeoLoc instance which contains latitude,
829
+ # longitude, city, and country code. Sets the success attribute to false if the ip
830
+ # parameter does not match an ip address.
831
+ def self.do_geocode(ip, options = {})
832
+ return GeoLoc.new unless /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})?$/.match(ip)
833
+ return GeoLoc.new if self.private_ip_address?(ip)
834
+ url = "http://api.hostip.info/get_html.php?ip=#{ip}&position=true"
835
+ response = self.call_geocoder_service(url)
836
+ response.is_a?(Net::HTTPSuccess) ? parse_body(response.body) : GeoLoc.new
837
+ rescue
838
+ logger.error "Caught an error during HostIp geocoding call: "+$!
839
+ return GeoLoc.new
840
+ end
841
+
842
+ # Converts the body to YAML since its in the form of:
843
+ #
844
+ # Country: UNITED STATES (US)
845
+ # City: Sugar Grove, IL
846
+ # Latitude: 41.7696
847
+ # Longitude: -88.4588
848
+ #
849
+ # then instantiates a GeoLoc instance to populate with location data.
850
+ def self.parse_body(body) # :nodoc:
851
+ yaml = YAML.load(body)
852
+ res = GeoLoc.new
853
+ res.provider = 'hostip'
854
+ res.city, res.state = yaml['City'].split(', ')
855
+ country, res.country_code = yaml['Country'].split(' (')
856
+ res.lat = yaml['Latitude']
857
+ res.lng = yaml['Longitude']
858
+ res.country_code.chop!
859
+ res.success = !(res.city =~ /\(.+\)/)
860
+ res
861
+ end
862
+
863
+ # Checks whether the IP address belongs to a private address range.
864
+ #
865
+ # This function is used to reduce the number of useless queries made to
866
+ # the geocoding service. Such queries can occur frequently during
867
+ # integration tests.
868
+ def self.private_ip_address?(ip)
869
+ return NON_ROUTABLE_IP_RANGES.any? { |range| range.include?(ip) }
870
+ end
871
+ end
872
+
873
+ # -------------------------------------------------------------------------------------------
874
+ # The Multi Geocoder
875
+ # -------------------------------------------------------------------------------------------
876
+
877
+ # Provides methods to geocode with a variety of geocoding service providers, plus failover
878
+ # among providers in the order you configure. When 2nd parameter is set 'true', perform
879
+ # ip location lookup with 'address' as the ip address.
880
+ #
881
+ # Goal:
882
+ # - homogenize the results of multiple geocoders
883
+ #
884
+ # Limitations:
885
+ # - currently only provides the first result. Sometimes geocoders will return multiple results.
886
+ # - currently discards the "accuracy" component of the geocoding calls
887
+ class MultiGeocoder < Geocoder
888
+
889
+ private
890
+ # This method will call one or more geocoders in the order specified in the
891
+ # configuration until one of the geocoders work.
892
+ #
893
+ # The failover approach is crucial for production-grade apps, but is rarely used.
894
+ # 98% of your geocoding calls will be successful with the first call
895
+ def self.do_geocode(address, options = {})
896
+ geocode_ip = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.match(address)
897
+ provider_order = geocode_ip ? Geokit::Geocoders::ip_provider_order : Geokit::Geocoders::provider_order
898
+
899
+ provider_order.each do |provider|
900
+ begin
901
+ klass = Geokit::Geocoders.const_get "#{Geokit::Inflector::camelize(provider.to_s)}Geocoder"
902
+ res = klass.send :geocode, address, options
903
+ return res if res.success?
904
+ rescue
905
+ 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}")
906
+ end
907
+ end
908
+ # If we get here, we failed completely.
909
+ GeoLoc.new
910
+ end
911
+
912
+ # This method will call one or more geocoders in the order specified in the
913
+ # configuration until one of the geocoders work, only this time it's going
914
+ # to try to reverse geocode a geographical point.
915
+ def self.do_reverse_geocode(latlng)
916
+ Geokit::Geocoders::provider_order.each do |provider|
917
+ begin
918
+ klass = Geokit::Geocoders.const_get "#{Geokit::Inflector::camelize(provider.to_s)}Geocoder"
919
+ res = klass.send :reverse_geocode, latlng
920
+ return res if res.success?
921
+ rescue
922
+ 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}")
923
+ end
924
+ end
925
+ # If we get here, we failed completely.
926
+ GeoLoc.new
927
+ end
928
+ end
929
+ end
930
+ end