geocoder 1.5.1 → 1.7.3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (77) hide show
  1. checksums.yaml +5 -5
  2. data/CHANGELOG.md +65 -0
  3. data/LICENSE +1 -1
  4. data/README.md +333 -238
  5. data/bin/console +13 -0
  6. data/lib/easting_northing.rb +171 -0
  7. data/lib/generators/geocoder/config/templates/initializer.rb +7 -1
  8. data/lib/geocoder/cache.rb +16 -33
  9. data/lib/geocoder/cache_stores/base.rb +40 -0
  10. data/lib/geocoder/cache_stores/generic.rb +35 -0
  11. data/lib/geocoder/cache_stores/redis.rb +34 -0
  12. data/lib/geocoder/configuration.rb +11 -4
  13. data/lib/geocoder/configuration_hash.rb +4 -4
  14. data/lib/geocoder/ip_address.rb +8 -1
  15. data/lib/geocoder/lookup.rb +21 -3
  16. data/lib/geocoder/lookups/abstract_api.rb +46 -0
  17. data/lib/geocoder/lookups/amazon_location_service.rb +54 -0
  18. data/lib/geocoder/lookups/ban_data_gouv_fr.rb +14 -1
  19. data/lib/geocoder/lookups/base.rb +10 -2
  20. data/lib/geocoder/lookups/bing.rb +1 -1
  21. data/lib/geocoder/lookups/esri.rb +6 -0
  22. data/lib/geocoder/lookups/freegeoip.rb +4 -4
  23. data/lib/geocoder/lookups/geoapify.rb +72 -0
  24. data/lib/geocoder/lookups/geocodio.rb +1 -1
  25. data/lib/geocoder/lookups/geoip2.rb +4 -0
  26. data/lib/geocoder/lookups/google.rb +7 -2
  27. data/lib/geocoder/lookups/google_places_details.rb +8 -14
  28. data/lib/geocoder/lookups/google_places_search.rb +28 -2
  29. data/lib/geocoder/lookups/google_premier.rb +4 -0
  30. data/lib/geocoder/lookups/here.rb +7 -16
  31. data/lib/geocoder/lookups/ip2location.rb +10 -14
  32. data/lib/geocoder/lookups/ipdata_co.rb +1 -1
  33. data/lib/geocoder/lookups/ipgeolocation.rb +51 -0
  34. data/lib/geocoder/lookups/ipqualityscore.rb +50 -0
  35. data/lib/geocoder/lookups/ipregistry.rb +68 -0
  36. data/lib/geocoder/lookups/latlon.rb +1 -2
  37. data/lib/geocoder/lookups/maxmind_local.rb +7 -1
  38. data/lib/geocoder/lookups/melissa_street.rb +41 -0
  39. data/lib/geocoder/lookups/nationaal_georegister_nl.rb +38 -0
  40. data/lib/geocoder/lookups/osmnames.rb +57 -0
  41. data/lib/geocoder/lookups/photon.rb +89 -0
  42. data/lib/geocoder/lookups/pickpoint.rb +1 -1
  43. data/lib/geocoder/lookups/smarty_streets.rb +6 -1
  44. data/lib/geocoder/lookups/telize.rb +1 -1
  45. data/lib/geocoder/lookups/tencent.rb +9 -9
  46. data/lib/geocoder/lookups/test.rb +4 -0
  47. data/lib/geocoder/lookups/uk_ordnance_survey_names.rb +59 -0
  48. data/lib/geocoder/lookups/yandex.rb +3 -4
  49. data/lib/geocoder/results/abstract_api.rb +146 -0
  50. data/lib/geocoder/results/amazon_location_service.rb +57 -0
  51. data/lib/geocoder/results/baidu.rb +0 -4
  52. data/lib/geocoder/results/ban_data_gouv_fr.rb +27 -2
  53. data/lib/geocoder/results/db_ip_com.rb +1 -1
  54. data/lib/geocoder/results/esri.rb +5 -2
  55. data/lib/geocoder/results/geoapify.rb +179 -0
  56. data/lib/geocoder/results/here.rb +4 -1
  57. data/lib/geocoder/results/ipgeolocation.rb +59 -0
  58. data/lib/geocoder/results/ipqualityscore.rb +54 -0
  59. data/lib/geocoder/results/ipregistry.rb +304 -0
  60. data/lib/geocoder/results/mapbox.rb +10 -4
  61. data/lib/geocoder/results/melissa_street.rb +46 -0
  62. data/lib/geocoder/results/nationaal_georegister_nl.rb +62 -0
  63. data/lib/geocoder/results/nominatim.rb +27 -15
  64. data/lib/geocoder/results/osmnames.rb +56 -0
  65. data/lib/geocoder/results/photon.rb +119 -0
  66. data/lib/geocoder/results/uk_ordnance_survey_names.rb +59 -0
  67. data/lib/geocoder/results/yandex.rb +217 -59
  68. data/lib/geocoder/sql.rb +4 -4
  69. data/lib/geocoder/util.rb +29 -0
  70. data/lib/geocoder/version.rb +1 -1
  71. data/lib/maxmind_database.rb +3 -3
  72. metadata +35 -18
  73. data/examples/autoexpire_cache_dalli.rb +0 -62
  74. data/examples/autoexpire_cache_redis.rb +0 -28
  75. data/lib/geocoder/lookups/geocoder_us.rb +0 -51
  76. data/lib/geocoder/results/geocoder_us.rb +0 -39
  77. data/lib/hash_recursive_merge.rb +0 -74
data/README.md CHANGED
@@ -1,29 +1,27 @@
1
1
  Geocoder
2
2
  ========
3
3
 
4
- **A complete geocoding solution for Ruby.**
4
+ **Complete geocoding solution for Ruby.**
5
5
 
