geocoder 1.6.6 → 1.8.5

Sign up to get free protection for your applications and to get access to all the features.
Files changed (70) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -2
  3. data/README.md +355 -211
  4. data/examples/app_defined_lookup_services.rb +22 -0
  5. data/lib/generators/geocoder/config/templates/initializer.rb +6 -1
  6. data/lib/geocoder/cache.rb +14 -35
  7. data/lib/geocoder/cache_stores/base.rb +40 -0
  8. data/lib/geocoder/cache_stores/generic.rb +35 -0
  9. data/lib/geocoder/cache_stores/redis.rb +34 -0
  10. data/lib/geocoder/configuration.rb +17 -4
  11. data/lib/geocoder/ip_address.rb +9 -0
  12. data/lib/geocoder/lookup.rb +37 -5
  13. data/lib/geocoder/lookups/abstract_api.rb +46 -0
  14. data/lib/geocoder/lookups/amap.rb +2 -2
  15. data/lib/geocoder/lookups/amazon_location_service.rb +58 -0
  16. data/lib/geocoder/lookups/azure.rb +56 -0
  17. data/lib/geocoder/lookups/ban_data_gouv_fr.rb +1 -1
  18. data/lib/geocoder/lookups/base.rb +2 -1
  19. data/lib/geocoder/lookups/bing.rb +2 -2
  20. data/lib/geocoder/lookups/esri.rb +18 -5
  21. data/lib/geocoder/lookups/freegeoip.rb +8 -6
  22. data/lib/geocoder/lookups/geoapify.rb +78 -0
  23. data/lib/geocoder/lookups/geoip2.rb +4 -0
  24. data/lib/geocoder/lookups/geoportail_lu.rb +1 -1
  25. data/lib/geocoder/lookups/google_places_details.rb +20 -0
  26. data/lib/geocoder/lookups/google_places_search.rb +21 -5
  27. data/lib/geocoder/lookups/here.rb +25 -20
  28. data/lib/geocoder/lookups/ip2location.rb +10 -6
  29. data/lib/geocoder/lookups/ip2location_io.rb +62 -0
  30. data/lib/geocoder/lookups/ip2location_lite.rb +40 -0
  31. data/lib/geocoder/lookups/ipbase.rb +49 -0
  32. data/lib/geocoder/lookups/ipdata_co.rb +1 -1
  33. data/lib/geocoder/lookups/ipqualityscore.rb +50 -0
  34. data/lib/geocoder/lookups/location_iq.rb +5 -1
  35. data/lib/geocoder/lookups/mapbox.rb +3 -3
  36. data/lib/geocoder/lookups/melissa_street.rb +41 -0
  37. data/lib/geocoder/lookups/pc_miler.rb +85 -0
  38. data/lib/geocoder/lookups/pdok_nl.rb +43 -0
  39. data/lib/geocoder/lookups/photon.rb +89 -0
  40. data/lib/geocoder/lookups/test.rb +1 -0
  41. data/lib/geocoder/lookups/twogis.rb +58 -0
  42. data/lib/geocoder/lookups/uk_ordnance_survey_names.rb +1 -1
  43. data/lib/geocoder/lookups/yandex.rb +3 -3
  44. data/lib/geocoder/query.rb +1 -1
  45. data/lib/geocoder/results/abstract_api.rb +146 -0
  46. data/lib/geocoder/results/amazon_location_service.rb +62 -0
  47. data/lib/geocoder/results/azure.rb +65 -0
  48. data/lib/geocoder/results/ban_data_gouv_fr.rb +1 -1
  49. data/lib/geocoder/results/esri.rb +5 -2
  50. data/lib/geocoder/results/geoapify.rb +179 -0
  51. data/lib/geocoder/results/here.rb +20 -25
  52. data/lib/geocoder/results/ip2location_io.rb +21 -0
  53. data/lib/geocoder/results/ip2location_lite.rb +47 -0
  54. data/lib/geocoder/results/ipbase.rb +40 -0
  55. data/lib/geocoder/results/ipqualityscore.rb +54 -0
  56. data/lib/geocoder/results/mapbox.rb +34 -10
  57. data/lib/geocoder/results/melissa_street.rb +46 -0
  58. data/lib/geocoder/results/nominatim.rb +24 -16
  59. data/lib/geocoder/results/pc_miler.rb +98 -0
  60. data/lib/geocoder/results/pdok_nl.rb +62 -0
  61. data/lib/geocoder/results/photon.rb +119 -0
  62. data/lib/geocoder/results/twogis.rb +76 -0
  63. data/lib/geocoder/version.rb +1 -1
  64. data/lib/maxmind_database.rb +12 -12
  65. data/lib/tasks/maxmind.rake +1 -1
  66. metadata +65 -11
  67. data/examples/autoexpire_cache_dalli.rb +0 -62
  68. data/examples/autoexpire_cache_redis.rb +0 -30
  69. data/lib/geocoder/lookups/dstk.rb +0 -22
  70. data/lib/geocoder/results/dstk.rb +0 -6
