geocoder-sgonyea 1.1.6.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (122) hide show
  1. data/.gitignore +5 -0
  2. data/.travis.yml +23 -0
  3. data/CHANGELOG.md +298 -0
  4. data/LICENSE +20 -0
  5. data/README.md +656 -0
  6. data/Rakefile +25 -0
  7. data/bin/geocode +5 -0
  8. data/examples/autoexpire_cache.rb +28 -0
  9. data/gemfiles/Gemfile.mongoid-2.4.x +15 -0
  10. data/lib/generators/geocoder/config/config_generator.rb +14 -0
  11. data/lib/generators/geocoder/config/templates/initializer.rb +21 -0
  12. data/lib/geocoder.rb +55 -0
  13. data/lib/geocoder/cache.rb +85 -0
  14. data/lib/geocoder/calculations.rb +319 -0
  15. data/lib/geocoder/cli.rb +114 -0
  16. data/lib/geocoder/configuration.rb +130 -0
  17. data/lib/geocoder/configuration_hash.rb +11 -0
  18. data/lib/geocoder/exceptions.rb +21 -0
  19. data/lib/geocoder/lookup.rb +82 -0
  20. data/lib/geocoder/lookups/base.rb +250 -0
  21. data/lib/geocoder/lookups/bing.rb +47 -0
  22. data/lib/geocoder/lookups/freegeoip.rb +47 -0
  23. data/lib/geocoder/lookups/geocoder_ca.rb +54 -0
  24. data/lib/geocoder/lookups/google.rb +62 -0
  25. data/lib/geocoder/lookups/google_premier.rb +47 -0
  26. data/lib/geocoder/lookups/mapquest.rb +43 -0
  27. data/lib/geocoder/lookups/maxmind.rb +88 -0
  28. data/lib/geocoder/lookups/nominatim.rb +45 -0
  29. data/lib/geocoder/lookups/ovi.rb +52 -0
  30. data/lib/geocoder/lookups/test.rb +38 -0
  31. data/lib/geocoder/lookups/yahoo.rb +84 -0
  32. data/lib/geocoder/lookups/yandex.rb +54 -0
  33. data/lib/geocoder/models/active_record.rb +46 -0
  34. data/lib/geocoder/models/base.rb +42 -0
  35. data/lib/geocoder/models/mongo_base.rb +60 -0
  36. data/lib/geocoder/models/mongo_mapper.rb +26 -0
  37. data/lib/geocoder/models/mongoid.rb +32 -0
  38. data/lib/geocoder/query.rb +103 -0
  39. data/lib/geocoder/railtie.rb +26 -0
  40. data/lib/geocoder/request.rb +23 -0
  41. data/lib/geocoder/results/base.rb +67 -0
  42. data/lib/geocoder/results/bing.rb +48 -0
  43. data/lib/geocoder/results/freegeoip.rb +45 -0
  44. data/lib/geocoder/results/geocoder_ca.rb +60 -0
  45. data/lib/geocoder/results/google.rb +106 -0
  46. data/lib/geocoder/results/google_premier.rb +6 -0
  47. data/lib/geocoder/results/mapquest.rb +51 -0
  48. data/lib/geocoder/results/maxmind.rb +136 -0
  49. data/lib/geocoder/results/nominatim.rb +94 -0
  50. data/lib/geocoder/results/ovi.rb +62 -0
  51. data/lib/geocoder/results/test.rb +16 -0
  52. data/lib/geocoder/results/yahoo.rb +55 -0
  53. data/lib/geocoder/results/yandex.rb +80 -0
  54. data/lib/geocoder/sql.rb +106 -0
  55. data/lib/geocoder/stores/active_record.rb +259 -0
  56. data/lib/geocoder/stores/base.rb +120 -0
  57. data/lib/geocoder/stores/mongo_base.rb +85 -0
  58. data/lib/geocoder/stores/mongo_mapper.rb +13 -0
  59. data/lib/geocoder/stores/mongoid.rb +13 -0
  60. data/lib/geocoder/version.rb +3 -0
  61. data/lib/hash_recursive_merge.rb +74 -0
  62. data/lib/oauth_util.rb +112 -0
  63. data/lib/tasks/geocoder.rake +25 -0
  64. data/test/active_record_test.rb +15 -0
  65. data/test/cache_test.rb +19 -0
  66. data/test/calculations_test.rb +195 -0
  67. data/test/configuration_test.rb +78 -0
  68. data/test/custom_block_test.rb +32 -0
  69. data/test/error_handling_test.rb +43 -0
  70. data/test/fixtures/bing_invalid_key +1 -0
  71. data/test/fixtures/bing_madison_square_garden +40 -0
  72. data/test/fixtures/bing_no_results +16 -0
  73. data/test/fixtures/bing_reverse +42 -0
  74. data/test/fixtures/freegeoip_74_200_247_59 +12 -0
  75. data/test/fixtures/freegeoip_no_results +1 -0
  76. data/test/fixtures/geocoder_ca_madison_square_garden +1 -0
  77. data/test/fixtures/geocoder_ca_no_results +1 -0
  78. data/test/fixtures/geocoder_ca_reverse +34 -0
  79. data/test/fixtures/google_garbage +456 -0
  80. data/test/fixtures/google_madison_square_garden +57 -0
  81. data/test/fixtures/google_no_city_data +44 -0
  82. data/test/fixtures/google_no_locality +51 -0
  83. data/test/fixtures/google_no_results +4 -0
  84. data/test/fixtures/mapquest_madison_square_garden +52 -0
  85. data/test/fixtures/mapquest_no_results +7 -0
  86. data/test/fixtures/maxmind_24_24_24_21 +1 -0
  87. data/test/fixtures/maxmind_24_24_24_22 +1 -0
  88. data/test/fixtures/maxmind_24_24_24_23 +1 -0
  89. data/test/fixtures/maxmind_24_24_24_24 +1 -0
  90. data/test/fixtures/maxmind_74_200_247_59 +1 -0
  91. data/test/fixtures/maxmind_invalid_key +1 -0
  92. data/test/fixtures/maxmind_no_results +1 -0
  93. data/test/fixtures/nominatim_madison_square_garden +150 -0
  94. data/test/fixtures/nominatim_no_results +1 -0
  95. data/test/fixtures/ovi_madison_square_garden +72 -0
  96. data/test/fixtures/ovi_no_results +8 -0
  97. data/test/fixtures/yahoo_error +1 -0
  98. data/test/fixtures/yahoo_invalid_key +2 -0
  99. data/test/fixtures/yahoo_madison_square_garden +52 -0
  100. data/test/fixtures/yahoo_no_results +10 -0
  101. data/test/fixtures/yahoo_over_limit +2 -0
  102. data/test/fixtures/yandex_invalid_key +1 -0
  103. data/test/fixtures/yandex_kremlin +48 -0
  104. data/test/fixtures/yandex_no_city_and_town +112 -0
  105. data/test/fixtures/yandex_no_results +16 -0
  106. data/test/geocoder_test.rb +59 -0
  107. data/test/https_test.rb +16 -0
  108. data/test/integration/smoke_test.rb +26 -0
  109. data/test/lookup_test.rb +116 -0
  110. data/test/method_aliases_test.rb +25 -0
  111. data/test/mongoid_test.rb +39 -0
  112. data/test/mongoid_test_helper.rb +43 -0
  113. data/test/near_test.rb +43 -0
  114. data/test/oauth_util_test.rb +30 -0
  115. data/test/proxy_test.rb +23 -0
  116. data/test/query_test.rb +51 -0
  117. data/test/request_test.rb +29 -0
  118. data/test/result_test.rb +42 -0
  119. data/test/services_test.rb +277 -0
  120. data/test/test_helper.rb +279 -0
  121. data/test/test_mode_test.rb +50 -0
  122. metadata +170 -0