6
6
  [![Gem Version](https://badge.fury.io/rb/geocoder.svg)](http://badge.fury.io/rb/geocoder)
7
7
  [![Code Climate](https://codeclimate.com/github/alexreisner/geocoder/badges/gpa.svg)](https://codeclimate.com/github/alexreisner/geocoder)
8
- [![Build Status](https://travis-ci.org/alexreisner/geocoder.svg?branch=master)](https://travis-ci.org/alexreisner/geocoder)
9
- [![GitHub Issues](https://img.shields.io/github/issues/alexreisner/geocoder.svg)](https://github.com/alexreisner/geocoder/issues)
10
- [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT)
8
+ [![Build Status](https://travis-ci.com/alexreisner/geocoder.svg?branch=master)](https://travis-ci.com/alexreisner/geocoder)
11
9
 
12
10
  Key features:
13
11
 
14
- * Forward and reverse geocoding, and IP address geocoding.
12
+ * Forward and reverse geocoding.
13
+ * IP address geocoding.
15
14
  * Connects to more than 40 APIs worldwide.
16
15
  * Performance-enhancing features like caching.
17
- * Advanced configuration allows different parameters and APIs to be used in different conditions.
18
16
  * Integrates with ActiveRecord and Mongoid.
19
17
  * Basic geospatial queries: search within radius (or rectangle, or ring).
20
18
 
21
19
  Compatibility:
22
20
 
23
- * Supports multiple Ruby versions: Ruby 2.x, and JRuby.
24
- * Supports multiple databases: MySQL, PostgreSQL, SQLite, and MongoDB (1.7.0 and higher).
25
- * Supports Rails 3, 4, and 5. If you need to use it with Rails 2 please see the `rails2` branch (no longer maintained, limited feature set).
26
- * Works very well outside of Rails, you just need to install either the `json` (for MRI) or `json_pure` (for JRuby) gem.
21
+ * Ruby versions: 2.1+, and JRuby.
22
+ * Databases: MySQL, PostgreSQL, SQLite, and MongoDB.
23
+ * Rails: 5.x and 6.x.
24
+ * Works outside of Rails with the `json` (for MRI) or `json_pure` (for JRuby) gem.
27
25
 
28
26
 
29
27
  Table of Contents
@@ -53,8 +51,8 @@ The Rest:
53
51
  * [Technical Discussions](#technical-discussions)
54
52
  * [Troubleshooting](#troubleshooting)
55
53
  * [Known Issues](#known-issues)
56
- * [Reporting Issues](#reporting-issues)
57
- * [Contributing](#contributing)
54
+ * [Reporting Issues](https://github.com/alexreisner/geocoder/blob/master/CONTRIBUTING.md#reporting-bugs)
55
+ * [Contributing](https://github.com/alexreisner/geocoder/blob/master/CONTRIBUTING.md#making-changes)
58
56
 
59
57
  See Also:
60
58
 
@@ -66,23 +64,29 @@ Basic Search
66
64
 
67
65
  In its simplest form, Geocoder takes an address and searches for its latitude/longitude coordinates:
68
66
 
69
- results = Geocoder.search("Paris")
70
- results.first.coordinates
71
- => [48.856614, 2.3522219] # latitude and longitude
67
+ ```ruby
68
+ results = Geocoder.search("Paris")
69
+ results.first.coordinates
70
+ # => [48.856614, 2.3522219] # latitude and longitude
71
+ ```
72
72
 
73
73
  The reverse is possible too. Given coordinates, it finds an address:
74
74
 
75
- results = Geocoder.search([48.856614, 2.3522219])
76
- results.first.address
77
- => "Hôtel de Ville, 75004 Paris, France"
75
+ ```ruby
76
+ results = Geocoder.search([48.856614, 2.3522219])
77
+ results.first.address
78
+ # => "Hôtel de Ville, 75004 Paris, France"
79
+ ```
78
80
 
79
81
  You can also look up the location of an IP addresses:
80
82
 
81
- results = Geocoder.search("172.56.21.89")
82
- results.first.coordinates
83
- => [30.267153, -97.7430608]
84
- results.first.country
85
- => "United States"
83
+ ```ruby
84
+ results = Geocoder.search("172.56.21.89")
85
+ results.first.coordinates
86
+ # => [30.267153, -97.7430608]
87
+ results.first.country
88
+ # => "United States"
89
+ ```
86
90
 
87
91
  **The success and accuracy of geocoding depends entirely on the API being used to do these lookups.** Most queries work fairly well with the default configuration, but every application has different needs and every API has its particular strengths and weaknesses. If you need better coverage for your application you'll want to get familiar with the large number of supported APIs, listed in the [API Guide](https://github.com/alexreisner/geocoder/blob/master/README_API_GUIDE.md).
88
92
 
@@ -94,30 +98,40 @@ To automatically geocode your objects:
94
98
 
95
99
  **1.** Your model must provide a method that returns an address to geocode. 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`). For example, if your model has `street`, `city`, `state`, and `country` attributes you might do something like this:
96
100
 
97
- def address
98
- [street, city, state, country].compact.join(', ')
99
- end
101
+ ```ruby
102
+ def address
103
+ [street, city, state, country].compact.join(', ')
104
+ end
105
+ ```
100
106
 
101
107
  **2.** Your model must have a way to store latitude/longitude coordinates. With ActiveRecord, add two attributes/columns (of type float or decimal) called `latitude` and `longitude`. For MongoDB, use a single field (of type Array) called `coordinates` (i.e., `field :coordinates, type: Array`). (See [Advanced Model Configuration](#advanced-model-configuration) for using different attribute names.)
102
108
 
103
109
  **3.** In your model, tell geocoder where to find the object's address:
104
110
 
105
- geocoded_by :address
111
+ ```ruby
112
+ geocoded_by :address
113
+ ```
106
114
 
107
115
  This adds a `geocode` method which you can invoke via callback:
108
116
 
109
- after_validation :geocode
117
+ ```ruby
118
+ after_validation :geocode
119
+ ```
110
120
 
111
121
  Reverse geocoding (given lat/lon coordinates, find an address) is similar:
112
122
 
113
- reverse_geocoded_by :latitude, :longitude
114
- after_validation :reverse_geocode
123
+ ```ruby
124
+ reverse_geocoded_by :latitude, :longitude
125
+ after_validation :reverse_geocode
126
+ ```
115
127
 
116
128
  With any geocoded objects, you can do the following:
117
129
 
118
- obj.distance_to([43.9,-98.6]) # distance from obj to point
119
- obj.bearing_to([43.9,-98.6]) # bearing from obj to point
120
- obj.bearing_from(obj2) # bearing from obj2 to obj
130
+ ```ruby
131
+ obj.distance_to([43.9,-98.6]) # distance from obj to point
132
+ obj.bearing_to([43.9,-98.6]) # bearing from obj to point
133
+ obj.bearing_from(obj2) # bearing from obj2 to obj
134
+ ```
121
135
 
122
136
  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`, `:km`, or `:nm` for nautical miles). See [Distance and Bearing](#distance-and-bearing) below for more info.
123
137
 
@@ -125,18 +139,24 @@ The `bearing_from/to` methods take a single argument which can be: a `[lat,lon]`
125
139
 
126
140
  Before you can call `geocoded_by` you'll need to include the necessary module using one of the following:
127
141
 
128
- include Geocoder::Model::Mongoid
129
- include Geocoder::Model::MongoMapper
142
+ ```ruby
143
+ include Geocoder::Model::Mongoid
144
+ include Geocoder::Model::MongoMapper
145
+ ```
130
146
 
131
147
  ### Latitude/Longitude Order in MongoDB
132
148
 
133
149
  Everywhere coordinates are passed to methods as two-element arrays, Geocoder expects them to be in the order: `[lat, lon]`. However, as per [the GeoJSON spec](http://geojson.org/geojson-spec.html#positions), MongoDB requires that coordinates be stored longitude-first (`[lon, lat]`), so internally they are stored "backwards." Geocoder's methods attempt to hide this, so calling `obj.to_coordinates` (a method added to the object by Geocoder via `geocoded_by`) returns coordinates in the conventional order:
134
150
 
135
- obj.to_coordinates # => [37.7941013, -122.3951096] # [lat, lon]
151
+ ```ruby
152
+ obj.to_coordinates # => [37.7941013, -122.3951096] # [lat, lon]
153
+ ```
136
154
 
137
155
  whereas calling the object's coordinates attribute directly (`obj.coordinates` by default) returns the internal representation which is probably the reverse of what you want:
138
156
 
139
- obj.coordinates # => [-122.3951096, 37.7941013] # [lon, lat]
157
+ ```ruby
158
+ obj.coordinates # => [-122.3951096, 37.7941013] # [lon, lat]
159
+ ```
140
160
 
141
161
  So, be careful.
142
162
 
@@ -144,7 +164,9 @@ So, be careful.
144
164
 
145
165
  To use 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:
146
166
 
147
- extend Geocoder::Model::ActiveRecord
167
+ ```ruby
168
+ extend Geocoder::Model::ActiveRecord
169
+ ```
148
170
 
149
171
 
150
172
  Geospatial Database Queries
@@ -154,19 +176,23 @@ Geospatial Database Queries
154
176
 
155
177
  To find objects by location, use the following scopes:
156
178
 
157
- Venue.near('Omaha, NE, US') # venues within 20 miles of Omaha
158
- Venue.near([40.71, -100.23], 50) # venues within 50 miles of a point
159
- Venue.near([40.71, -100.23], 50, units: :km) # venues within 50 kilometres of a point
160
- Venue.geocoded # venues with coordinates
161
- Venue.not_geocoded # venues without coordinates
179
+ ```ruby
180
+ Venue.near('Omaha, NE, US') # venues within 20 miles of Omaha
181
+ Venue.near([40.71, -100.23], 50) # venues within 50 miles of a point
182
+ Venue.near([40.71, -100.23], 50, units: :km) # venues within 50 kilometres of a point
183
+ Venue.geocoded # venues with coordinates
184
+ Venue.not_geocoded # venues without coordinates
185
+ ```
162
186
 
163
187
  With geocoded objects you can do things like this:
164
188
 
165
- if obj.geocoded?
166
- obj.nearbys(30) # other objects within 30 miles
167
- obj.distance_from([40.714,-100.234]) # distance from arbitrary point to object
168
- obj.bearing_to("Paris, France") # direction from object to arbitrary point
169
- end
189
+ ```ruby
190
+ if obj.geocoded?
191
+ obj.nearbys(30) # other objects within 30 miles
192
+ obj.distance_from([40.714,-100.234]) # distance from arbitrary point to object
193
+ obj.bearing_to("Paris, France") # direction from object to arbitrary point
194
+ end
195
+ ```
170
196
 
171
197
  ### For MongoDB-backed models:
172
198
 
@@ -178,8 +204,10 @@ Geocoding HTTP Requests
178
204
 
179
205
  Geocoder adds `location` and `safe_location` methods 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:
180
206
 
181
- # returns Geocoder::Result object
182
- result = request.location
207
+ ```ruby
208
+ # returns Geocoder::Result object
209
+ result = request.location
210
+ ```
183
211
 
184
212
  **The `location` method is vulnerable to trivial IP address spoofing via HTTP headers.** If that's a problem for your application, use `safe_location` instead, but be aware that `safe_location` will *not* try to trace a request's originating IP through proxy headers; you will instead get the location of the last proxy the request passed through, if any (excepting any proxies you have explicitly whitelisted in your Rack config).
185
213
 
@@ -193,71 +221,83 @@ Geocoder supports a variety of street and IP address geocoding services. The def
193
221
 
194
222
  To create a Rails initializer with sample configuration:
195
223
 
196
- rails generate geocoder:config
224
+ ```sh
225
+ rails generate geocoder:config
226
+ ```
197
227
 
198
228
  Some common options are:
199
229
 
200
- # config/initializers/geocoder.rb
201
- Geocoder.configure(
230
+ ```ruby
231
+ # config/initializers/geocoder.rb
232
+ Geocoder.configure(
233
+ # street address geocoding service (default :nominatim)
234
+ lookup: :yandex,
202
235
 
203
- # street address geocoding service (default :nominatim)
204
- lookup: :yandex,
236
+ # IP address geocoding service (default :ipinfo_io)
237
+ ip_lookup: :maxmind,
205
238
 
206
- # IP address geocoding service (default :ipinfo_io)
207
- ip_lookup: :maxmind,
239
+ # to use an API key:
240
+ api_key: "...",
208
241
 
209
- # to use an API key:
210
- api_key: "...",
242
+ # geocoding service request timeout, in seconds (default 3):
243
+ timeout: 5,
211
244
 
212
- # geocoding service request timeout, in seconds (default 3):
213
- timeout: 5,
245
+ # set default units to kilometers:
246
+ units: :km,
214
247
 
215
- # set default units to kilometers:
216
- units: :km,
217
-
218
- # caching (see [below](#caching) for details):
219
- cache: Redis.new,
220
- cache_prefix: "..."
221
-
222
- )
248
+ # caching (see Caching section below for details):
249
+ # warning: `cache_prefix` is deprecated, use `cache_options` instead
250
+ cache: Redis.new,
251
+ cache_options: {
252
+ expiration: 2.days, # Redis ttl
253
+ prefix: "..."
254
+ }
255
+ )
256
+ ```
223
257
 
224
258
  Please see [`lib/geocoder/configuration.rb`](https://github.com/alexreisner/geocoder/blob/master/lib/geocoder/configuration.rb) for a complete list of configuration options. Additionally, some lookups have their own special configuration options which are directly supported by Geocoder. For example, to specify a value for Google's `bounds` parameter:
225
259
 
226
- # with Google:
227
- Geocoder.search("Middletown", bounds: [[40.6,-77.9], [39.9,-75.9]])
260
+ ```ruby
261
+ # with Google:
262
+ Geocoder.search("Middletown", bounds: [[40.6,-77.9], [39.9,-75.9]])
263
+ ```
228
264
 
229
265
  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, which appends options to the query string of the geocoding request. For example:
230
266
 
231
- # Nominatim's `countrycodes` parameter:
232
- Geocoder.search("Rome", params: {countrycodes: "us,ca"})
267
+ ```ruby
268
+ # Nominatim's `countrycodes` parameter:
269
+ Geocoder.search("Rome", params: {countrycodes: "us,ca"})
233
270
 
234
- # Google's `region` parameter:
235
- Geocoder.search("Rome", params: {region: "..."})
271
+ # Google's `region` parameter:
272
+ Geocoder.search("Rome", params: {region: "..."})
273
+ ```
236
274
 
237
275
  ### Configuring Multiple Services
238
276
 
239
277
  You can configure multiple geocoding services at once by using the service's name as a key for a sub-configuration hash, like this:
240
278
 
241
- Geocoder.configure(
279
+ ```ruby
280
+ Geocoder.configure(
242
281
 
243
- timeout: 2,
244
- cache: Redis.new,
282
+ timeout: 2,
283
+ cache: Redis.new,
245
284
 
246
- yandex: {
247
- api_key: "...",
248
- timeout: 5
249
- },
285
+ yandex: {
286
+ api_key: "...",
287
+ timeout: 5
288
+ },
250
289
 
251
- baidu: {
252
- api_key: "..."
253
- },
290
+ baidu: {
291
+ api_key: "..."
292
+ },
254
293
 
255
- maxmind: {
256
- api_key: "...",
257
- service: :omni
258
- }
294
+ maxmind: {
295
+ api_key: "...",
296
+ service: :omni
297
+ }
259
298
 
260
- )
299
+ )
300
+ ```
261
301
 
262
302
  Lookup-specific settings override global settings so, in this example, the timeout for all lookups is 2 seconds, except for Yandex which is 5.
263
303
 
@@ -269,12 +309,16 @@ Performance and Optimization
269
309
 
270
310
  In MySQL and Postgres, queries use a bounding box to limit the number of points over which a more precise distance calculation needs to be done. To take advantage of this optimisation, you need to add a composite index on latitude and longitude. In your Rails migration:
271
311
 
272
- add_index :table, [:latitude, :longitude]
312
+ ```ruby
313
+ add_index :table, [:latitude, :longitude]
314
+ ```
273
315
 
274
316
  In MongoDB, 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:
275
317
 
276
- include Geocoder::Model::Mongoid
277
- geocoded_by :address, skip_index: true
318
+ ```ruby
319
+ include Geocoder::Model::Mongoid
320
+ geocoded_by :address, skip_index: true
321
+ ```
278
322
 
279
323
  ### Avoiding Unnecessary API Requests
280
324
 
@@ -285,13 +329,17 @@ Geocoding only needs to be performed under certain conditions. To avoid unnecess
285
329
 
286
330
  The exact code will vary depending on the method you use for your geocodable string, but it would be something like this:
287
331
 
288
- after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }
332
+ ```ruby
333
+ after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }
334
+ ```
289
335
 
290
336
  ### Caching
291
337
 
292
338
  When relying on any external service, it's always a good idea 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:
293
339
 
294
- Geocoder.configure(cache: Redis.new)
340
+ ```ruby
341
+ Geocoder.configure(cache: Redis.new)
342
+ ```
295
343
 
296
344
  This example uses Redis, but the cache store can be any object that supports these methods:
297
345
 
@@ -302,20 +350,30 @@ This example uses Redis, but the cache store can be any object that supports the
302
350
 
303
351
  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).
304
352
 
353
+ When using Rails use the Generic cache store as an adapter around `Rails.cache`:
354
+
355
+ ```ruby
356
+ Geocoder.configure(cache: Geocoder::CacheStore::Generic.new(Rails.cache, {}))
357
+ ```
358
+
305
359
  You can also set a custom prefix to be used for cache keys:
306
360
 
307
- Geocoder.configure(cache_prefix: "...")
361
+ ```ruby
362
+ Geocoder.configure(cache_options: { prefix: "..." })
363
+ ```
308
364
 
309
365
  By default the prefix is `geocoder:`
310
366
 
311
367
  If you need to expire cached content:
312
368
 
313
- Geocoder::Lookup.get(Geocoder.config[:lookup]).cache.expire(:all) # expire cached results for current Lookup
314
- Geocoder::Lookup.get(:nominatim).cache.expire("http://...") # expire cached result for a specific URL
315
- Geocoder::Lookup.get(:nominatim).cache.expire(:all) # expire cached results for Google Lookup
316
- # expire all cached results for all Lookups.
317
- # Be aware that this methods spawns a new Lookup object for each Service
318
- Geocoder::Lookup.all_services.each{|service| Geocoder::Lookup.get(service).cache.expire(:all)}
369
+ ```ruby
370
+ Geocoder::Lookup.get(Geocoder.config[:lookup]).cache.expire(:all) # expire cached results for current Lookup
371
+ Geocoder::Lookup.get(:nominatim).cache.expire("http://...") # expire cached result for a specific URL
372
+ Geocoder::Lookup.get(:nominatim).cache.expire(:all) # expire cached results for Google Lookup
373
+ # expire all cached results for all Lookups.
374
+ # Be aware that this methods spawns a new Lookup object for each Service
375
+ Geocoder::Lookup.all_services.each{|service| Geocoder::Lookup.get(service).cache.expire(:all)}
376
+ ```
319
377
 
320
378
  Do *not* include the prefix when passing a URL to be expired. Expiring `:all` will only expire keys with the configured prefix -- it will *not* expire every entry in your key/value store.
321
379
 
@@ -329,44 +387,55 @@ Advanced Model Configuration
329
387
 
330
388
  You are not stuck with the `latitude` and `longitude` database column names (with ActiveRecord) or the `coordinates` array (Mongo) for storing coordinates. For example:
331
389
 
332
- geocoded_by :address, latitude: :lat, longitude: :lon # ActiveRecord
333
- geocoded_by :address, coordinates: :coords # MongoDB
390
+ ```ruby
391
+ geocoded_by :address, latitude: :lat, longitude: :lon # ActiveRecord
392
+ geocoded_by :address, coordinates: :coords # MongoDB
393
+ ```
334
394
 
335
395
  For reverse geocoding, you can specify the attribute where the address will be stored. For example:
336
396
 
337
- reverse_geocoded_by :latitude, :longitude, address: :loc # ActiveRecord
338
- reverse_geocoded_by :coordinates, address: :street_address # MongoDB
397
+ ```ruby
398
+ reverse_geocoded_by :latitude, :longitude, address: :loc # ActiveRecord
399
+ reverse_geocoded_by :coordinates, address: :street_address # MongoDB
400
+ ```
339
401
 
340
402
  To specify geocoding parameters in your model:
341
403
 
342
- geocoded_by :address, params: {region: "..."}
404
+ ```ruby
405
+ geocoded_by :address, params: {region: "..."}
406
+ ```
343
407
 
344
408
  Supported parameters: `:lookup`, `:ip_lookup`, `:language`, and `:params`. You can specify an anonymous function if you want to set these on a per-request basis. For example, to use different lookups for objects in different regions:
345
409
 
346
- geocoded_by :address, lookup: lambda{ |obj| obj.geocoder_lookup }
410
+ ```ruby
411
+ geocoded_by :address, lookup: lambda{ |obj| obj.geocoder_lookup }
347
412
 
348
- def geocoder_lookup
349
- if country_code == "RU"
350
- :yandex
351
- elsif country_code == "CN"
352
- :baidu
353
- else
354
- :nominatim
355
- end
356
- end
413
+ def geocoder_lookup
414
+ if country_code == "RU"
415
+ :yandex
416
+ elsif country_code == "CN"
417
+ :baidu
418
+ else
419
+ :nominatim
420
+ end
421
+ end
422
+ ```
357
423
 
358
424
  ### Custom Result Handling
359
425
 
360
426
  So far we have seen examples where geocoding results are assigned automatically to predefined object attributes. However, you can skip the auto-assignment by providing a block which handles the parsed geocoding results any way you like, for example:
361
427
 
362
- reverse_geocoded_by :latitude, :longitude do |obj,results|
363
- if geo = results.first
364
- obj.city = geo.city
365
- obj.zipcode = geo.postal_code
366
- obj.country = geo.country_code
367
- end
368
- end
369
- after_validation :reverse_geocode
428
+ ```ruby
429
+ reverse_geocoded_by :latitude, :longitude do |obj,results|
430
+ if geo = results.first
431
+ obj.city = geo.city
432
+ obj.zipcode = geo.postal_code
433
+ obj.country = geo.country_code
434
+ end
435
+ end
436
+
437
+ after_validation :reverse_geocode
438
+ ```
370
439
 
371
440
  Every `Geocoder::Result` object, `result`, provides the following data:
372
441
 
@@ -392,23 +461,26 @@ You can apply both forward and reverse geocoding to the same model (i.e. users c
392
461
 
393
462
  For example:
394
463
 
395
- class Venue
396
-
397
- # build an address from street, city, and state attributes
398
- geocoded_by :address_from_components
464
+ ```ruby
465
+ class Venue
466
+ # build an address from street, city, and state attributes
467
+ geocoded_by :address_from_components
399
468
 
400
- # store the fetched address in the full_address attribute
401
- reverse_geocoded_by :latitude, :longitude, address: :full_address
402
- end
469
+ # store the fetched address in the full_address attribute
470
+ reverse_geocoded_by :latitude, :longitude, address: :full_address
471
+ end
472
+ ```
403
473
 
404
474
  The same goes for latitude/longitude. However, for purposes of querying the database, there can be only one authoritative set of latitude/longitude attributes for use in database queries. This is whichever you specify last. For example, here the attributes *without* the `fetched_` prefix will be authoritative:
405
475
 
406
- class Venue
407
- geocoded_by :address,
408
- latitude: :fetched_latitude,
409
- longitude: :fetched_longitude
410
- reverse_geocoded_by :latitude, :longitude
411
- end
476
+ ```ruby
477
+ class Venue
478
+ geocoded_by :address,
479
+ latitude: :fetched_latitude,
480
+ longitude: :fetched_longitude
481
+ reverse_geocoded_by :latitude, :longitude
482
+ end
483
+ ```
412
484
 
413
485
 
414
486
  Advanced Database Queries
@@ -418,21 +490,29 @@ Advanced Database Queries
418
490
 
419
491
  The default `near` search looks for objects within a circle. To search within a doughnut or ring use the `:min_radius` option:
420
492
 
421
- Venue.near("Austin, TX", 200, min_radius: 40)
493
+ ```ruby
494
+ Venue.near("Austin, TX", 200, min_radius: 40)
495
+ ```
422
496
 
423
497
  To search within a rectangle (note that results will *not* include `distance` and `bearing` attributes):
424
498
 
425
- sw_corner = [40.71, 100.23]
426
- ne_corner = [36.12, 88.65]
427
- Venue.within_bounding_box(sw_corner, ne_corner)
499
+ ```ruby
500
+ sw_corner = [40.71, 100.23]
501
+ ne_corner = [36.12, 88.65]
502
+ Venue.within_bounding_box(sw_corner, ne_corner)
503
+ ```
428
504
 
429
505
  To search for objects near a certain point where each object has a different distance requirement (which is defined in the database), you can pass a column name for the radius:
430
506
 
431
- Venue.near([40.71, 99.23], :effective_radius)
507
+ ```ruby
508
+ Venue.near([40.71, 99.23], :effective_radius)
509
+ ```
432
510
 
433
511
  If you store multiple sets of coordinates for each object, you can specify latitude and longitude columns to use for a search:
434
512
 
435
- Venue.near("Paris", 50, latitude: :secondary_latitude, longitude: :secondary_longitude)
513
+ ```ruby
514
+ Venue.near("Paris", 50, latitude: :secondary_latitude, longitude: :secondary_longitude)
515
+ ```
436
516
 
437
517
  ### Distance and Bearing
438
518
 
@@ -452,9 +532,11 @@ Results are automatically sorted by distance from the search point, closest to f
452
532
 
453
533
  You can convert these to compass point names via provided method:
454
534
 
455
- Geocoder::Calculations.compass_point(355) # => "N"
456
- Geocoder::Calculations.compass_point(45) # => "NE"
457
- Geocoder::Calculations.compass_point(208) # => "SW"
535
+ ```ruby
536
+ Geocoder::Calculations.compass_point(355) # => "N"
537
+ Geocoder::Calculations.compass_point(45) # => "NE"
538
+ Geocoder::Calculations.compass_point(208) # => "SW"
539
+ ```
458
540
 
459
541
  _Note: when running queries on SQLite, `distance` and `bearing` are provided for consistency only. They are not very accurate._
460
542
 
@@ -466,13 +548,15 @@ Geospatial Calculations
466
548
 
467
549
  The `Geocoder::Calculations` module contains some useful methods:
468
550
 
469
- # find the distance between two arbitrary points
470
- Geocoder::Calculations.distance_between([47.858205,2.294359], [40.748433,-73.985655])
471
- => 3619.77359999382 # in configured units (default miles)
551
+ ```ruby
552
+ # find the distance between two arbitrary points
553
+ Geocoder::Calculations.distance_between([47.858205,2.294359], [40.748433,-73.985655])
554
+ => 3619.77359999382 # in configured units (default miles)
472
555
 
473
- # find the geographic center (aka center of gravity) of objects or points
474
- Geocoder::Calculations.geographic_center([city1, city2, [40.22,-73.99], city4])
475
- => [35.14968, -90.048929]
556
+ # find the geographic center (aka center of gravity) of objects or points
557
+ Geocoder::Calculations.geographic_center([city1, city2, [40.22,-73.99], city4])
558
+ => [35.14968, -90.048929]
559
+ ```
476
560
 
477
561
  See [the code](https://github.com/alexreisner/geocoder/blob/master/lib/geocoder/calculations.rb) for more!
478
562
 
@@ -482,19 +566,27 @@ Batch Geocoding
482
566
 
483
567
  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:
484
568
 
485
- rake geocode:all CLASS=YourModel
569
+ ```sh
570
+ rake geocode:all CLASS=YourModel
571
+ ```
486
572
 
487
573
  If you need reverse geocoding instead, call the task with REVERSE=true:
488
574
 
489
- rake geocode:all CLASS=YourModel REVERSE=true
575
+ ```sh
576
+ rake geocode:all CLASS=YourModel REVERSE=true
577
+ ```
490
578
 
491
579
  In either case, it won't try to geocode objects that are already geocoded. The task will print warnings if you exceed the rate limit for your geocoding service. Some services enforce a per-second limit in addition to a per-day limit. To avoid exceeding the per-second limit, you can add a `SLEEP` option to pause between requests for a given amount of time. You can also load objects in batches to save memory, for example:
492
580
 
493
- rake geocode:all CLASS=YourModel SLEEP=0.25 BATCH=100
581
+ ```sh
582
+ rake geocode:all CLASS=YourModel SLEEP=0.25 BATCH=100
583
+ ```
494
584
 
495
585
  To avoid exceeding per-day limits you can add a `LIMIT` option. However, this will ignore the `BATCH` value, if provided.
496
586
 
497
- rake geocode:all CLASS=YourModel LIMIT=1000
587
+ ```sh
588
+ rake geocode:all CLASS=YourModel LIMIT=1000
589
+ ```
498
590
 
499
591
 
500
592
  Testing
@@ -502,42 +594,54 @@ Testing
502
594
 
503
595
  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 the `:test` lookup and/or `:ip_lookup`
504
596
 
505
- Geocoder.configure(lookup: :test, ip_lookup: :test)
597
+ ```ruby
598
+ Geocoder.configure(lookup: :test, ip_lookup: :test)
599
+ ```
506
600
 
507
601
  Add stubs to define the results that will be returned:
508
602
 
509
- Geocoder::Lookup::Test.add_stub(
510
- "New York, NY", [
511
- {
512
- 'coordinates' => [40.7143528, -74.0059731],
513
- 'address' => 'New York, NY, USA',
514
- 'state' => 'New York',
515
- 'state_code' => 'NY',
516
- 'country' => 'United States',
517
- 'country_code' => 'US'
518
- }
519
- ]
520
- )
603
+ ```ruby
604
+ Geocoder::Lookup::Test.add_stub(
605
+ "New York, NY", [
606
+ {
607
+ 'coordinates' => [40.7143528, -74.0059731],
608
+ 'address' => 'New York, NY, USA',
609
+ 'state' => 'New York',
610
+ 'state_code' => 'NY',
611
+ 'country' => 'United States',
612
+ 'country_code' => 'US'
613
+ }
614
+ ]
615
+ )
616
+ ```
521
617
 
522
618
  With the above stub defined, any query for "New York, NY" will return the results array that follows. You can also set a default stub, to be returned when no other stub matches a given query:
523
619
 
524
- Geocoder::Lookup::Test.set_default_stub(
525
- [
526
- {
527
- 'coordinates' => [40.7143528, -74.0059731],
528
- 'address' => 'New York, NY, USA',
529
- 'state' => 'New York',
530
- 'state_code' => 'NY',
531
- 'country' => 'United States',
532
- 'country_code' => 'US'
533
- }
534
- ]
535
- )
620
+ ```ruby
621
+ Geocoder::Lookup::Test.set_default_stub(
622
+ [
623
+ {
624
+ 'coordinates' => [40.7143528, -74.0059731],
625
+ 'address' => 'New York, NY, USA',
626
+ 'state' => 'New York',
627
+ 'state_code' => 'NY',
628
+ 'country' => 'United States',
629
+ 'country_code' => 'US'
630
+ }
631
+ ]
632
+ )
633
+ ```
634
+
635
+ You may also delete a single stub, or reset all stubs _including the default stub_:
636
+
637
+ ```ruby
638
+ Geocoder::Lookup::Test.delete_stub('New York, NY')
639
+ Geocoder::Lookup::Test.reset
640
+ ```
536
641
 
537
642
  Notes:
538
643
 
539
644
  - Keys must be strings (not symbols) when calling `add_stub` or `set_default_stub`. For example `'country' =>` not `:country =>`.
540
- - To clear stubs (e.g. prior to another spec), use `Geocoder::Lookup::Test.reset`. This will clear all stubs _including the default stub_.
541
645
  - The stubbed result objects returned by the Test lookup do not support all the methods real result objects do. If you need to test interaction with real results it may be better to use an external stubbing tool and something like WebMock or VCR to prevent network calls.
542
646
 
543
647
 
@@ -546,21 +650,27 @@ Error Handling
546
650
 
547
651
  By default Geocoder will rescue any exceptions raised by calls to a geocoding service and return an empty array. 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:
548
652
 
549
- Geocoder.configure(always_raise: [SocketError, Timeout::Error])
653
+ ```ruby
654
+ Geocoder.configure(always_raise: [SocketError, Timeout::Error])
655
+ ```
550
656
 
551
657
  You can also do this to raise all exceptions:
552
658
 
553
- Geocoder.configure(always_raise: :all)
659
+ ```ruby
660
+ Geocoder.configure(always_raise: :all)
661
+ ```
554
662
 
555
663
  The raise-able exceptions are:
556
664
 
557
- SocketError
558
- Timeout::Error
559
- Geocoder::OverQueryLimitError
560
- Geocoder::RequestDenied
561
- Geocoder::InvalidRequest
562
- Geocoder::InvalidApiKey
563
- Geocoder::ServiceUnavailable
665
+ ```ruby
666
+ SocketError
667
+ Timeout::Error
668
+ Geocoder::OverQueryLimitError
669
+ Geocoder::RequestDenied
670
+ Geocoder::InvalidRequest
671
+ Geocoder::InvalidApiKey
672
+ Geocoder::ServiceUnavailable
673
+ ```
564
674
 
565
675
  Note that only a few of the above exceptions are raised by any given lookup, so there's no guarantee if you configure Geocoder to raise `ServiceUnavailable` that it will actually be raised under those conditions (because most APIs don't return 503 when they should; you may get a `Timeout::Error` instead). Please see the source code for your particular lookup for details.
566
676
 
@@ -570,15 +680,17 @@ Command Line Interface
570
680
 
571
681
  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:
572
682
 
573
- $ geocode 29.951,-90.081
574
- Latitude: 29.952211
575
- Longitude: -90.080563
576
- Full address: 1500 Sugar Bowl Dr, New Orleans, LA 70112, USA
577
- City: New Orleans
578
- State/province: Louisiana
579
- Postal code: 70112
580
- Country: United States
581
- Map: http://maps.google.com/maps?q=29.952211,-90.080563
683
+ ```sh
684
+ $ geocode 29.951,-90.081
685
+ Latitude: 29.952211
686
+ Longitude: -90.080563
687
+ Full address: 1500 Sugar Bowl Dr, New Orleans, LA 70112, USA
688
+ City: New Orleans
689
+ State/province: Louisiana
690
+ Postal code: 70112
691
+ Country: United States
692
+ Map: http://maps.google.com/maps?q=29.952211,-90.080563
693
+ ```
582
694
 
583
695
  There are also a number of options for setting the geocoding API, key, and language, viewing the raw JSON response, and more. Please run `geocode -h` for details.
584
696
 
@@ -614,8 +726,10 @@ Troubleshooting
614
726
 
615
727
  If you get one of these errors:
616
728
 
617
- uninitialized constant Geocoder::Model::Mongoid
618
- uninitialized constant Geocoder::Model::Mongoid::Mongo
729
+ ```ruby
730
+ uninitialized constant Geocoder::Model::Mongoid
731
+ uninitialized constant Geocoder::Model::Mongoid::Mongo
732
+ ```
619
733
 
620
734
  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.
621
735
 
@@ -640,13 +754,17 @@ For the most part, the speed of geocoding requests has little to do with the Geo
640
754
 
641
755
  Take a look at the server's raw response. You can do this by getting the request URL in an app console:
642
756
 
643
- Geocoder::Lookup.get(:nominatim).query_url(Geocoder::Query.new("..."))
757
+ ```ruby
758
+ Geocoder::Lookup.get(:nominatim).query_url(Geocoder::Query.new("..."))
759
+ ```
644
760
 
645
761
  Replace `:nominatim` with the lookup you are using and replace `...` with the address you are trying to geocode. Then visit the returned URL in your web browser. Often the API will return an error message that helps you resolve the problem. If, after reading the raw response, you believe there is a problem with Geocoder, please post an issue and include both the URL and raw response body.
646
762
 
647
763
  You can also fetch the response in the console:
648
764
 
649
- Geocoder::Lookup.get(:nominatim).send(:fetch_raw_data, Geocoder::Query.new("..."))
765
+ ```ruby
766
+ Geocoder::Lookup.get(:nominatim).send(:fetch_raw_data, Geocoder::Query.new("..."))
767
+ ```
650
768
 
651
769
 
652
770
  Known Issues
@@ -662,14 +780,16 @@ You cannot use the `near` scope with another scope that provides an `includes` o
662
780
 
663
781
  Instead of using `includes` to reduce the number of database queries, try using `joins` with either the `:select` option or a call to `preload`. For example:
664
782
 
665
- # Pass a :select option to the near scope to get the columns you want.
666
- # Instead of City.near(...).includes(:venues), try:
667
- City.near("Omaha, NE", 20, select: "cities.*, venues.*").joins(:venues)
783
+ ```ruby
784
+ # Pass a :select option to the near scope to get the columns you want.
785
+ # Instead of City.near(...).includes(:venues), try:
786
+ City.near("Omaha, NE", 20, select: "cities.*, venues.*").joins(:venues)
668
787
 
669
- # This preload call will normally trigger two queries regardless of the
670
- # number of results; one query on hotels, and one query on administrators.
671
- # Instead of Hotel.near(...).includes(:administrator), try:
672
- Hotel.near("London, UK", 50).joins(:administrator).preload(:administrator)
788
+ # This preload call will normally trigger two queries regardless of the
789
+ # number of results; one query on hotels, and one query on administrators.
790
+ # Instead of Hotel.near(...).includes(:administrator), try:
791
+ Hotel.near("London, UK", 50).joins(:administrator).preload(:administrator)
792
+ ```
673
793
 
674
794
  If anyone has a more elegant solution to this problem I am very interested in seeing it.
675
795
 
@@ -678,29 +798,4 @@ If anyone has a more elegant solution to this problem I am very interested in se
678
798
  The `near` method will not look across the 180th meridian to find objects close to a given point. In practice this is rarely an issue outside of New Zealand and certain surrounding islands. This problem does not exist with the zero-meridian. The problem is due to a shortcoming of the Haversine formula which Geocoder uses to calculate distances.
679
799
 
680
800
 
681
- Reporting Issues
682
- ----------------
683
-
684
- When reporting an issue, please list the version of Geocoder you are using and any relevant information about your application (Rails version, database type and version, etc). Please describe as specifically as you can what behavior you are seeing (eg: an error message? a nil return value?).
685
-
686
- Please DO NOT use GitHub issues to ask questions about how to use Geocoder. Sites like [StackOverflow](http://www.stackoverflow.com/) are a better forum for such discussions.
687
-
688
-
689
- Contributing
690
- ------------
691
-
692
- Contributions are welcome via Github pull requests. If you are new to the project and looking for a way to get involved, try picking up an issue with a "beginner-task" label. Hints about what needs to be done are usually provided.
693
-
694
- For all contributions, please respect the following guidelines:
695
-
696
- * Each pull request should implement ONE feature or bugfix. If you want to add or fix more than one thing, submit more than one pull request.
697
- * Do not commit changes to files that are irrelevant to your feature or bugfix (eg: `.gitignore`).
698
- * Do not add dependencies on other gems.
699
- * Do not add unnecessary `require` statements which could cause LoadErrors on certain systems.
700
- * Remember: Geocoder needs to run outside of Rails. Don't assume things like ActiveSupport are available.
701
- * Be willing to accept criticism and work on improving your code; Geocoder is used by thousands of developers and care must be taken not to introduce bugs.
702
- * Be aware that the pull request review process is not immediate, and is generally proportional to the size of the pull request.
703
- * If your pull request is merged, please do not ask for an immediate release of the gem. There are many factors contributing to when releases occur (remember that they affect thousands of apps with Geocoder in their Gemfiles). If necessary, please install from the Github source until the next official release.
704
-
705
-
706
- Copyright (c) 2009-18 Alex Reisner, released under the MIT license.
801
+ Copyright :copyright: 2009-2021 Alex Reisner, released under the MIT license.