badnaam-geokit 1.5.0

Sign up to get free protection for your applications and to get access to all the features.
data/Manifest.txt ADDED
@@ -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
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::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.
data/Rakefile ADDED
@@ -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
data/lib/geokit.rb ADDED
@@ -0,0 +1,30 @@
1
+ module Geokit
2
+ VERSION = '1.5.0'
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
@@ -0,0 +1,691 @@
1
+ require 'net/http'
2
+ require 'rexml/document'
3
+ require 'yaml'
4
+ require 'timeout'
5
+ require 'logger'
6
+
7
+ module Geokit
8
+
9
+ class TooManyQueriesError < StandardError; end
10
+
11
+ module Inflector
12
+
13
+ extend self
14
+
15
+ def titleize(word)
16
+ humanize(underscore(word)).gsub(/\b([a-z])/u) { $1.capitalize }
17
+ end
18
+
19
+ def underscore(camel_cased_word)
20
+ camel_cased_word.to_s.gsub(/::/, '/').
21
+ gsub(/([A-Z]+)([A-Z][a-z])/u,'\1_\2').
22
+ gsub(/([a-z\d])([A-Z])/u,'\1_\2').
23
+ tr("-", "_").
24
+ downcase
25
+ end
26
+
27
+ def humanize(lower_case_and_underscored_word)
28
+ lower_case_and_underscored_word.to_s.gsub(/_id$/, "").gsub(/_/, " ").capitalize
29
+ end
30
+
31
+ def snake_case(s)
32
+ return s.downcase if s =~ /^[A-Z]+$/u
33
+ s.gsub(/([A-Z]+)(?=[A-Z][a-z]?)|\B[A-Z]/u, '_\&') =~ /_*(.*)/
34
+ return $+.downcase
35
+
36
+ end
37
+
38
+ def url_escape(s)
39
+ s.gsub(/([^ a-zA-Z0-9_.-]+)/nu) do
40
+ '%' + $1.unpack('H2' * $1.size).join('%').upcase
41
+ end.tr(' ', '+')
42
+ end
43
+
44
+ def camelize(str)
45
+ str.split('_').map {|w| w.capitalize}.join
46
+ end
47
+ end
48
+
49
+ # Contains a range of geocoders:
50
+ #
51
+ # ### "regular" address geocoders
52
+ # * Yahoo Geocoder - requires an API key.
53
+ # * Geocoder.us - may require authentication if performing more than the free request limit.
54
+ # * Geocoder.ca - for Canada; may require authentication as well.
55
+ # * Geonames - a free geocoder
56
+ #
57
+ # ### address geocoders that also provide reverse geocoding
58
+ # * Google Geocoder - requires an API key.
59
+ #
60
+ # ### IP address geocoders
61
+ # * IP Geocoder - geocodes an IP address using hostip.info's web service.
62
+ # * Geoplugin.net -- another IP address geocoder
63
+ #
64
+ # ### The Multigeocoder
65
+ # * Multi Geocoder - provides failover for the physical location geocoders.
66
+ #
67
+ # Some of these geocoders require configuration. You don't have to provide it here. See the README.
68
+ module Geocoders
69
+ @@proxy_addr = nil
70
+ @@proxy_port = nil
71
+ @@proxy_user = nil
72
+ @@proxy_pass = nil
73
+ @@request_timeout = nil
74
+ @@yahoo = 'REPLACE_WITH_YOUR_YAHOO_KEY'
75
+ @@google = 'REPLACE_WITH_YOUR_GOOGLE_KEY'
76
+ @@geocoder_us = false
77
+ @@geocoder_ca = false
78
+ @@geonames = false
79
+ @@provider_order = [:google,:us]
80
+ @@ip_provider_order = [:geo_plugin,:ip]
81
+ @@logger=Logger.new(STDOUT)
82
+ @@logger.level=Logger::INFO
83
+ @@domain = nil
84
+
85
+ def self.__define_accessors
86
+ class_variables.each do |v|
87
+ sym = v.to_s.delete("@").to_sym
88
+ unless self.respond_to? sym
89
+ module_eval <<-EOS, __FILE__, __LINE__
90
+ def self.#{sym}
91
+ value = if defined?(#{sym.to_s.upcase})
92
+ #{sym.to_s.upcase}
93
+ else
94
+ @@#{sym}
95
+ end
96
+ if value.is_a?(Hash)
97
+ value = (self.domain.nil? ? nil : value[self.domain]) || value.values.first
98
+ end
99
+ value
100
+ end
101
+
102
+ def self.#{sym}=(obj)
103
+ @@#{sym} = obj
104
+ end
105
+ EOS
106
+ end
107
+ end
108
+ end
109
+
110
+ __define_accessors
111
+
112
+ # Error which is thrown in the event a geocoding error occurs.
113
+ class GeocodeError < StandardError; end
114
+
115
+ # -------------------------------------------------------------------------------------------
116
+ # Geocoder Base class -- every geocoder should inherit from this
117
+ # -------------------------------------------------------------------------------------------
118
+
119
+ # The Geocoder base class which defines the interface to be used by all
120
+ # other geocoders.
121
+ class Geocoder
122
+ # Main method which calls the do_geocode template method which subclasses
123
+ # are responsible for implementing. Returns a populated GeoLoc or an
124
+ # empty one with a failed success code.
125
+ def self.geocode(address, options = {})
126
+ res = do_geocode(address, options)
127
+ return res.nil? ? GeoLoc.new : res
128
+ end
129
+ # Main method which calls the do_reverse_geocode template method which subclasses
130
+ # are responsible for implementing. Returns a populated GeoLoc or an
131
+ # empty one with a failed success code.
132
+ def self.reverse_geocode(latlng)
133
+ res = do_reverse_geocode(latlng)
134
+ return res.success? ? res : GeoLoc.new
135
+ end
136
+
137
+ # Call the geocoder service using the timeout if configured.
138
+ def self.call_geocoder_service(url)
139
+ Timeout::timeout(Geokit::Geocoders::request_timeout) { return self.do_get(url) } if Geokit::Geocoders::request_timeout
140
+ return self.do_get(url)
141
+ rescue TimeoutError
142
+ return nil
143
+ end
144
+
145
+ # Not all geocoders can do reverse geocoding. So, unless the subclass explicitly overrides this method,
146
+ # a call to reverse_geocode will return an empty GeoLoc. If you happen to be using MultiGeocoder,
147
+ # this will cause it to failover to the next geocoder, which will hopefully be one which supports reverse geocoding.
148
+ def self.do_reverse_geocode(latlng)
149
+ return GeoLoc.new
150
+ end
151
+
152
+ protected
153
+
154
+ def self.logger()
155
+ Geokit::Geocoders::logger
156
+ end
157
+
158
+ private
159
+
160
+ # Wraps the geocoder call around a proxy if necessary.
161
+ def self.do_get(url)
162
+ uri = URI.parse(url)
163
+ req = Net::HTTP::Get.new(url)
164
+ req.basic_auth(uri.user, uri.password) if uri.userinfo
165
+ res = Net::HTTP::Proxy(GeoKit::Geocoders::proxy_addr,
166
+ GeoKit::Geocoders::proxy_port,
167
+ GeoKit::Geocoders::proxy_user,
168
+ GeoKit::Geocoders::proxy_pass).start(uri.host, uri.port) { |http| http.get(uri.path + "?" + uri.query) }
169
+ return res
170
+ end
171
+
172
+ # Adds subclass' geocode method making it conveniently available through
173
+ # the base class.
174
+ def self.inherited(clazz)
175
+ class_name = clazz.name.split('::').last
176
+ src = <<-END_SRC
177
+ def self.#{Geokit::Inflector.underscore(class_name)}(address, options = {})
178
+ #{class_name}.geocode(address, options)
179
+ end
180
+ END_SRC
181
+ class_eval(src)
182
+ end
183
+ end
184
+
185
+ # -------------------------------------------------------------------------------------------
186
+ # "Regular" Address geocoders
187
+ # -------------------------------------------------------------------------------------------
188
+
189
+ # Geocoder CA geocoder implementation. Requires the Geokit::Geocoders::GEOCODER_CA variable to
190
+ # contain true or false based upon whether authentication is to occur. Conforms to the
191
+ # interface set by the Geocoder class.
192
+ #
193
+ # Returns a response like:
194
+ # <?xml version="1.0" encoding="UTF-8" ?>
195
+ # <geodata>
196
+ # <latt>49.243086</latt>
197
+ # <longt>-123.153684</longt>
198
+ # </geodata>
199
+ class CaGeocoder < Geocoder
200
+
201
+ private
202
+
203
+ # Template method which does the geocode lookup.
204
+ def self.do_geocode(address, options = {})
205
+ raise ArgumentError('Geocoder.ca requires a GeoLoc argument') unless address.is_a?(GeoLoc)
206
+ url = construct_request(address)
207
+ res = self.call_geocoder_service(url)
208
+ return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
209
+ xml = res.body
210
+ logger.debug "Geocoder.ca geocoding. Address: #{address}. Result: #{xml}"
211
+ # Parse the document.
212
+ doc = REXML::Document.new(xml)
213
+ address.lat = doc.elements['//latt'].text
214
+ address.lng = doc.elements['//longt'].text
215
+ address.success = true
216
+ return address
217
+ rescue
218
+ logger.error "Caught an error during Geocoder.ca geocoding call: "+$!
219
+ return GeoLoc.new
220
+ end
221
+
222
+ # Formats the request in the format acceptable by the CA geocoder.
223
+ def self.construct_request(location)
224
+ url = ""
225
+ url += add_ampersand(url) + "stno=#{location.street_number}" if location.street_address
226
+ url += add_ampersand(url) + "addresst=#{Geokit::Inflector::url_escape(location.street_name)}" if location.street_address
227
+ url += add_ampersand(url) + "city=#{Geokit::Inflector::url_escape(location.city)}" if location.city
228
+ url += add_ampersand(url) + "prov=#{location.state}" if location.state
229
+ url += add_ampersand(url) + "postal=#{location.zip}" if location.zip
230
+ url += add_ampersand(url) + "auth=#{Geokit::Geocoders::geocoder_ca}" if Geokit::Geocoders::geocoder_ca
231
+ url += add_ampersand(url) + "geoit=xml"
232
+ 'http://geocoder.ca/?' + url
233
+ end
234
+
235
+ def self.add_ampersand(url)
236
+ url && url.length > 0 ? "&" : ""
237
+ end
238
+ end
239
+
240
+ # Geocoder Us geocoder implementation. Requires the Geokit::Geocoders::GEOCODER_US variable to
241
+ # contain true or false based upon whether authentication is to occur. Conforms to the
242
+ # interface set by the Geocoder class.
243
+ class UsGeocoder < Geocoder
244
+
245
+ private
246
+ def self.do_geocode(address, options = {})
247
+ address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
248
+
249
+ query = (address_str =~ /^\d{5}(?:-\d{4})?$/ ? "zip" : "address") + "=#{Geokit::Inflector::url_escape(address_str)}"
250
+ url = if GeoKit::Geocoders::geocoder_us
251
+ "http://#{GeoKit::Geocoders::geocoder_us}@geocoder.us/member/service/csv/geocode"
252
+ else
253
+ "http://geocoder.us/service/csv/geocode"
254
+ end
255
+
256
+ url = "#{url}?#{query}"
257
+ res = self.call_geocoder_service(url)
258
+
259
+ return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
260
+ data = res.body
261
+ logger.debug "Geocoder.us geocoding. Address: #{address}. Result: #{data}"
262
+ array = data.chomp.split(',')
263
+
264
+ if array.length == 5
265
+ res=GeoLoc.new
266
+ res.lat,res.lng,res.city,res.state,res.zip=array
267
+ res.country_code='US'
268
+ res.success=true
269
+ return res
270
+ elsif array.length == 6
271
+ res=GeoLoc.new
272
+ res.lat,res.lng,res.street_address,res.city,res.state,res.zip=array
273
+ res.country_code='US'
274
+ res.success=true
275
+ return res
276
+ else
277
+ logger.info "geocoder.us was unable to geocode address: "+address
278
+ return GeoLoc.new
279
+ end
280
+ rescue
281
+ logger.error "Caught an error during geocoder.us geocoding call: "+$!
282
+ return GeoLoc.new
283
+
284
+ end
285
+ end
286
+
287
+ # Yahoo geocoder implementation. Requires the Geokit::Geocoders::YAHOO variable to
288
+ # contain a Yahoo API key. Conforms to the interface set by the Geocoder class.
289
+ class YahooGeocoder < Geocoder
290
+
291
+ private
292
+
293
+ # Template method which does the geocode lookup.
294
+ def self.do_geocode(address, options = {})
295
+ address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
296
+ url="http://api.local.yahoo.com/MapsService/V1/geocode?appid=#{Geokit::Geocoders::yahoo}&location=#{Geokit::Inflector::url_escape(address_str)}"
297
+ res = self.call_geocoder_service(url)
298
+ return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
299
+ xml = res.body
300
+ doc = REXML::Document.new(xml)
301
+ logger.debug "Yahoo geocoding. Address: #{address}. Result: #{xml}"
302
+
303
+ if doc.elements['//ResultSet']
304
+ res=GeoLoc.new
305
+
306
+ #basic
307
+ res.lat=doc.elements['//Latitude'].text
308
+ res.lng=doc.elements['//Longitude'].text
309
+ res.country_code=doc.elements['//Country'].text
310
+ res.provider='yahoo'
311
+
312
+ #extended - false if not available
313
+ res.city=doc.elements['//City'].text if doc.elements['//City'] && doc.elements['//City'].text != nil
314
+ res.state=doc.elements['//State'].text if doc.elements['//State'] && doc.elements['//State'].text != nil
315
+ res.zip=doc.elements['//Zip'].text if doc.elements['//Zip'] && doc.elements['//Zip'].text != nil
316
+ res.street_address=doc.elements['//Address'].text if doc.elements['//Address'] && doc.elements['//Address'].text != nil
317
+ res.precision=doc.elements['//Result'].attributes['precision'] if doc.elements['//Result']
318
+ # set the accuracy as google does (added by Andruby)
319
+ res.accuracy=%w{unknown country state state city zip zip+4 street address building}.index(res.precision)
320
+ res.success=true
321
+ #badnaam change - cache the result
322
+ if !address.nil?
323
+ logger.info "Caching location #{address}"
324
+ GeocodeCache.store(address, res.city, res.state, res.lat, res.lng, "yahoo")
325
+ end
326
+
327
+ return res
328
+ else
329
+ logger.info "Yahoo was unable to geocode address: "+address
330
+ return GeoLoc.new
331
+ end
332
+
333
+ rescue
334
+ logger.info "Caught an error during Yahoo geocoding call: "+$!
335
+ return GeoLoc.new
336
+ end
337
+ end
338
+
339
+ # Another geocoding web service
340
+ # http://www.geonames.org
341
+ class GeonamesGeocoder < Geocoder
342
+
343
+ private
344
+
345
+ # Template method which does the geocode lookup.
346
+ def self.do_geocode(address, options = {})
347
+ address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
348
+ # geonames need a space seperated search string
349
+ address_str.gsub!(/,/, " ")
350
+ params = "/postalCodeSearch?placename=#{Geokit::Inflector::url_escape(address_str)}&maxRows=10"
351
+
352
+ if(GeoKit::Geocoders::geonames)
353
+ url = "http://ws.geonames.net#{params}&username=#{GeoKit::Geocoders::geonames}"
354
+ else
355
+ url = "http://ws.geonames.org#{params}"
356
+ end
357
+
358
+ res = self.call_geocoder_service(url)
359
+
360
+ return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
361
+
362
+ xml=res.body
363
+ logger.debug "Geonames geocoding. Address: #{address}. Result: #{xml}"
364
+ doc=REXML::Document.new(xml)
365
+
366
+ if(doc.elements['//geonames/totalResultsCount'].text.to_i > 0)
367
+ res=GeoLoc.new
368
+
369
+ # only take the first result
370
+ res.lat=doc.elements['//code/lat'].text if doc.elements['//code/lat']
371
+ res.lng=doc.elements['//code/lng'].text if doc.elements['//code/lng']
372
+ res.country_code=doc.elements['//code/countryCode'].text if doc.elements['//code/countryCode']
373
+ res.provider='genomes'
374
+ res.city=doc.elements['//code/name'].text if doc.elements['//code/name']
375
+ res.state=doc.elements['//code/adminName1'].text if doc.elements['//code/adminName1']
376
+ res.zip=doc.elements['//code/postalcode'].text if doc.elements['//code/postalcode']
377
+ res.success=true
378
+ #badnaam change - cache the result
379
+ if !address.nil?
380
+ logger.info "Caching location #{address}"
381
+ GeocodeCache.store(address, res.city, res.state, res.lat, res.lng, "geonames")
382
+ end
383
+
384
+ return res
385
+ else
386
+ logger.info "Geonames was unable to geocode address: "+address
387
+ return GeoLoc.new
388
+ end
389
+
390
+ rescue
391
+ logger.error "Caught an error during Geonames geocoding call: "+$!
392
+ end
393
+ end
394
+
395
+ # -------------------------------------------------------------------------------------------
396
+ # Address geocoders that also provide reverse geocoding
397
+ # -------------------------------------------------------------------------------------------
398
+
399
+ # Google geocoder implementation. Requires the Geokit::Geocoders::GOOGLE variable to
400
+ # contain a Google API key. Conforms to the interface set by the Geocoder class.
401
+ class GoogleGeocoder < Geocoder
402
+
403
+ private
404
+
405
+ # Template method which does the reverse-geocode lookup.
406
+ def self.do_reverse_geocode(latlng)
407
+ latlng=LatLng.normalize(latlng)
408
+ 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")
409
+ # 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"))
410
+ return GeoLoc.new unless (res.is_a?(Net::HTTPSuccess) || res.is_a?(Net::HTTPOK))
411
+ xml = res.body
412
+ logger.debug "Google reverse-geocoding. LL: #{latlng}. Result: #{xml}"
413
+ return self.xml2GeoLoc(xml)
414
+ end
415
+
416
+ # Template method which does the geocode lookup.
417
+ #
418
+ # Supports viewport/country code biasing
419
+ #
420
+ # ==== OPTIONS
421
+ # * :bias - This option makes the Google Geocoder return results biased to a particular
422
+ # country or viewport. Country code biasing is achieved by passing the ccTLD
423
+ # ('uk' for .co.uk, for example) as a :bias value. For a list of ccTLD's,
424
+ # look here: http://en.wikipedia.org/wiki/CcTLD. By default, the geocoder
425
+ # will be biased to results within the US (ccTLD .com).
426
+ #
427
+ # If you'd like the Google Geocoder to prefer results within a given viewport,
428
+ # you can pass a Geokit::Bounds object as the :bias value.
429
+ #
430
+ # ==== EXAMPLES
431
+ # # By default, the geocoder will return Syracuse, NY
432
+ # Geokit::Geocoders::GoogleGeocoder.geocode('Syracuse').country_code # => 'US'
433
+ # # With country code biasing, it returns Syracuse in Sicily, Italy
434
+ # Geokit::Geocoders::GoogleGeocoder.geocode('Syracuse', :bias => :it).country_code # => 'IT'
435
+ #
436
+ # # By default, the geocoder will return Winnetka, IL
437
+ # Geokit::Geocoders::GoogleGeocoder.geocode('Winnetka').state # => 'IL'
438
+ # # When biased to an bounding box around California, it will now return the Winnetka neighbourhood, CA
439
+ # bounds = Geokit::Bounds.normalize([34.074081, -118.694401], [34.321129, -118.399487])
440
+ # Geokit::Geocoders::GoogleGeocoder.geocode('Winnetka', :bias => bounds).state # => 'CA'
441
+ def self.do_geocode(address, options = {})
442
+ bias_str = options[:bias] ? construct_bias_string_from_options(options[:bias]) : ''
443
+ address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
444
+ 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")
445
+ return GeoLoc.new if !res.is_a?(Net::HTTPSuccess)
446
+ xml = res.body
447
+ logger.debug "Google geocoding. Address: #{address}. Result: #{xml}"
448
+ return self.xml2GeoLoc(xml, address)
449
+ end
450
+
451
+ def self.construct_bias_string_from_options(bias)
452
+ if bias.is_a?(String) or bias.is_a?(Symbol)
453
+ # country code biasing
454
+ "&gl=#{bias.to_s.downcase}"
455
+ elsif bias.is_a?(Bounds)
456
+ # viewport biasing
457
+ "&ll=#{bias.center.ll}&spn=#{bias.to_span.ll}"
458
+ end
459
+ end
460
+
461
+ def self.xml2GeoLoc(xml, address="")
462
+ doc=REXML::Document.new(xml)
463
+
464
+ if doc.elements['//kml/Response/Status/code'].text == '200'
465
+ geoloc = nil
466
+ # Google can return multiple results as //Placemark elements.
467
+ # iterate through each and extract each placemark as a geoloc
468
+ doc.each_element('//Placemark') do |e|
469
+ extracted_geoloc = extract_placemark(e) # g is now an instance of GeoLoc
470
+ if geoloc.nil?
471
+ # first time through, geoloc is still nil, so we make it the geoloc we just extracted
472
+ geoloc = extracted_geoloc
473
+ else
474
+ # second (and subsequent) iterations, we push additional
475
+ # geolocs onto "geoloc.all"
476
+ geoloc.all.push(extracted_geoloc)
477
+ end
478
+ end
479
+ return geoloc
480
+ elsif doc.elements['//kml/Response/Status/code'].text == '620'
481
+ raise Geokit::TooManyQueriesError
482
+ else
483
+ logger.info "Google was unable to geocode address: "+address
484
+ return GeoLoc.new
485
+ end
486
+
487
+ rescue Geokit::TooManyQueriesError
488
+ # re-raise because of other rescue
489
+ 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."
490
+ rescue
491
+ logger.error "Caught an error during Google geocoding call: "+$!
492
+ return GeoLoc.new
493
+ end
494
+
495
+ # extracts a single geoloc from a //placemark element in the google results xml
496
+ def self.extract_placemark(doc)
497
+ res = GeoLoc.new
498
+ coordinates=doc.elements['.//coordinates'].text.to_s.split(',')
499
+
500
+ #basics
501
+ res.lat=coordinates[1]
502
+ res.lng=coordinates[0]
503
+ res.country_code=doc.elements['.//CountryNameCode'].text if doc.elements['.//CountryNameCode']
504
+ res.provider='google'
505
+
506
+ #extended -- false if not not available
507
+ res.city = doc.elements['.//LocalityName'].text if doc.elements['.//LocalityName']
508
+ res.state = doc.elements['.//AdministrativeAreaName'].text if doc.elements['.//AdministrativeAreaName']
509
+ res.province = doc.elements['.//SubAdministrativeAreaName'].text if doc.elements['.//SubAdministrativeAreaName']
510
+ res.full_address = doc.elements['.//address'].text if doc.elements['.//address'] # google provides it
511
+ res.zip = doc.elements['.//PostalCodeNumber'].text if doc.elements['.//PostalCodeNumber']
512
+ res.street_address = doc.elements['.//ThoroughfareName'].text if doc.elements['.//ThoroughfareName']
513
+ res.country = doc.elements['.//CountryName'].text if doc.elements['.//CountryName']
514
+ res.district = doc.elements['.//DependentLocalityName'].text if doc.elements['.//DependentLocalityName']
515
+ # Translate accuracy into Yahoo-style token address, street, zip, zip+4, city, state, country
516
+ # For Google, 1=low accuracy, 8=high accuracy
517
+ address_details=doc.elements['.//*[local-name() = "AddressDetails"]']
518
+ res.accuracy = address_details ? address_details.attributes['Accuracy'].to_i : 0
519
+ res.precision=%w{unknown country state state city zip zip+4 street address building}[res.accuracy]
520
+
521
+ # google returns a set of suggested boundaries for the geocoded result
522
+ if suggested_bounds = doc.elements['//LatLonBox']
523
+ res.suggested_bounds = Bounds.normalize(
524
+ [suggested_bounds.attributes['south'], suggested_bounds.attributes['west']],
525
+ [suggested_bounds.attributes['north'], suggested_bounds.attributes['east']])
526
+ end
527
+
528
+ res.success=true
529
+ #badnaam change - cache the result
530
+ #if !address.nil?
531
+ logger.info "Caching location #{res.zip}"
532
+ GeocodeCache.store(res.zip, res.city, res.state, res.lat, res.lng, "google")
533
+ #end
534
+ return res
535
+ end
536
+ end
537
+
538
+
539
+ # -------------------------------------------------------------------------------------------
540
+ # IP Geocoders
541
+ # -------------------------------------------------------------------------------------------
542
+
543
+ # Provides geocoding based upon an IP address. The underlying web service is geoplugin.net
544
+ class GeoPluginGeocoder < Geocoder
545
+ private
546
+
547
+ def self.do_geocode(ip, options = {})
548
+ return GeoLoc.new unless /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})?$/.match(ip)
549
+ response = self.call_geocoder_service("http://www.geoplugin.net/xml.gp?ip=#{ip}")
550
+ return response.is_a?(Net::HTTPSuccess) ? parse_xml(response.body) : GeoLoc.new
551
+ rescue
552
+ logger.error "Caught an error during GeoPluginGeocoder geocoding call: "+$!
553
+ return GeoLoc.new
554
+ end
555
+
556
+ def self.parse_xml(xml)
557
+ xml = REXML::Document.new(xml)
558
+ geo = GeoLoc.new
559
+ geo.provider='geoPlugin'
560
+ geo.city = xml.elements['//geoplugin_city'].text
561
+ geo.state = xml.elements['//geoplugin_region'].text
562
+ geo.country_code = xml.elements['//geoplugin_countryCode'].text
563
+ geo.lat = xml.elements['//geoplugin_latitude'].text.to_f
564
+ geo.lng = xml.elements['//geoplugin_longitude'].text.to_f
565
+ geo.success = !!geo.city && !geo.city.empty?
566
+ return geo
567
+ end
568
+ end
569
+
570
+ # Provides geocoding based upon an IP address. The underlying web service is a hostip.info
571
+ # which sources their data through a combination of publicly available information as well
572
+ # as community contributions.
573
+ class IpGeocoder < Geocoder
574
+
575
+ private
576
+
577
+ # Given an IP address, returns a GeoLoc instance which contains latitude,
578
+ # longitude, city, and country code. Sets the success attribute to false if the ip
579
+ # parameter does not match an ip address.
580
+ def self.do_geocode(ip, options = {})
581
+ return GeoLoc.new if '0.0.0.0' == ip
582
+ return GeoLoc.new unless /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})?$/.match(ip)
583
+ url = "http://api.hostip.info/get_html.php?ip=#{ip}&position=true"
584
+ response = self.call_geocoder_service(url)
585
+ response.is_a?(Net::HTTPSuccess) ? parse_body(response.body) : GeoLoc.new
586
+ rescue
587
+ logger.error "Caught an error during HostIp geocoding call: "+$!
588
+ return GeoLoc.new
589
+ end
590
+
591
+ # Converts the body to YAML since its in the form of:
592
+ #
593
+ # Country: UNITED STATES (US)
594
+ # City: Sugar Grove, IL
595
+ # Latitude: 41.7696
596
+ # Longitude: -88.4588
597
+ #
598
+ # then instantiates a GeoLoc instance to populate with location data.
599
+ def self.parse_body(body) # :nodoc:
600
+ yaml = YAML.load(body)
601
+ res = GeoLoc.new
602
+ res.provider = 'hostip'
603
+ res.city, res.state = yaml['City'].split(', ')
604
+ country, res.country_code = yaml['Country'].split(' (')
605
+ res.lat = yaml['Latitude']
606
+ res.lng = yaml['Longitude']
607
+ res.country_code.chop!
608
+ res.success = !(res.city =~ /\(.+\)/)
609
+ res
610
+ end
611
+ end
612
+
613
+
614
+
615
+ # -------------------------------------------------------------------------------------------
616
+ # The Multi Geocoder
617
+ # -------------------------------------------------------------------------------------------
618
+
619
+ # Provides methods to geocode with a variety of geocoding service providers, plus failover
620
+ # among providers in the order you configure. When 2nd parameter is set 'true', perform
621
+ # ip location lookup with 'address' as the ip address.
622
+ #
623
+ # Goal:
624
+ # - homogenize the results of multiple geocoders
625
+ #
626
+ # Limitations:
627
+ # - currently only provides the first result. Sometimes geocoders will return multiple results.
628
+ # - currently discards the "accuracy" component of the geocoding calls
629
+ class MultiGeocoder < Geocoder
630
+
631
+ private
632
+ # This method will call one or more geocoders in the order specified in the
633
+ # configuration until one of the geocoders work.
634
+ #
635
+ # The failover approach is crucial for production-grade apps, but is rarely used.
636
+ # 98% of your geocoding calls will be successful with the first call
637
+ def self.do_geocode(address, options = {})
638
+ geocode_ip = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.match(address)
639
+ provider_order = geocode_ip ? Geokit::Geocoders::ip_provider_order : Geokit::Geocoders::provider_order
640
+
641
+ provider_order.each do |provider|
642
+ begin
643
+ klass = Geokit::Geocoders.const_get "#{Geokit::Inflector::camelize(provider.to_s)}Geocoder"
644
+ res = klass.send :geocode, address, options
645
+ return res if res.success?
646
+ rescue
647
+ 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}")
648
+ end
649
+ end
650
+ # If we get here, we failed completely.
651
+ GeoLoc.new
652
+ end
653
+
654
+ # This method will call one or more geocoders in the order specified in the
655
+ # configuration until one of the geocoders work, only this time it's going
656
+ # to try to reverse geocode a geographical point.
657
+ def self.do_reverse_geocode(latlng)
658
+ Geokit::Geocoders::provider_order.each do |provider|
659
+ begin
660
+ klass = Geokit::Geocoders.const_get "#{Geokit::Inflector::camelize(provider.to_s)}Geocoder"
661
+ res = klass.send :reverse_geocode, latlng
662
+ return res if res.success?
663
+ rescue
664
+ 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}")
665
+ end
666
+ end
667
+ # If we get here, we failed completely.
668
+ GeoLoc.new
669
+ end
670
+ end
671
+ #badnaam modification
672
+ class CacheGeocoder < Geocoder
673
+ private
674
+
675
+ def self.do_geocode(address, options = {})
676
+ cache = GeocodeCache.find(:first, :conditions => ["address = ?",address])
677
+ if cache.nil?
678
+ GeoLoc.new
679
+ else
680
+ logger.info("Found #{address} in Cache")
681
+ res = GeoLoc.new(:lat=>cache.lat, :lng=>cache.lng, :city => cache.city, :state => cache.state, :address => cache.address)
682
+ res.success = true
683
+ res
684
+ end
685
+ end
686
+ end
687
+ #End badnaam modification
688
+ end
689
+ end
690
+
691
+