data/.gitignore ADDED
@@ -0,0 +1,5 @@
1
+ pkg/*
2
+ rdoc/*
3
+ *.gem
4
+ .bundle
5
+ Gemfile.lock
data/.travis.yml ADDED
@@ -0,0 +1,23 @@
1
+ rvm:
2
+ - 1.8.7
3
+ - 1.9.2
4
+ - 1.9.3
5
+ - jruby-19mode
6
+ gemfile:
7
+ - Gemfile
8
+ - gemfiles/Gemfile.mongoid-2.4.x
9
+ env: SSL_CERT_DIR=/etc/ssl/certs
10
+ matrix:
11
+ exclude:
12
+ - rvm: 1.8.7
13
+ gemfile: Gemfile
14
+ env: SSL_CERT_DIR=/etc/ssl/certs
15
+ - rvm: 1.9.2
16
+ gemfile: Gemfile
17
+ env: SSL_CERT_DIR=/etc/ssl/certs
18
+ - rvm: 1.9.3
19
+ gemfile: gemfiles/Gemfile.mongoid-2.4.x
20
+ env: SSL_CERT_DIR=/etc/ssl/certs
21
+ - rvm: jruby-19mode
22
+ gemfile: gemfiles/Gemfile.mongoid-2.4.x
23
+ env: SSL_CERT_DIR=/etc/ssl/certs
data/CHANGELOG.md ADDED
@@ -0,0 +1,298 @@
1
+ Changelog
2
+ =========
3
+
4
+ Per-release changes to Geocoder.
5
+
6
+ 1.1.6 (2012 Dec 24)
7
+ -------------------
8
+
9
+ * Major changes to configuration syntax which allow for API-specific config options. Old config syntax is now DEPRECATED.
10
+ * Add support for MaxMind API (thanks github.com/gonzoyumo).
11
+ * Add optional Geocoder::InvalidApiKey exception for bad API credentials (Yahoo, Yandex, Bing, and Maxmind). Warn when bad key and exception not set in Geocoder.configure(:always_raise => [...]).
12
+ * Add support for X-Real-IP and X-Forwarded-For headers (thanks github.com/konsti).
13
+ * Add support for custom Nominatim host config: Geocoder.configure(:nominatim => {:host => "..."}).
14
+ * Raise exception when required API key is missing or incorrect format.
15
+ * Add support for Google's :region and :components parameters (thanks to github.com/tomlion).
16
+ * Fix: string escaping bug in OAuth lib (thanks github.com/m0thman).
17
+ * Fix: configured units were not always respected in SQL queries.
18
+ * Fix: in #nearbys, don't try to exclude self if not yet persisted.
19
+ * Fix: bug with cache stores that provided #delete but not #del.
20
+ * Change #nearbys so that it returns nil instead of [] when object is not geocoded.
21
+
22
+ 1.1.5 (2012 Nov 9)
23
+ ------------------
24
+
25
+ * Replace support for old Yahoo Placefinder with Yahoo BOSS (thanks github.com/pwoltman).
26
+ * Add support for actual Mapquest API (was previously just a proxy for Nominatim), including the paid service (thanks github.com/jedschneider).
27
+ * Add support for :select => :id_only option to near scope.
28
+ * Treat a given query as blank (don't do a lookup) if coordinates are given but latitude or longitude is nil.
29
+ * Speed up 'near' queries by adding bounding box condition (thanks github.com/mlandauer).
30
+ * Fix: don't redefine Object#hash in Yahoo result object (thanks github.com/m0thman).
31
+
32
+ 1.1.4 (2012 Oct 2)
33
+ ------------------
34
+
35
+ * Deprecate Geocoder::Result::Nominatim#class and #type methods. Use #place_class and #place_type instead.
36
+ * Add support for setting arbitrary parameters in geocoding request URL.
37
+ * Add support for Google's :bounds parameter (thanks to github.com/rosscooperman and github.com/peterjm for submitting suggestions).
38
+ * Add support for :select => :geo_only option to near scope (thanks github.com/gugl).
39
+ * Add ability to omit ORDER BY clause from .near scope (pass option :order => false).
40
+ * Fix: error on Yahoo lookup due to API change (thanks github.com/kynesun).
41
+ * Fix: problem with Mongoid field aliases not being respected.
42
+ * Fix: :exclude option to .near scope when primary key != :id (thanks github.com/smisml).
43
+ * Much code refactoring (added Geocoder::Query class and Geocoder::Sql module).
44
+
45
+ 1.1.3 (2012 Aug 26)
46
+ -------------------
47
+
48
+ * Add support for Mapquest geocoding service (thanks github.com/razorinc).
49
+ * Add :test lookup for easy testing of apps using Geocoder (thanks github.com/mguterl).
50
+ * Add #precision method to Yandex results (thanks github.com/gemaker).
51
+ * Add support for raising :all exceptions (thanks github.com/andyvb).
52
+ * Add exceptions for certain Google geocoder responses (thanks github.com/andyvb).
53
+ * Add Travis-CI integration (thanks github.com/petergoldstein).
54
+ * Fix: unit config was not working with SQLite (thanks github.com/balvig).
55
+ * Fix: get tests to pass under Jruby (thanks github.com/petergoldstein).
56
+ * Fix: bug in distance_from_sql method (error occurred when coordinates not found).
57
+ * Fix: incompatibility with Mongoid 3.0.x (thanks github.com/petergoldstein).
58
+
59
+ 1.1.2 (2012 May 24)
60
+ -------------------
61
+
62
+ * Add ability to specify default units and distance calculation method (thanks github.com/abravalheri).
63
+ * Add new (optional) configuration syntax (thanks github.com/abravalheri).
64
+ * Add support for cache stores that provide :get and :set methods.
65
+ * Add support for custom HTTP request headers (thanks github.com/robotmay).
66
+ * Add Result#cache_hit attribute (thanks github.com/s01ipsist).
67
+ * Fix: rake geocode:all wasn't properly loading namespaced classes.
68
+ * Fix: properly recognize IP addresses with ::ffff: prefix (thanks github.com/brian-ewell).
69
+ * Fix: avoid exception during calculations when coordinates not known (thanks github.com/flori).
70
+
71
+ 1.1.1 (2012 Feb 16)
72
+ -------------------
73
+
74
+ * Add distance_from_sql class method to geocoded class (thanks github.com/dwilkie).
75
+ * Add OverQueryLimitError and raise when relevant for Google lookup.
76
+ * Fix: don't cache API data if response indicates an error.
77
+ * Fix: within_bounding_box now uses correct lat/lon DB columns (thanks github.com/kongo).
78
+ * Fix: error accessing city in some cases with Yandex result (thanks github.com/kor6n and sld).
79
+
80
+ 1.1.0 (2011 Dec 3)
81
+ ------------------
82
+
83
+ * A block passed to geocoded_by is now always executed, even if the geocoding service returns no results. This means you need to make sure you have results before trying to assign data to your object.
84
+ * Fix issues with joins and row counts (issues #49, 86, and 108) by not using GROUP BY clause with ActiveRecord scopes.
85
+ * Fix incorrect object ID when join used (fixes issue #140).
86
+ * Fix calculation of bounding box which spans 180th meridian (thanks github.com/hwuethrich).
87
+ * Add within_bounding_box scope for ActiveRecord-based models (thanks github.com/gavinhughes and dbloete).
88
+ * Add option to raise Geocoder::OverQueryLimitError for Google geocoding service.
89
+ * Add support for Nominatim geocoding service (thanks github.com/wranglerdriver).
90
+ * Add support for API key to Geocoder.ca geocoding service (thanks github.com/ryanLonac).
91
+ * Add support for state to Yandex results (thanks github.com/tipugin).
92
+
93
+ 1.0.5 (2011 Oct 26)
94
+ -------------------
95
+
96
+ * Fix error with `rake assets:precompile` (thanks github.com/Sush).
97
+ * Fix HTTPS support (thanks github.com/rsanheim).
98
+ * Improve cache interface.
99
+
100
+ 1.0.4 (2011 Sep 18)
101
+ -------------------
102
+
103
+ * Remove klass method from rake task, which could conflict with app methods (thanks github.com/mguterl).
104
+
105
+ 1.0.3 (2011 Sep 17)
106
+ -------------------
107
+
108
+ * Add support for Google Premier geocoding service (thanks github.com/steveh).
109
+ * Update Google API URL (thanks github.com/soorajb).
110
+ * Allow rescue from timeout with FreeGeoIP (thanks github.com/lukeledet).
111
+ * Fix: rake assets:precompile (Rails 3.1) not working in some situations.
112
+ * Fix: stop double-adjusting units when using kilometers (thanks github.com/hairyheron).
113
+
114
+ 1.0.2 (2011 June 25)
115
+ --------------------
116
+
117
+ * Add support for MongoMapper (thanks github.com/spagalloco).
118
+ * Fix: user-specified coordinates field wasn't working with Mongoid (thanks github.com/thisduck).
119
+ * Fix: invalid location given to near scope was returning all results (Active Record) or error (Mongoid) (thanks github.com/ogennadi).
120
+
121
+ 1.0.1 (2011 May 17)
122
+ -------------------
123
+
124
+ * Add option to not rescue from certain exceptions (thanks github.com/ahmedrb).
125
+ * Fix STI child/parent geocoding bug (thanks github.com/ogennadi).
126
+ * Other bugfixes.
127
+
128
+ 1.0.0 (2011 May 9)
129
+ ------------------
130
+
131
+ * Add command line interface.
132
+ * Add support for local proxy (thanks github.com/Olivier).
133
+ * Add support for Yandex.ru geocoding service.
134
+ * Add support for Bing geocoding service (thanks github.com/astevens).
135
+ * Fix single table inheritance bug (reported by github.com/enrico).
136
+ * Fix bug when Google result supplies no city (thanks github.com/jkeen).
137
+
138
+ 0.9.13 (2011 Apr 11)
139
+ --------------------
140
+
141
+ * Fix "can't find special index: 2d" error when using Mongoid with Ruby 1.8.
142
+
143
+ 0.9.12 (2011 Apr 6)
144
+ -------------------
145
+
146
+ * Add support for Mongoid.
147
+ * Add bearing_to/from methods to geocoded objects.
148
+ * Improve SQLite's distance calculation heuristic.
149
+ * Fix: Geocoder::Calculations.geographic_center was modifying its argument in-place (reported by github.com/joelmats).
150
+ * Fix: sort 'near' query results by distance when using SQLite.
151
+ * Clean up input: search for coordinates as a string with space after comma yields zero results from Google. Now we get rid of any such space before sending the query.
152
+ * DEPRECATION: Geocoder.near should not take <tt>:limit</tt> or <tt>:offset</tt> options.
153
+ * DEPRECATION: Change argument format of all methods that take lat/lon as separate arguments. Now you must pass the coordinates as an array [lat,lon], but you may alternatively pass a address string (will look up coordinates) or a geocoded object (or any object that implements a to_coordinates method which returns a [lat,lon] array).
154
+
155
+ 0.9.11 (2011 Mar 25)
156
+ --------------------
157
+
158
+ * Add support for result caching.
159
+ * Add support for Geocoder.ca geocoding service.
160
+ * Add +bearing+ attribute to objects returned by geo-aware queries (thanks github.com/matellis).
161
+ * Add config setting: language.
162
+ * Add config settings: +use_https+, +google_api_key+ (thanks github.com/svesely).
163
+ * DEPRECATION: <tt>Geocoder.search</tt> now returns an array instead of a single result.
164
+ * DEPRECATION: <tt>obj.nearbys</tt> second argument is now an options hash (instead of units). Please change <tt>obj.nearbys(20, :km)</tt> to: <tt>obj.nearbys(20, :units => :km)</tt>.
165
+
166
+ 0.9.10 (2011 Mar 9)
167
+ -------------------
168
+
169
+ * Fix broken scopes (github.com/mikepinde).
170
+ * Fix broken Ruby 1.9 and JRuby compatibility (don't require json gem).
171
+
172
+ 0.9.9 (2011 Mar 9)
173
+ ------------------
174
+
175
+ * Add support for IP address geocoding via FreeGeoIp.net.
176
+ * Add support for Yahoo PlaceFinder geocoding API.
177
+ * Add support for custom geocoder data handling by passing a block to geocoded_by or reverse_geocoded_by.
178
+ * Add <tt>Rack::Request#location</tt> method for geocoding user's IP address.
179
+ * Change gem name to geocoder (no more rails-geocoder).
180
+ * Gem now works outside of Rails.
181
+ * DEPRECATION: +fetch_coordinates+ no longer takes an argument.
182
+ * DEPRECATION: +fetch_address+ no longer takes an argument.
183
+ * DEPRECATION: <tt>Geocoder.search</tt> now returns a single result instead of an array.
184
+ * DEPRECATION: <tt>fetch_coordinates!</tt> has been superceded by +geocode+ (then save your object manually).
185
+ * DEPRECATION: <tt>fetch_address!</tt> has been superceded by +reverse_geocode+ (then save your object manually).
186
+ * Fix: don't die when trying to get coordinates with a nil address (github.com/zmack).
187
+
188
+ 0.9.8 (2011 Feb 8)
189
+ ------------------
190
+
191
+ * Include <tt>geocode:all</tt> Rake task in gem (was missing!).
192
+ * Add <tt>Geocoder.search</tt> for access to Google's full response.
193
+ * Add ability to configure Google connection timeout.
194
+ * Emit warnings on Google connection problems and errors.
195
+ * Refactor: insert Geocoder into ActiveRecord via Railtie.
196
+
197
+ 0.9.7 (2011 Feb 1)
198
+ ------------------
199
+
200
+ * Add reverse geocoding (+reverse_geocoded_by+).
201
+ * Prevent exception (uninitialized constant Geocoder::Net) when net/http not already required (github.com/sleepycat).
202
+ * Refactor: split monolithic Geocoder module into several smaller ones.
203
+
204
+ 0.9.6 (2011 Jan 19)
205
+ -------------------
206
+
207
+ * Fix incompatibility with will_paginate gem.
208
+ * Include table names in GROUP BY clause of nearby scope to avoid ambiguity in joins (github.com/matchu).
209
+
210
+ 0.9.5 (2010 Oct 15)
211
+ -------------------
212
+
213
+ * Fix broken PostgreSQL compatibility (now 100% compatible).
214
+ * Switch from Google's XML to JSON geocoding API.
215
+ * Separate Rails 2 and Rails 3-compatible branches.
216
+ * Don't allow :conditions hash in 'options' argument to 'nearbys' method (was deprecated in 0.9.3).
217
+
218
+ 0.9.4 (2010 Aug 2)
219
+ ------------------
220
+
221
+ * Google Maps API key no longer required (uses geocoder v3).
222
+
223
+ 0.9.3 (2010 Aug 2)
224
+ ------------------
225
+
226
+ * Fix incompatibility with Rails 3 RC 1.
227
+ * Deprecate 'options' argument to 'nearbys' method.
228
+ * Allow inclusion of 'nearbys' in Arel method chains.
229
+
230
+ 0.9.2 (2010 Jun 3)
231
+ ------------------
232
+
233
+ * Fix LIMIT clause bug in PostgreSQL (reported by github.com/kenzie).
234
+
235
+ 0.9.1 (2010 May 4)
236
+ ------------------
237
+
238
+ * Use scope instead of named_scope in Rails 3.
239
+
240
+ 0.9.0 (2010 Apr 2)
241
+ ------------------
242
+
243
+ * Fix bug in PostgreSQL support (caused "PGError: ERROR: column "distance" does not exist"), reported by github.com/developish.
244
+
245
+ 0.8.9 (2010 Feb 11)
246
+ -------------------
247
+
248
+ * Add Rails 3 compatibility.
249
+ * Avoid querying Google when query would be an empty string.
250
+
251
+ 0.8.8 (2009 Dec 7)
252
+ ------------------
253
+
254
+ * Automatically select a less accurate but compatible distance algorithm when SQLite database detected (fixes SQLite incompatibility).
255
+
256
+ 0.8.7 (2009 Nov 4)
257
+ ------------------
258
+
259
+ * Added Geocoder.geographic_center method.
260
+ * Replaced _get_coordinates class method with read_coordinates instance method.
261
+
262
+ 0.8.6 (2009 Oct 27)
263
+ -------------------
264
+
265
+ * The fetch_coordinates method now assigns coordinates to attributes (behaves like fetch_coordinates! used to) and fetch_coordinates! both assigns and saves the attributes.
266
+ * Added geocode:all rake task.
267
+
268
+ 0.8.5 (2009 Oct 26)
269
+ -------------------
270
+
271
+ * Avoid calling deprecated method from within Geocoder itself.
272
+
273
+ 0.8.4 (2009 Oct 23)
274
+ -------------------
275
+
276
+ * Deprecate <tt>find_near</tt> class method in favor of +near+ named scope.
277
+
278
+ 0.8.3 (2009 Oct 23)
279
+ -------------------
280
+
281
+ * Update Google URL query string parameter to reflect recent changes in Google's API.
282
+
283
+ 0.8.2 (2009 Oct 12)
284
+ -------------------
285
+
286
+ * Allow a model's geocoder search string method to be something other than an ActiveRecord attribute.
287
+ * Clean up documentation.
288
+
289
+ 0.8.1 (2009 Oct 8)
290
+ ------------------
291
+
292
+ * Extract XML-fetching code from <tt>Geocoder.search</tt> and place in Geocoder._fetch_xml (for ease of mocking).
293
+ * Add tests for coordinate-fetching instance methods.
294
+
295
+ 0.8.0 (2009 Oct 1)
296
+ ------------------
297
+
298
+ First release.
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009-11 Alex Reisner
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,656 @@
1
+ Geocoder
2
+ ========
3
+
4
+ Geocoder is a complete geocoding solution for Ruby. With Rails it adds geocoding (by street or IP address), reverse geocoding (find street address based on given coordinates), and distance queries. It's as simple as calling `geocode` on your objects, and then using a scope like `Venue.near("Billings, MT")`.
5
+
6
+
7
+ Compatibility
8
+ -------------
9
+
10
+ * Supports multiple Ruby versions: Ruby 1.8.7, 1.9.2, 1.9.3, and JRuby.
11
+ * Supports multiple databases: MySQL, PostgreSQL, SQLite, and MongoDB (1.7.0 and higher).
12
+ * Supports Rails 3.x. If you need to use it with Rails 2 please see the `rails2` branch (no longer maintained, limited feature set).
13
+ * Works very well outside of Rails, you just need to install either the `json` (for MRI) or `json_pure` (for JRuby) gem.
14
+
15
+
16
+ Installation
17
+ ------------
18
+
19
+ Install Geocoder like any other Ruby gem:
20
+
21
+ gem install geocoder
22
+
23
+ Or, if you're using Rails/Bundler, add this to your Gemfile:
24
+
25
+ gem "geocoder"
26
+
27
+ and run at the command prompt:
28
+
29
+ bundle install
30
+
31
+
32
+ Object Geocoding
33
+ ----------------
34
+
35
+ ### ActiveRecord
36
+
37
+ Your model must have two attributes (database columns) for storing latitude and longitude coordinates. By default they should be called `latitude` and `longitude` but this can be changed (see "Model Configuration" below):
38
+
39
+ rails generate migration AddLatitudeAndLongitudeToModel latitude:float longitude:float
40
+ rake db:migrate
41
+
42
+ For reverse geocoding your model must provide a method that returns an address. This can be a single attribute, but it can also be a method that returns a string assembled from different attributes (eg: `city`, `state`, and `country`).
43
+
44
+ Next, your model must tell Geocoder which method returns your object's geocodable address:
45
+
46
+ geocoded_by :full_street_address # can also be an IP address
47
+ after_validation :geocode # auto-fetch coordinates
48
+
49
+ For reverse geocoding, tell Geocoder which attributes store latitude and longitude:
50
+
51
+ reverse_geocoded_by :latitude, :longitude
52
+ after_validation :reverse_geocode # auto-fetch address
53
+
54
+ ### Mongoid
55
+
56
+ First, your model must have an array field for storing coordinates:
57
+
58
+ field :coordinates, :type => Array
59
+
60
+ You may also want an address field, like this:
61
+
62
+ field :address
63
+
64
+ but if you store address components (city, state, country, etc) in separate fields you can instead define a method called `address` that combines them into a single string which will be used to query the geocoding service.
65
+
66
+ Once your fields are defined, include the `Geocoder::Model::Mongoid` module and then call `geocoded_by`:
67
+
68
+ include Geocoder::Model::Mongoid
69
+ geocoded_by :address # can also be an IP address
70
+ after_validation :geocode # auto-fetch coordinates
71
+
72
+ Reverse geocoding is similar:
73
+
74
+ include Geocoder::Model::Mongoid
75
+ reverse_geocoded_by :coordinates
76
+ after_validation :reverse_geocode # auto-fetch address
77
+
78
+ Once you've set up your model you'll need to create the necessary spatial indices in your database:
79
+
80
+ rake db:mongoid:create_indexes
81
+
82
+ Be sure to read _Latitude/Longitude Order_ in the _Notes on MongoDB_ section below on how to properly retrieve latitude/longitude coordinates from your objects.
83
+
84
+ ### MongoMapper
85
+
86
+ MongoMapper is very similar to Mongoid, just be sure to include `Geocoder::Model::MongoMapper`.
87
+
88
+ ### Mongo Indices
89
+
90
+ By default, the methods `geocoded_by` and `reverse_geocoded_by` create a geospatial index. You can avoid index creation with the `:skip_index option`, for example:
91
+
92
+ include Geocoder::Model::Mongoid
93
+ geocoded_by :address, :skip_index => true
94
+
95
+ ### Bulk Geocoding
96
+
97
+ If you have just added geocoding to an existing application with a lot of objects you can use this Rake task to geocode them all:
98
+
99
+ rake geocode:all CLASS=YourModel
100
+
101
+ Geocoder will print warnings if you exceed the rate limit for your geocoding service.
102
+
103
+
104
+ Request Geocoding by IP Address
105
+ -------------------------------
106
+
107
+ Geocoder adds a `location` method to the standard `Rack::Request` object so you can easily look up the location of any HTTP request by IP address. For example, in a Rails controller or a Sinatra app:
108
+
109
+ # returns Geocoder::Result object
110
+ result = request.location
111
+
112
+ See _Advanced Geocoding_ below for more information about `Geocoder::Result` objects.
113
+
114
+
115
+ Location-Aware Database Queries
116
+ -------------------------------
117
+
118
+ To find objects by location, use the following scopes:
119
+
120
+ Venue.near('Omaha, NE, US', 20) # venues within 20 miles of Omaha
121
+ Venue.near([40.71, 100.23], 20) # venues within 20 miles of a point
122
+ Venue.geocoded # venues with coordinates
123
+ Venue.not_geocoded # venues without coordinates
124
+
125
+ With geocoded objects you can do things like this:
126
+
127
+ if obj.geocoded?
128
+ obj.nearbys(30) # other objects within 30 miles
129
+ obj.distance_from([40.714,-100.234]) # distance from arbitrary point to object
130
+ obj.bearing_to("Paris, France") # direction from object to arbitrary point
131
+ end
132
+
133
+ Some utility methods are also available:
134
+
135
+ # look up coordinates of some location (like searching Google Maps)
136
+ Geocoder.coordinates("25 Main St, Cooperstown, NY")
137
+ => [42.700149, -74.922767]
138
+
139
+ # distance (in miles) between Eiffel Tower and Empire State Building
140
+ Geocoder::Calculations.distance_between([47.858205,2.294359], [40.748433,-73.985655])
141
+ => 3619.77359999382
142
+
143
+ # find the geographic center (aka center of gravity) of objects or points
144
+ Geocoder::Calculations.geographic_center([city1, city2, [40.22,-73.99], city4])
145
+ => [35.14968, -90.048929]
146
+
147
+ Please see the code for more methods and detailed information about arguments (eg, working with kilometers).
148
+
149
+
150
+ Distance and Bearing
151
+ --------------------
152
+
153
+ When you run a location-aware query the returned objects have two attributes added to them (only w/ ActiveRecord):
154
+
155
+ * `obj.distance` - number of miles from the search point to this object
156
+ * `obj.bearing` - direction from the search point to this object
157
+
158
+ Results are automatically sorted by distance from the search point, closest to farthest. Bearing is given as a number of clockwise degrees from due north, for example:
159
+
160
+ * `0` - due north
161
+ * `180` - due south
162
+ * `90` - due east
163
+ * `270` - due west
164
+ * `230.1` - southwest
165
+ * `359.9` - almost due north
166
+
167
+ You can convert these numbers to compass point names by using the utility method provided:
168
+
169
+ Geocoder::Calculations.compass_point(355) # => "N"
170
+ Geocoder::Calculations.compass_point(45) # => "NE"
171
+ Geocoder::Calculations.compass_point(208) # => "SW"
172
+
173
+ _Note: when using SQLite `distance` and `bearing` values are provided for interface consistency only. They are not very accurate._
174
+
175
+ To calculate accurate distance and bearing with SQLite or MongoDB:
176
+
177
+ obj.distance_to([43.9,-98.6]) # distance from obj to point
178
+ obj.bearing_to([43.9,-98.6]) # bearing from obj to point
179
+ obj.bearing_from(obj2) # bearing from obj2 to obj
180
+
181
+ The `bearing_from/to` methods take a single argument which can be: a `[lat,lon]` array, a geocoded object, or a geocodable address (string). The `distance_from/to` methods also take a units argument (`:mi` or `:km`).
182
+
183
+
184
+ Model Configuration
185
+ -------------------
186
+
187
+ You are not stuck with using the `latitude` and `longitude` database column names (with ActiveRecord) or the `coordinates` array (Mongo) for storing coordinates. For example:
188
+
189
+ geocoded_by :address, :latitude => :lat, :longitude => :lon # ActiveRecord
190
+ geocoded_by :address, :coordinates => :coords # MongoDB
191
+
192
+ The `address` method can return any string you'd use to search Google Maps. For example, any of the following are acceptable:
193
+
194
+ * "714 Green St, Big Town, MO"
195
+ * "Eiffel Tower, Paris, FR"
196
+ * "Paris, TX, US"
197
+
198
+ If your model has `street`, `city`, `state`, and `country` attributes you might do something like this:
199
+
200
+ geocoded_by :address
201
+
202
+ def address
203
+ [street, city, state, country].compact.join(', ')
204
+ end
205
+
206
+ For reverse geocoding you can also specify an alternate name attribute where the address will be stored, for example:
207
+
208
+ reverse_geocoded_by :latitude, :longitude, :address => :location # ActiveRecord
209
+ reverse_geocoded_by :coordinates, :address => :loc # MongoDB
210
+
211
+
212
+ Advanced Querying
213
+ -----------------
214
+
215
+ When querying for objects (if you're using ActiveRecord) you can also look within a square rather than a radius (circle) by using the `within_bounding_box` scope:
216
+
217
+ distance = 20
218
+ center_point = [40.71, 100.23]
219
+ box = Geocoder::Calculations.bounding_box(center_point, distance)
220
+ Venue.within_bounding_box(box)
221
+
222
+ This can also dramatically improve query performance, especially when used in conjunction with indexes on the latitude/longitude columns. Note, however, that returned results do not include `distance` and `bearing` attributes. If you want to improve performance AND have access to distance and bearing info, use both scopes:
223
+
224
+ Venue.near(center_point, distance).within_bounding_box(box)
225
+
226
+
227
+ Advanced Geocoding
228
+ ------------------
229
+
230
+ So far we have looked at shortcuts for assigning geocoding results to object attributes. However, if you need to do something fancy you can skip the auto-assignment by providing a block (takes the object to be geocoded and an array of `Geocoder::Result` objects) in which you handle the parsed geocoding result any way you like, for example:
231
+
232
+ reverse_geocoded_by :latitude, :longitude do |obj,results|
233
+ if geo = results.first
234
+ obj.city = geo.city
235
+ obj.zipcode = geo.postal_code
236
+ obj.country = geo.country_code
237
+ end
238
+ end
239
+ after_validation :reverse_geocode
240
+
241
+ Every `Geocoder::Result` object, `result`, provides the following data:
242
+
243
+ * `result.latitude` - float
244
+ * `result.longitude` - float
245
+ * `result.coordinates` - array of the above two
246
+ * `result.address` - string
247
+ * `result.city` - string
248
+ * `result.state` - string
249
+ * `result.state_code` - string
250
+ * `result.postal_code` - string
251
+ * `result.country` - string
252
+ * `result.country_code` - string
253
+
254
+ If you're familiar with the results returned by the geocoding service you're using you can access even more data, but you'll need to be familiar with the particular `Geocoder::Result` object you're using and the structure of your geocoding service's responses. (See below for links to geocoding service documentation.)
255
+
256
+
257
+ Geocoding Services
258
+ ------------------
259
+
260
+ By default Geocoder uses Google's geocoding API to fetch coordinates and street addresses (FreeGeoIP is the default for IP address info). However there are several other APIs supported, as well as a variety of settings. Please see the listing and comparison below for details on specific geocoding services (not all settings are supported by all services). Some common configuration options are:
261
+
262
+ # config/initializers/geocoder.rb
263
+ Geocoder.configure(
264
+
265
+ # geocoding service (see below for supported options):
266
+ :lookup => :yandex,
267
+
268
+ # to use an API key:
269
+ :api_key => "...",
270
+
271
+ # geocoding service request timeout, in seconds (default 3):
272
+ :timeout => 5,
273
+
274
+ # set default units to kilometers:
275
+ :units => :km,
276
+
277
+ # caching (see below for details):
278
+ :cache => Redis.new,
279
+ :cache_prefix => "..."
280
+
281
+ )
282
+
283
+ Please see lib/geocoder/configuration.rb for a complete list of configuration options. Additionally, some lookups have their own configuration options, some of which are directly supported by Geocoder. For example, to specify a value for Google's `bounds` parameter:
284
+
285
+ # with Google:
286
+ Geocoder.search("Paris", :bounds => [[32.1,-95.9], [33.9,-94.3]])
287
+
288
+ Please see the [source code for each lookup](https://github.com/alexreisner/geocoder/tree/master/lib/geocoder/lookups) to learn about directly supported parameters. Parameters which are not directly supported can be specified using the `:params` option, by which you can pass arbitrary parameters to any geocoding service. For example, to use Nominatim's `countrycodes` parameter:
289
+
290
+ # with Nominatim:
291
+ Geocoder.search("Paris", :params => {:countrycodes => "gb,de,fr,es,us"})
292
+
293
+
294
+ ### Listing and Comparison
295
+
296
+ The following is a comparison of the supported geocoding APIs. The "Limitations" listed for each are a very brief and incomplete summary of some special limitations beyond basic data source attribution. Please read the official Terms of Service for a service before using it.
297
+
298
+ #### Google (`:google`, `:google_premier`)
299
+
300
+ * **API key**: required for Premier (do NOT use a key for the free version)
301
+ * **Key signup**: http://code.google.com/apis/maps/signup.html
302
+ * **Quota**: 2,500 requests/day, 100,000 with Google Maps API Premier
303
+ * **Region**: world
304
+ * **SSL support**: yes
305
+ * **Languages**: ar, eu, bg, bn, ca, cs, da, de, el, en, en-AU, en-GB, es, eu, fa, fi, fil, fr, gl, gu, hi, hr, hu, id, it, iw, ja, kn, ko, lt, lv, ml, mr, nl, no, pl, pt, pt-BR, pt-PT, ro, ru, sk, sl, sr, sv, tl, ta, te, th, tr, uk, vi, zh-CN, zh-TW (see http://spreadsheets.google.com/pub?key=p9pdwsai2hDMsLkXsoM05KQ&gid=1)
306
+ * **Extra options**: `:bounds` - pass SW and NE coordinates as an array of two arrays to bias results towards a viewport
307
+ * **Documentation**: http://code.google.com/apis/maps/documentation/geocoding/#JSON
308
+ * **Terms of Service**: http://code.google.com/apis/maps/terms.html#section_10_12
309
+ * **Limitations**: "You must not use or display the Content without a corresponding Google map, unless you are explicitly permitted to do so in the Maps APIs Documentation, or through written permission from Google." "You must not pre-fetch, cache, or store any Content, except that you may store: (i) limited amounts of Content for the purpose of improving the performance of your Maps API Implementation..."
310
+ * **Notes**: To use Google Premier set `Geocoder.configure(:lookup => :google_premier, :api_key => [key, client, channel])`.
311
+
312
+ #### Yahoo BOSS (`:yahoo`)
313
+
314
+ Yahoo BOSS is **not a free service**. As of November 17, 2012 Yahoo no longer offers a free geocoding API.
315
+
316
+ * **API key**: requires OAuth consumer key and secret (set `Geocoder.configure(:api_key => [key, secret])`)
317
+ * **Key signup**: http://developer.yahoo.com/boss/geo/
318
+ * **Quota**: unlimited, but subject to usage fees
319
+ * **Region**: world
320
+ * **SSL support**: no
321
+ * **Languages**: en, fr, de, it, es, pt, nl, zh, ja, ko
322
+ * **Documentation**: http://developer.yahoo.com/boss/geo/docs/index.html
323
+ * **Terms of Service**: http://info.yahoo.com/legal/us/yahoo/boss/tou/?pir=ucJPcJ1ibUn.h.d.lVmlcbcEkoHjwJ_PvxG9SLK9VIbIQAw1XFrnDqY-
324
+ * **Limitations**: No mass downloads, no commercial map production based on the data, no storage of data except for caching.
325
+
326
+ #### Bing (`:bing`)
327
+
328
+ * **API key**: required
329
+ * **Key signup**: http://www.bingmapsportal.com
330
+ * **Quota**: 50,000 requests/24 hrs
331
+ * **Region**: world
332
+ * **SSL support**: no
333
+ * **Languages**: ?
334
+ * **Documentation**: http://msdn.microsoft.com/en-us/library/ff701715.aspx
335
+ * **Terms of Service**: http://www.microsoft.com/maps/product/terms.html
336
+ * **Limitations**: No country codes or state names. Must be used on "public-facing, non-password protected web sites," "in conjunction with Bing Maps or an application that integrates Bing Maps."
337
+
338
+ #### Nominatim (`:nominatim`)
339
+
340
+ * **API key**: none
341
+ * **Quota**: 1 request/second
342
+ * **Region**: world
343
+ * **SSL support**: no
344
+ * **Languages**: ?
345
+ * **Documentation**: http://wiki.openstreetmap.org/wiki/Nominatim
346
+ * **Terms of Service**: http://wiki.openstreetmap.org/wiki/Nominatim_usage_policy
347
+ * **Limitations**: Please limit request rate to 1 per second and include your contact information in User-Agent headers. Data licensed under CC-BY-SA (you must provide attribution).
348
+
349
+ #### Yandex (`:yandex`)
350
+
351
+ * **API key**: none
352
+ * **Quota**: 25000 requests / day
353
+ * **Region**: world
354
+ * **SSL support**: no
355
+ * **Languages**: Russian, Belarusian, Ukrainian, English, Turkish (only for maps of Turkey)
356
+ * **Documentation**: http://api.yandex.com.tr/maps/doc/intro/concepts/intro.xml
357
+ * **Terms of Service**: http://api.yandex.com.tr/maps/doc/intro/concepts/intro.xml#rules
358
+ * **Limitations**: ?
359
+
360
+ #### Geocoder.ca (`:geocoder_ca`)
361
+
362
+ * **API key**: none
363
+ * **Quota**: ?
364
+ * **Region**: US and Canada
365
+ * **SSL support**: no
366
+ * **Languages**: English
367
+ * **Documentation**: ?
368
+ * **Terms of Service**: http://geocoder.ca/?terms=1
369
+ * **Limitations**: "Under no circumstances can our data be re-distributed or re-sold by anyone to other parties without our written permission."
370
+
371
+ #### Mapquest (`:mapquest`)
372
+
373
+ * **API key**: required for the licensed API, do not use for open tier
374
+ * **Quota**: ?
375
+ * **HTTP Headers**: in order to use the licensed API you can configure the http_headers to include a referer as so:
376
+ `Geocoder.configure(:http_headers => { "Referer" => "http://foo.com" })`
377
+ You can also allow a blank referer from the API management console via mapquest but it is potentially a security risk that someone else could use your API key from another domain.
378
+ * **Region**: world
379
+ * **SSL support**: no
380
+ * **Languages**: English
381
+ * **Documentation**: http://www.mapquestapi.com/geocoding/
382
+ * **Terms of Service**: http://info.mapquest.com/terms-of-use/
383
+ * **Limitations**: ?
384
+
385
+ #### Ovi/Nokia (`:ovi`)
386
+
387
+ * **API key**: not required, but performance restricted without it
388
+ * **Quota**: ?
389
+ * **Region**: world
390
+ * **SSL support**: no
391
+ * **Languages**: English
392
+ * **Documentation**: http://api.maps.ovi.com/devguide/overview.html
393
+ * **Terms of Service**: http://www.developer.nokia.com/Develop/Maps/TC.html
394
+ * **Limitations**: ?
395
+
396
+ #### FreeGeoIP (`:freegeoip`)
397
+
398
+ * **API key**: none
399
+ * **Quota**: 1000 requests per hour. After reaching the hourly quota, all of your requests will result in HTTP 403 (Forbidden) until it clears up on the next roll over.
400
+ * **Region**: world
401
+ * **SSL support**: no
402
+ * **Languages**: English
403
+ * **Documentation**: http://github.com/fiorix/freegeoip/blob/master/README.rst
404
+ * **Terms of Service**: ?
405
+ * **Limitations**: ?
406
+
407
+ #### MaxMind Web Services (`:maxmind`)
408
+
409
+ * **API key**: required
410
+ * **Quota**: Request Packs can be purchased
411
+ * **Region**: world
412
+ * **SSL support**: yes
413
+ * **Languages**: English
414
+ * **Documentation**: http://www.maxmind.com/app/web_services
415
+ * **Terms of Service**: ?
416
+ * **Limitations**: ?
417
+
418
+
419
+ Caching
420
+ -------
421
+
422
+ It's a good idea, when relying on any external service, to cache retrieved data. When implemented correctly it improves your app's response time and stability. It's easy to cache geocoding results with Geocoder, just configure a cache store:
423
+
424
+ Geocoder.configure(:cache => Redis.new)
425
+
426
+ This example uses Redis, but the cache store can be any object that supports these methods:
427
+
428
+ * `store#[](key)` - retrieves a value
429
+ * `store#[]=(key, value)` - stores a value
430
+ * `store#keys` - lists all keys
431
+ * `store#del(url)` - deletes a value
432
+
433
+ Even a plain Ruby hash will work, though it's not a great choice (cleared out when app is restarted, not shared between app instances, etc).
434
+
435
+ You can also set a custom prefix to be used for cache keys:
436
+
437
+ Geocoder.configure(:cache_prefix => "...")
438
+
439
+ By default the prefix is `geocoder:`
440
+
441
+ If you need to expire cached content:
442
+
443
+ Geocoder.cache.expire("http://...") # expire cached result for a URL
444
+ Geocoder.cache.expire(:all) # expire all cached results
445
+
446
+ Do *not* include the prefix when passing a URL to be expired. Expiring `:all` will only expire keys with the configured prefix (won't kill every entry in your key/value store).
447
+
448
+ For an example of a cache store with URL expiry please see examples/autoexpire_cache.rb
449
+
450
+ _Before you implement caching in your app please be sure that doing so does not violate the Terms of Service for your geocoding service._
451
+
452
+
453
+ Forward and Reverse Geocoding in the Same Model
454
+ -----------------------------------------------
455
+
456
+ If you apply both forward and reverse geocoding functionality to the same model (say users can supply an address or coordinates and you want to fill in whatever's missing), you will provide two address methods:
457
+
458
+ * one for storing the fetched address (reverse geocoding)
459
+ * one for providing an address to use when fetching coordinates (forward geocoding)
460
+
461
+ For example:
462
+
463
+ class Venue
464
+
465
+ # build an address from street, city, and state attributes
466
+ geocoded_by :address_from_components
467
+
468
+ # store the fetched address in the full_address attribute
469
+ reverse_geocoded_by :latitude, :longitude, :address => :full_address
470
+ end
471
+
472
+ However, there can be only one set of latitude/longitude attributes, and whichever you specify last will be used. For example:
473
+
474
+ class Venue
475
+
476
+ geocoded_by :address,
477
+ :latitude => :fetched_latitude, # this will be overridden by the below
478
+ :longitude => :fetched_longitude # same here
479
+
480
+ reverse_geocoded_by :latitude, :longitude
481
+ end
482
+
483
+ The reason for this is that we don't want ambiguity when doing distance calculations. We need a single, authoritative source for coordinates!
484
+
485
+
486
+ Use Outside of Rails
487
+ --------------------
488
+
489
+ You can use Geocoder outside of Rails by calling the `Geocoder.search` method:
490
+
491
+ results = Geocoder.search("McCarren Park, Brooklyn, NY")
492
+
493
+ This returns an array of `Geocoder::Result` objects with all data provided by the geocoding service.
494
+
495
+
496
+ Testing Apps that Use Geocoder
497
+ ------------------------------
498
+
499
+ When writing tests for an app that uses Geocoder it may be useful to avoid network calls and have Geocoder return consistent, configurable results. To do this, configure and use the `:test` lookup. For example:
500
+
501
+ Geocoder.configure(:lookup => :test)
502
+
503
+ Geocoder::Lookup::Test.add_stub(
504
+ "New York, NY", [
505
+ {
506
+ 'latitude' => 40.7143528,
507
+ 'longitude' => -74.0059731,
508
+ 'address' => 'New York, NY, USA',
509
+ 'state' => 'New York',
510
+ 'state_code' => 'NY',
511
+ 'country' => 'United States',
512
+ 'country_code' => 'US'
513
+ }
514
+ ]
515
+ )
516
+
517
+ Now, any time Geocoder looks up "New York, NY" its results array will contain one result with the above attributes.
518
+
519
+
520
+ Command Line Interface
521
+ ----------------------
522
+
523
+ When you install the Geocoder gem it adds a `geocode` command to your shell. You can search for a street address, IP address, postal code, coordinates, etc just like you can with the Geocoder.search method for example:
524
+
525
+ $ geocode 29.951,-90.081
526
+ Latitude: 29.952211
527
+ Longitude: -90.080563
528
+ Full address: 1500 Sugar Bowl Dr, New Orleans, LA 70112, USA
529
+ City: New Orleans
530
+ State/province: Louisiana
531
+ Postal code: 70112
532
+ Country: United States
533
+ Google map: http://maps.google.com/maps?q=29.952211,-90.080563
534
+
535
+ There are also a number of options for setting the geocoding API, key, and language, viewing the raw JSON reponse, and more. Please run `geocode -h` for details.
536
+
537
+ Notes on MongoDB
538
+ ----------------
539
+
540
+ ### The Near Method
541
+
542
+ Mongo document classes (Mongoid and MongoMapper) have a built-in `near` scope, but since it only works two-dimensions Geocoder overrides it with its own spherical `near` method in geocoded classes.
543
+
544
+ ### Latitude/Longitude Order
545
+
546
+ Coordinates are generally printed and spoken as latitude, then longitude ([lat,lon]). Geocoder respects this convention and always expects method arguments to be given in [lat,lon] order. However, MongoDB requires that coordinates be stored in [lon,lat] order as per the GeoJSON spec (http://geojson.org/geojson-spec.html#positions), so internally they are stored "backwards." However, this does not affect order of arguments to methods when using Mongoid or MongoMapper.
547
+
548
+ To access an object's coordinates in the conventional order, use the `to_coordinates` instance method provided by Geocoder. For example:
549
+
550
+ obj.to_coordinates # => [37.7941013, -122.3951096] # [lat, lon]
551
+
552
+ Calling `obj.coordinates` directly returns the internal representation of the coordinates which, in the case of MongoDB, is probably the reverse of what you want:
553
+
554
+ obj.coordinates # => [-122.3951096, 37.7941013] # [lon, lat]
555
+
556
+ For consistency with the rest of Geocoder, always use the `to_coordinates` method instead.
557
+
558
+ Notes on Non-Rails Frameworks
559
+ -----------------------------
560
+
561
+ If you are using Geocoder with ActiveRecord and a framework other than Rails (like Sinatra or Padrino) you will need to add this in your model before calling Geocoder methods:
562
+
563
+ extend Geocoder::Model::ActiveRecord
564
+
565
+ Optimisation of Distance Queries
566
+ --------------------------------
567
+
568
+ In MySQL and Postgres the finding of objects near a given point is speeded up by using a bounding box to limit the number of points over which a full distance calculation needs to be done.
569
+
570
+ To take advantage of this optimisation you need to add a composite index on latitude and longitude. In your Rails migration:
571
+
572
+ add_index :table, [:latitude, :longitude]
573
+
574
+
575
+ Distance Queries in SQLite
576
+ --------------------------
577
+
578
+ SQLite's lack of trigonometric functions requires an alternate implementation of the `near` scope. When using SQLite, Geocoder will automatically use a less accurate algorithm for finding objects near a given point. Results of this algorithm should not be trusted too much as it will return objects that are outside the given radius, along with inaccurate distance and bearing calculations.
579
+
580
+
581
+ ### Discussion
582
+
583
+ There are few options for finding objects near a given point in SQLite without installing extensions:
584
+
585
+ 1. Use a square instead of a circle for finding nearby points. For example, if you want to find points near 40.71, 100.23, search for objects with latitude between 39.71 and 41.71 and longitude between 99.23 and 101.23. One degree of latitude or longitude is at most 69 miles so divide your radius (in miles) by 69.0 to get the amount to add and subtract from your center coordinates to get the upper and lower bounds. The results will not be very accurate (you'll get points outside the desired radius), but you will get all the points within the required radius.
586
+
587
+ 2. Load all objects into memory and compute distances between them using the `Geocoder::Calculations.distance_between` method. This will produce accurate results but will be very slow (and use a lot of memory) if you have a lot of objects in your database.
588
+
589
+ 3. If you have a large number of objects (so you can't use approach #2) and you need accurate results (better than approach #1 will give), you can use a combination of the two. Get all the objects within a square around your center point, and then eliminate the ones that are too far away using `Geocoder::Calculations.distance_between`.
590
+
591
+ Because Geocoder needs to provide this functionality as a scope, we must go with option #1, but feel free to implement #2 or #3 if you need more accuracy.
592
+
593
+
594
+ Tests
595
+ -----
596
+
597
+ Geocoder comes with a test suite (just run `rake test`) that mocks ActiveRecord and is focused on testing the aspects of Geocoder that do not involve executing database queries. Geocoder uses many database engine-specific queries which must be tested against all supported databases (SQLite, MySQL, etc). Ideally this involves creating a full, working Rails application, and that seems beyond the scope of the included test suite. As such, I have created a separate repository which includes a full-blown Rails application and some utilities for easily running tests against multiple environments:
598
+
599
+ http://github.com/alexreisner/geocoder_test
600
+
601
+
602
+ Error Handling
603
+ --------------
604
+
605
+ By default Geocoder will rescue any exceptions raised by calls to a geocoding service and return an empty array (using warn() to inform you of the error). You can override this on a per-exception basis, and also have Geocoder raise its own exceptions for certain events (eg: API quota exceeded) by using the `:always_raise` option:
606
+
607
+ Geocoder.configure(:always_raise => [SocketError, TimeoutError])
608
+
609
+ You can also do this to raise all exceptions:
610
+
611
+ Geocoder.configure(:always_raise => :all)
612
+
613
+ The raise-able exceptions are:
614
+
615
+ SocketError
616
+ TimeoutError
617
+ Geocoder::OverQueryLimitError
618
+ Geocoder::RequestDenied
619
+ Geocoder::InvalidRequest
620
+ Geocoder::InvalidApiKey
621
+
622
+ Note that not all lookups support all exceptions.
623
+
624
+
625
+ Troubleshooting
626
+ ---------------
627
+
628
+ ### Mongoid
629
+
630
+ If you get one of these errors:
631
+
632
+ uninitialized constant Geocoder::Model::Mongoid
633
+ uninitialized constant Geocoder::Model::Mongoid::Mongo
634
+
635
+ you should check your Gemfile to make sure the Mongoid gem is listed _before_ Geocoder. If Mongoid isn't loaded when Geocoder is initialized, Geocoder will not load support for Mongoid.
636
+
637
+ ### ActiveRecord
638
+
639
+ A lot of debugging time can be saved by understanding how Geocoder works with ActiveRecord. When you use the `near` scope or the `nearbys` method of a geocoded object, Geocoder creates an ActiveModel::Relation object which adds some attributes (eg: distance, bearing) to the SELECT clause. It also adds a condition to the WHERE clause to check that distance is within the given radius. Because the SELECT clause is modified, anything else that modifies the SELECT clause may produce strange results, for example:
640
+
641
+ * using the `pluck` method (selects only a single column)
642
+ * specifying another model through `includes` (selects columns from other tables)
643
+
644
+
645
+ Known Issue
646
+ -----------
647
+
648
+ You cannot use the `near` scope with another scope that provides an `includes` option because the `SELECT` clause generated by `near` will overwrite it (or vice versa). Instead, try using `joins` and pass a `:select` option to the `near` scope to get the columns you want. For example:
649
+
650
+ # instead of City.near(...).includes(:venues)
651
+ City.near("Omaha, NE", 20, :select => "cities.*, venues.*").joins(:venues)
652
+
653
+ If anyone has a more elegant solution to this problem I am very interested in seeing it.
654
+
655
+
656
+ Copyright (c) 2009-12 Alex Reisner, released under the MIT license