data/README.md CHANGED
@@ -5,7 +5,6 @@ Geocoder
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
8
 
10
9
  Key features:
11
10
 
@@ -18,9 +17,9 @@ Key features:
18
17
 
19
18
  Compatibility:
20
19
 
21
- * Ruby versions: 2.x, and JRuby.
20
+ * Ruby versions: 2.1+, and JRuby.
22
21
  * Databases: MySQL, PostgreSQL, SQLite, and MongoDB.
23
- * Rails: 4, 5, and 6.
22
+ * Rails: 5.x, 6.x, and 7.x.
24
23
  * Works outside of Rails with the `json` (for MRI) or `json_pure` (for JRuby) gem.
25
24
 
26
25
 
@@ -51,8 +50,8 @@ The Rest:
51
50
  * [Technical Discussions](#technical-discussions)
52
51
  * [Troubleshooting](#troubleshooting)
53
52
  * [Known Issues](#known-issues)
54
- * [Reporting Issues](#reporting-issues)
55
- * [Contributing](#contributing)
53
+ * [Reporting Issues](https://github.com/alexreisner/geocoder/blob/master/CONTRIBUTING.md#reporting-bugs)
54
+ * [Contributing](https://github.com/alexreisner/geocoder/blob/master/CONTRIBUTING.md#making-changes)
56
55
 
57
56
  See Also:
58
57
 
@@ -64,23 +63,29 @@ Basic Search
64
63
 
65
64
  In its simplest form, Geocoder takes an address and searches for its latitude/longitude coordinates:
66
65
 
67
- results = Geocoder.search("Paris")
68
- results.first.coordinates
69
- => [48.856614, 2.3522219] # latitude and longitude
66
+ ```ruby
67
+ results = Geocoder.search("Paris")
68
+ results.first.coordinates
69
+ # => [48.856614, 2.3522219] # latitude and longitude
70
+ ```
70
71
 
71
72
  The reverse is possible too. Given coordinates, it finds an address:
72
73
 
73
- results = Geocoder.search([48.856614, 2.3522219])
74
- results.first.address
75
- => "Hôtel de Ville, 75004 Paris, France"
74
+ ```ruby
75
+ results = Geocoder.search([48.856614, 2.3522219])
76
+ results.first.address
77
+ # => "Hôtel de Ville, 75004 Paris, France"
78
+ ```
76
79
 
77
- You can also look up the location of an IP addresses:
80
+ You can also look up the location of an IP address:
78
81
 
79
- results = Geocoder.search("172.56.21.89")
80
- results.first.coordinates
81
- => [30.267153, -97.7430608]
82
- results.first.country
83
- => "United States"
82
+ ```ruby
83
+ results = Geocoder.search("172.56.21.89")
84
+ results.first.coordinates
85
+ # => [30.267153, -97.7430608]
86
+ results.first.country
87
+ # => "United States"
88
+ ```
84
89
 
85
90
  **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).
86
91
 
@@ -92,30 +97,40 @@ To automatically geocode your objects:
92
97
 
93
98
  **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:
94
99
 
95
- def address
96
- [street, city, state, country].compact.join(', ')
97
- end
100
+ ```ruby
101
+ def address
102
+ [street, city, state, country].compact.join(', ')
103
+ end
104
+ ```
98
105
 
99
106
  **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.)
100
107
 
101
108
  **3.** In your model, tell geocoder where to find the object's address:
102
109
 
103
- geocoded_by :address
110
+ ```ruby
111
+ geocoded_by :address
112
+ ```
104
113
 
105
114
  This adds a `geocode` method which you can invoke via callback:
106
115
 
107
- after_validation :geocode
116
+ ```ruby
117
+ after_validation :geocode
118
+ ```
108
119
 
109
120
  Reverse geocoding (given lat/lon coordinates, find an address) is similar:
110
121
 
111
- reverse_geocoded_by :latitude, :longitude
112
- after_validation :reverse_geocode
122
+ ```ruby
123
+ reverse_geocoded_by :latitude, :longitude
124
+ after_validation :reverse_geocode
125
+ ```
113
126
 
114
127
  With any geocoded objects, you can do the following:
115
128
 
116
- obj.distance_to([43.9,-98.6]) # distance from obj to point
117
- obj.bearing_to([43.9,-98.6]) # bearing from obj to point
118
- obj.bearing_from(obj2) # bearing from obj2 to obj
129
+ ```ruby
130
+ obj.distance_to([43.9,-98.6]) # distance from obj to point
131
+ obj.bearing_to([43.9,-98.6]) # bearing from obj to point
132
+ obj.bearing_from(obj2) # bearing from obj2 to obj
133
+ ```
119
134
 
120
135
  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.
121
136
 
@@ -123,18 +138,24 @@ The `bearing_from/to` methods take a single argument which can be: a `[lat,lon]`
123
138
 
124
139
  Before you can call `geocoded_by` you'll need to include the necessary module using one of the following:
125
140
 
126
- include Geocoder::Model::Mongoid
127
- include Geocoder::Model::MongoMapper
141
+ ```ruby
142
+ include Geocoder::Model::Mongoid
143
+ include Geocoder::Model::MongoMapper
144
+ ```
128
145
 
129
146
  ### Latitude/Longitude Order in MongoDB
130
147
 
131
148
  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:
132
149
 
133
- obj.to_coordinates # => [37.7941013, -122.3951096] # [lat, lon]
150
+ ```ruby
151
+ obj.to_coordinates # => [37.7941013, -122.3951096] # [lat, lon]
152
+ ```
134
153
 
135
154
  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:
136
155
 
137
- obj.coordinates # => [-122.3951096, 37.7941013] # [lon, lat]
156
+ ```ruby
157
+ obj.coordinates # => [-122.3951096, 37.7941013] # [lon, lat]
158
+ ```
138
159
 
139
160
  So, be careful.
140
161
 
@@ -142,7 +163,9 @@ So, be careful.
142
163
 
143
164
  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:
144
165
 
145
- extend Geocoder::Model::ActiveRecord
166
+ ```ruby
167
+ extend Geocoder::Model::ActiveRecord
168
+ ```
146
169
 
147
170
 
148
171
  Geospatial Database Queries
@@ -152,19 +175,23 @@ Geospatial Database Queries
152
175
 
153
176
  To find objects by location, use the following scopes:
154
177
 
155
- Venue.near('Omaha, NE, US') # venues within 20 miles of Omaha
156
- Venue.near([40.71, -100.23], 50) # venues within 50 miles of a point
157
- Venue.near([40.71, -100.23], 50, units: :km) # venues within 50 kilometres of a point
158
- Venue.geocoded # venues with coordinates
159
- Venue.not_geocoded # venues without coordinates
178
+ ```ruby
179
+ Venue.near('Omaha, NE, US') # venues within 20 miles of Omaha
180
+ Venue.near([40.71, -100.23], 50) # venues within 50 miles of a point
181
+ Venue.near([40.71, -100.23], 50, units: :km) # venues within 50 kilometres of a point
182
+ Venue.geocoded # venues with coordinates
183
+ Venue.not_geocoded # venues without coordinates
184
+ ```
160
185
 
161
186
  With geocoded objects you can do things like this:
162
187
 
163
- if obj.geocoded?
164
- obj.nearbys(30) # other objects within 30 miles
165
- obj.distance_from([40.714,-100.234]) # distance from arbitrary point to object
166
- obj.bearing_to("Paris, France") # direction from object to arbitrary point
167
- end
188
+ ```ruby
189
+ if obj.geocoded?
190
+ obj.nearbys(30) # other objects within 30 miles
191
+ obj.distance_from([40.714,-100.234]) # distance from arbitrary point to object
192
+ obj.bearing_to("Paris, France") # direction from object to arbitrary point
193
+ end
194
+ ```
168
195
 
169
196
  ### For MongoDB-backed models:
170
197
 
@@ -176,8 +203,10 @@ Geocoding HTTP Requests
176
203
 
177
204
  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:
178
205
 
179
- # returns Geocoder::Result object
180
- result = request.location
206
+ ```ruby
207
+ # returns Geocoder::Result object
208
+ result = request.location
209
+ ```
181
210
 
182
211
  **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).
183
212
 
@@ -191,71 +220,82 @@ Geocoder supports a variety of street and IP address geocoding services. The def
191
220
 
192
221
  To create a Rails initializer with sample configuration:
193
222
 
194
- rails generate geocoder:config
223
+ ```sh
224
+ rails generate geocoder:config
225
+ ```
195
226
 
196
227
  Some common options are:
197
228
 
198
- # config/initializers/geocoder.rb
199
- Geocoder.configure(
229
+ ```ruby
230
+ # config/initializers/geocoder.rb
231
+ Geocoder.configure(
232
+ # street address geocoding service (default :nominatim)
233
+ lookup: :yandex,
200
234
 
201
- # street address geocoding service (default :nominatim)
202
- lookup: :yandex,
235
+ # IP address geocoding service (default :ipinfo_io)
236
+ ip_lookup: :maxmind,
203
237
 
204
- # IP address geocoding service (default :ipinfo_io)
205
- ip_lookup: :maxmind,
238
+ # to use an API key:
239
+ api_key: "...",
206
240
 
207
- # to use an API key:
208
- api_key: "...",
241
+ # geocoding service request timeout, in seconds (default 3):
242
+ timeout: 5,
209
243
 
210
- # geocoding service request timeout, in seconds (default 3):
211
- timeout: 5,
244
+ # set default units to kilometers:
245
+ units: :km,
212
246
 
213
- # set default units to kilometers:
214
- units: :km,
215
-
216
- # caching (see Caching section below for details):
217
- cache: Redis.new,
218
- cache_prefix: "..."
219
-
220
- )
247
+ # caching (see Caching section below for details):
248
+ cache: Redis.new,
249
+ cache_options: {
250
+ expiration: 1.day, # Defaults to `nil`
251
+ prefix: "another_key:" # Defaults to `geocoder:`
252
+ }
253
+ )
254
+ ```
221
255
 
222
256
  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:
223
257
 
224
- # with Google:
225
- Geocoder.search("Middletown", bounds: [[40.6,-77.9], [39.9,-75.9]])
258
+ ```ruby
259
+ # with Google:
260
+ Geocoder.search("Middletown", bounds: [[40.6,-77.9], [39.9,-75.9]])
261
+ ```
226
262
 
227
263
  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:
228
264
 
229
- # Nominatim's `countrycodes` parameter:
230
- Geocoder.search("Rome", params: {countrycodes: "us,ca"})
265
+ ```ruby
266
+ # Nominatim's `countrycodes` parameter:
267
+ Geocoder.search("Rome", params: {countrycodes: "us,ca"})
231
268
 
232
- # Google's `region` parameter:
233
- Geocoder.search("Rome", params: {region: "..."})
269
+ # Google's `region` parameter:
270
+ Geocoder.search("Rome", params: {region: "..."})
271
+ ```
234
272
 
235
273
  ### Configuring Multiple Services
236
274
 
237
275
  You can configure multiple geocoding services at once by using the service's name as a key for a sub-configuration hash, like this:
238
276
 
239
- Geocoder.configure(
277
+ ```ruby
278
+ Geocoder.configure(
240
279
 
241
- timeout: 2,
242
- cache: Redis.new,
280
+ timeout: 2,
281
+ cache: Redis.new,
243
282
 
244
- yandex: {
245
- api_key: "...",
246
- timeout: 5
247
- },
283
+ yandex: {
284
+ api_key: "...",
285
+ timeout: 5
286
+ },
248
287
 
249
- baidu: {
250
- api_key: "..."
251
- },
288
+ baidu: {
289
+ api_key: "..."
290
+ },
252
291
 
253
- maxmind: {
254
- api_key: "...",
255
- service: :omni
256
- }
292
+ maxmind: {
293
+ api_key: "...",
294
+ service: :omni
295
+ }
257
296
 
258
- )
297
+ )
298
+ ```
259
299
 
260
300
  Lookup-specific settings override global settings so, in this example, the timeout for all lookups is 2 seconds, except for Yandex which is 5.
261
301
 
@@ -267,12 +307,16 @@ Performance and Optimization
267
307
 
268
308
  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:
269
309
 
270
- add_index :table, [:latitude, :longitude]
310
+ ```ruby
311
+ add_index :table, [:latitude, :longitude]
312
+ ```
271
313
 
272
314
  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:
273
315
 
274
- include Geocoder::Model::Mongoid
275
- geocoded_by :address, skip_index: true
316
+ ```ruby
317
+ include Geocoder::Model::Mongoid
318
+ geocoded_by :address, skip_index: true
319
+ ```
276
320
 
277
321
  ### Avoiding Unnecessary API Requests
278
322
 
@@ -283,13 +327,17 @@ Geocoding only needs to be performed under certain conditions. To avoid unnecess
283
327
 
284
328
  The exact code will vary depending on the method you use for your geocodable string, but it would be something like this:
285
329
 
286
- after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }
330
+ ```ruby
331
+ after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }
332
+ ```
287
333
 
288
334
  ### Caching
289
335
 
290
336
  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:
291
337
 
292
- Geocoder.configure(cache: Redis.new)
338
+ ```ruby
339
+ Geocoder.configure(cache: Redis.new)
340
+ ```
293
341
 
294
342
  This example uses Redis, but the cache store can be any object that supports these methods:
295
343
 
@@ -300,71 +348,94 @@ This example uses Redis, but the cache store can be any object that supports the
300
348
 
301
349
  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).
302
350
 
351
+ When using Rails use the Generic cache store as an adapter around `Rails.cache`:
352
+
353
+ ```ruby
354
+ Geocoder.configure(cache: Geocoder::CacheStore::Generic.new(Rails.cache, {}))
355
+ ```
356
+
303
357
  You can also set a custom prefix to be used for cache keys:
304
358
 
305
- Geocoder.configure(cache_prefix: "...")
359
+ ```ruby
360
+ Geocoder.configure(cache_options: { prefix: "..." })
361
+ ```
306
362
 
307
363
  By default the prefix is `geocoder:`
308
364
 
309
365
  If you need to expire cached content:
310
366
 
311
- Geocoder::Lookup.get(Geocoder.config[:lookup]).cache.expire(:all) # expire cached results for current Lookup
312
- Geocoder::Lookup.get(:nominatim).cache.expire("http://...") # expire cached result for a specific URL
313
- Geocoder::Lookup.get(:nominatim).cache.expire(:all) # expire cached results for Google Lookup
314
- # expire all cached results for all Lookups.
315
- # Be aware that this methods spawns a new Lookup object for each Service
316
- Geocoder::Lookup.all_services.each{|service| Geocoder::Lookup.get(service).cache.expire(:all)}
367
+ ```ruby
368
+ Geocoder::Lookup.get(Geocoder.config[:lookup]).cache.expire(:all) # expire cached results for current Lookup
369
+ Geocoder::Lookup.get(:nominatim).cache.expire("http://...") # expire cached result for a specific URL
370
+ Geocoder::Lookup.get(:nominatim).cache.expire(:all) # expire cached results for Nominatim
371
+ # expire all cached results for all Lookups.
372
+ # Be aware that this methods spawns a new Lookup object for each Service
373
+ Geocoder::Lookup.all_services.each{|service| Geocoder::Lookup.get(service).cache.expire(:all)}
374
+ ```
317
375
 
318
376
  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.
319
377
 
320
- For an example of a cache store with URL expiry, please see examples/autoexpire_cache.rb
378
+ In addition to conventional cache stores like Redis, it's possible to keep your cache in the database using `ActiveRecord`. For example see [this gist](https://gist.github.com/shqear93/4b07153b4ca7e4e4a41da492679f6c0e).
379
+
321
380
 
322
381
  _Before you implement caching in your app please be sure that doing so does not violate the Terms of Service for your geocoding service._
323
382
 
383
+ Not all services support caching, [check the service limitations in the API guide for more information](https://github.com/alexreisner/geocoder/blob/master/README_API_GUIDE.md).
324
384
 
325
385
  Advanced Model Configuration
326
386
  ----------------------------
327
387
 
328
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:
329
389
 
330
- geocoded_by :address, latitude: :lat, longitude: :lon # ActiveRecord
331
- 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
+ ```
332
394
 
333
395
  For reverse geocoding, you can specify the attribute where the address will be stored. For example:
334
396
 
335
- reverse_geocoded_by :latitude, :longitude, address: :loc # ActiveRecord
336
- 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
+ ```
337
401
 
338
402
  To specify geocoding parameters in your model:
339
403
 
340
- geocoded_by :address, params: {region: "..."}
404
+ ```ruby
405
+ geocoded_by :address, params: {region: "..."}
406
+ ```
341
407
 
342
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:
343
409
 
344
- geocoded_by :address, lookup: lambda{ |obj| obj.geocoder_lookup }
410
+ ```ruby
411
+ geocoded_by :address, lookup: lambda{ |obj| obj.geocoder_lookup }
345
412
 
346
- def geocoder_lookup
347
- if country_code == "RU"
348
- :yandex
349
- elsif country_code == "CN"
350
- :baidu
351
- else
352
- :nominatim
353
- end
354
- 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
+ ```
355
423
 
356
424
  ### Custom Result Handling
357
425
 
358
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:
359
427
 
360
- reverse_geocoded_by :latitude, :longitude do |obj,results|
361
- if geo = results.first
362
- obj.city = geo.city
363
- obj.zipcode = geo.postal_code
364
- obj.country = geo.country_code
365
- end
366
- end
367
- 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
+ ```
368
439
 
369
440
  Every `Geocoder::Result` object, `result`, provides the following data:
370
441
 
@@ -390,23 +461,26 @@ You can apply both forward and reverse geocoding to the same model (i.e. users c
390
461
 
391
462
  For example:
392
463
 
393
- class Venue
464
+ ```ruby
465
+ class Venue
466
+ # build an address from street, city, and state attributes
467
+ geocoded_by :address_from_components
394
468
 
395
- # build an address from street, city, and state attributes
396
- geocoded_by :address_from_components
397
-
398
- # store the fetched address in the full_address attribute
399
- reverse_geocoded_by :latitude, :longitude, address: :full_address
400
- end
469
+ # store the fetched address in the full_address attribute
470
+ reverse_geocoded_by :latitude, :longitude, address: :full_address
471
+ end
472
+ ```
401
473
 
402
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:
403
475
 
404
- class Venue
405
- geocoded_by :address,
406
- latitude: :fetched_latitude,
407
- longitude: :fetched_longitude
408
- reverse_geocoded_by :latitude, :longitude
409
- 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
+ ```
410
484
 
411
485
 
412
486
  Advanced Database Queries
@@ -416,21 +490,29 @@ Advanced Database Queries
416
490
 
417
491
  The default `near` search looks for objects within a circle. To search within a doughnut or ring use the `:min_radius` option:
418
492
 
419
- Venue.near("Austin, TX", 200, min_radius: 40)
493
+ ```ruby
494
+ Venue.near("Austin, TX", 200, min_radius: 40)
495
+ ```
420
496
 
421
497
  To search within a rectangle (note that results will *not* include `distance` and `bearing` attributes):
422
498
 
423
- sw_corner = [40.71, 100.23]
424
- ne_corner = [36.12, 88.65]
425
- 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
+ ```
426
504
 
427
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:
428
506
 
429
- Venue.near([40.71, 99.23], :effective_radius)
507
+ ```ruby
508
+ Venue.near([40.71, 99.23], :effective_radius)
509
+ ```
430
510
 
431
511
  If you store multiple sets of coordinates for each object, you can specify latitude and longitude columns to use for a search:
432
512
 
433
- Venue.near("Paris", 50, latitude: :secondary_latitude, longitude: :secondary_longitude)
513
+ ```ruby
514
+ Venue.near("Paris", 50, latitude: :secondary_latitude, longitude: :secondary_longitude)
515
+ ```
434
516
 
435
517
  ### Distance and Bearing
436
518
 
@@ -450,9 +532,11 @@ Results are automatically sorted by distance from the search point, closest to f
450
532
 
451
533
  You can convert these to compass point names via provided method:
452
534
 
453
- Geocoder::Calculations.compass_point(355) # => "N"
454
- Geocoder::Calculations.compass_point(45) # => "NE"
455
- 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
+ ```
456
540
 
457
541
  _Note: when running queries on SQLite, `distance` and `bearing` are provided for consistency only. They are not very accurate._
458
542
 
@@ -464,13 +548,15 @@ Geospatial Calculations
464
548
 
465
549
  The `Geocoder::Calculations` module contains some useful methods:
466
550
 
467
- # find the distance between two arbitrary points
468
- Geocoder::Calculations.distance_between([47.858205,2.294359], [40.748433,-73.985655])
469
- => 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)
470
555
 
471
- # find the geographic center (aka center of gravity) of objects or points
472
- Geocoder::Calculations.geographic_center([city1, city2, [40.22,-73.99], city4])
473
- => [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
+ ```
474
560
 
475
561
  See [the code](https://github.com/alexreisner/geocoder/blob/master/lib/geocoder/calculations.rb) for more!
476
562
 
@@ -480,19 +566,27 @@ Batch Geocoding
480
566
 
481
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:
482
568
 
483
- rake geocode:all CLASS=YourModel
569
+ ```sh
570
+ rake geocode:all CLASS=YourModel
571
+ ```
484
572
 
485
573
  If you need reverse geocoding instead, call the task with REVERSE=true:
486
574
 
487
- rake geocode:all CLASS=YourModel REVERSE=true
575
+ ```sh
576
+ rake geocode:all CLASS=YourModel REVERSE=true
577
+ ```
488
578
 
489
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:
490
580
 
491
- rake geocode:all CLASS=YourModel SLEEP=0.25 BATCH=100
581
+ ```sh
582
+ rake geocode:all CLASS=YourModel SLEEP=0.25 BATCH=100
583
+ ```
492
584
 
493
585
  To avoid exceeding per-day limits you can add a `LIMIT` option. However, this will ignore the `BATCH` value, if provided.
494
586
 
495
- rake geocode:all CLASS=YourModel LIMIT=1000
587
+ ```sh
588
+ rake geocode:all CLASS=YourModel LIMIT=1000
589
+ ```
496
590
 
497
591
 
498
592
  Testing
@@ -500,42 +594,50 @@ Testing
500
594
 
501
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`
502
596
 
503
- Geocoder.configure(lookup: :test, ip_lookup: :test)
597
+ ```ruby
598
+ Geocoder.configure(lookup: :test, ip_lookup: :test)
599
+ ```
504
600
 
505
601
  Add stubs to define the results that will be returned:
506
602
 
507
- Geocoder::Lookup::Test.add_stub(
508
- "New York, NY", [
509
- {
510
- 'coordinates' => [40.7143528, -74.0059731],
511
- 'address' => 'New York, NY, USA',
512
- 'state' => 'New York',
513
- 'state_code' => 'NY',
514
- 'country' => 'United States',
515
- 'country_code' => 'US'
516
- }
517
- ]
518
- )
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
+ ```
519
617
 
520
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:
521
619
 
522
- Geocoder::Lookup::Test.set_default_stub(
523
- [
524
- {
525
- 'coordinates' => [40.7143528, -74.0059731],
526
- 'address' => 'New York, NY, USA',
527
- 'state' => 'New York',
528
- 'state_code' => 'NY',
529
- 'country' => 'United States',
530
- 'country_code' => 'US'
531
- }
532
- ]
533
- )
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
+ ```
534
634
 
535
635
  You may also delete a single stub, or reset all stubs _including the default stub_:
536
636
 
537
- Geocoder::Lookup::Test.delete_stub('New York, NY')
538
- Geocoder::Lookup::Test.reset
637
+ ```ruby
638
+ Geocoder::Lookup::Test.delete_stub('New York, NY')
639
+ Geocoder::Lookup::Test.reset
640
+ ```
539
641
 
540
642
  Notes:
541
643
 
@@ -548,21 +650,27 @@ Error Handling
548
650
 
549
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:
550
652
 
551
- Geocoder.configure(always_raise: [SocketError, Timeout::Error])
653
+ ```ruby
654
+ Geocoder.configure(always_raise: [SocketError, Timeout::Error])
655
+ ```
552
656
 
553
657
  You can also do this to raise all exceptions:
554
658
 
555
- Geocoder.configure(always_raise: :all)
659
+ ```ruby
660
+ Geocoder.configure(always_raise: :all)
661
+ ```
556
662
 
557
663
  The raise-able exceptions are:
558
664
 
559
- SocketError
560
- Timeout::Error
561
- Geocoder::OverQueryLimitError
562
- Geocoder::RequestDenied
563
- Geocoder::InvalidRequest
564
- Geocoder::InvalidApiKey
565
- 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
+ ```
566
674
 
567
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.
568
676
 
@@ -572,15 +680,17 @@ Command Line Interface
572
680
 
573
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:
574
682
 
575
- $ geocode 29.951,-90.081
576
- Latitude: 29.952211
577
- Longitude: -90.080563
578
- Full address: 1500 Sugar Bowl Dr, New Orleans, LA 70112, USA
579
- City: New Orleans
580
- State/province: Louisiana
581
- Postal code: 70112
582
- Country: United States
583
- 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
+ ```
584
694
 
585
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.
586
696
 
@@ -616,8 +726,10 @@ Troubleshooting
616
726
 
617
727
  If you get one of these errors:
618
728
 
619
- uninitialized constant Geocoder::Model::Mongoid
620
- uninitialized constant Geocoder::Model::Mongoid::Mongo
729
+ ```ruby
730
+ uninitialized constant Geocoder::Model::Mongoid
731
+ uninitialized constant Geocoder::Model::Mongoid::Mongo
732
+ ```
621
733
 
622
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.
623
735
 
@@ -625,8 +737,34 @@ you should check your Gemfile to make sure the Mongoid gem is listed _before_ Ge
625
737
 
626
738
  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:
627
739
 
628
- * using the `pluck` method (selects only a single column)
629
- * specifying another model through `includes` (selects columns from other tables)
740
+ * using [`select` method (selects one or more columns)](https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-select)
741
+ * using the [`pluck` method (gets an array with selecting one or more columns)](https://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck)
742
+ * The same problem will appear with [ActiveRecord's `ids` method](https://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-ids).
743
+ * specifying another model through [`includes` (selects columns from other tables)](https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-includes)
744
+ * See also Known Issues [using-near-with-includes](#using-near-with-select) section.
745
+
746
+ If you get an error in the above cases, try the following:
747
+
748
+ ```ruby
749
+ # Use the :select option with the near scope to get the columns you want.
750
+ # Instead of City.near(...).select(:id, :name), try:
751
+ City.near("Omaha, NE", 20, select: "id, name")
752
+
753
+ # Pass a :select option to the near scope to get the columns you want.
754
+ # Then, Ruby's built-in pluck method gets arrays you want.
755
+ # Instead of City.near(...).pluck(:id) or City.near(...).ids,, try:
756
+ City.near("Omaha, NE", 20, select: "id, name").to_a.pluck(:id, :name)
757
+ City.near("Omaha, NE", 20, select: "id").to_a.pluck(:id)
758
+
759
+ # Pass a :select option to the near scope to get the columns you want.
760
+ # Instead of City.near(...).includes(:venues), try:
761
+ City.near("Omaha, NE", 20, select: "cities.*, venues.*").joins(:venues)
762
+
763
+ # This preload call will normally trigger two queries regardless of the
764
+ # number of results; one query on hotels, and one query on administrators.
765
+ # Instead of Hotel.near(...).includes(:administrator), try:
766
+ Hotel.near("London, UK", 50).joins(:administrator).preload(:administrator)
767
+ ```
630
768
 
631
769
  ### Geocoding is Slow
632
770
 
@@ -636,19 +774,23 @@ If your application requires quick geocoding responses you will probably need to
636
774
 
637
775
  For IP address lookups in Rails applications, it is generally NOT a good idea to run `request.location` during a synchronous page load without understanding the speed/behavior of your configured lookup. If the lookup becomes slow, so will your website.
638
776
 
639
- For the most part, the speed of geocoding requests has little to do with the Geocoder gem. Please take the time to learn about your configured lookup (links to documentation are provided above) before posting performance-related issues.
777
+ For the most part, the speed of geocoding requests has little to do with the Geocoder gem. Please take the time to learn about your configured lookup before posting performance-related issues.
640
778
 
641
779
  ### Unexpected Responses from Geocoding Services
642
780
 
643
781
  Take a look at the server's raw response. You can do this by getting the request URL in an app console:
644
782
 
645
- Geocoder::Lookup.get(:nominatim).query_url(Geocoder::Query.new("..."))
783
+ ```ruby
784
+ Geocoder::Lookup.get(:nominatim).query_url(Geocoder::Query.new("..."))
785
+ ```
646
786
 
647
787
  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.
648
788
 
649
789
  You can also fetch the response in the console:
650
790
 
651
- Geocoder::Lookup.get(:nominatim).send(:fetch_raw_data, Geocoder::Query.new("..."))
791
+ ```ruby
792
+ Geocoder::Lookup.get(:nominatim).send(:fetch_raw_data, Geocoder::Query.new("..."))
793
+ ```
652
794
 
653
795
 
654
796
  Known Issues
@@ -664,14 +806,16 @@ You cannot use the `near` scope with another scope that provides an `includes` o
664
806
 
665
807
  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:
666
808
 
667
- # Pass a :select option to the near scope to get the columns you want.
668
- # Instead of City.near(...).includes(:venues), try:
669
- City.near("Omaha, NE", 20, select: "cities.*, venues.*").joins(:venues)
809
+ ```ruby
810
+ # Pass a :select option to the near scope to get the columns you want.
811
+ # Instead of City.near(...).includes(:venues), try:
812
+ City.near("Omaha, NE", 20, select: "cities.*, venues.*").joins(:venues)
670
813
 
671
- # This preload call will normally trigger two queries regardless of the
672
- # number of results; one query on hotels, and one query on administrators.
673
- # Instead of Hotel.near(...).includes(:administrator), try:
674
- Hotel.near("London, UK", 50).joins(:administrator).preload(:administrator)
814
+ # This preload call will normally trigger two queries regardless of the
815
+ # number of results; one query on hotels, and one query on administrators.
816
+ # Instead of Hotel.near(...).includes(:administrator), try:
817
+ Hotel.near("London, UK", 50).joins(:administrator).preload(:administrator)
818
+ ```
675
819
 
676
820
  If anyone has a more elegant solution to this problem I am very interested in seeing it.
677
821