broken-geocoder 1.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +467 -0
  3. data/LICENSE +20 -0
  4. data/README.md +1193 -0
  5. data/bin/geocode +5 -0
  6. data/examples/autoexpire_cache_dalli.rb +62 -0
  7. data/examples/autoexpire_cache_redis.rb +28 -0
  8. data/examples/cache_bypass.rb +48 -0
  9. data/examples/reverse_geocode_job.rb +40 -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/generators/geocoder/maxmind/geolite_city_generator.rb +28 -0
  13. data/lib/generators/geocoder/maxmind/geolite_country_generator.rb +28 -0
  14. data/lib/generators/geocoder/maxmind/templates/migration/geolite_city.rb +30 -0
  15. data/lib/generators/geocoder/maxmind/templates/migration/geolite_country.rb +17 -0
  16. data/lib/geocoder.rb +48 -0
  17. data/lib/geocoder/cache.rb +90 -0
  18. data/lib/geocoder/calculations.rb +431 -0
  19. data/lib/geocoder/cli.rb +121 -0
  20. data/lib/geocoder/configuration.rb +129 -0
  21. data/lib/geocoder/configuration_hash.rb +11 -0
  22. data/lib/geocoder/esri_token.rb +38 -0
  23. data/lib/geocoder/exceptions.rb +37 -0
  24. data/lib/geocoder/ip_address.rb +13 -0
  25. data/lib/geocoder/kernel_logger.rb +25 -0
  26. data/lib/geocoder/logger.rb +47 -0
  27. data/lib/geocoder/lookup.rb +110 -0
  28. data/lib/geocoder/lookups/baidu.rb +59 -0
  29. data/lib/geocoder/lookups/baidu_ip.rb +59 -0
  30. data/lib/geocoder/lookups/base.rb +325 -0
  31. data/lib/geocoder/lookups/bing.rb +80 -0
  32. data/lib/geocoder/lookups/dstk.rb +20 -0
  33. data/lib/geocoder/lookups/esri.rb +64 -0
  34. data/lib/geocoder/lookups/freegeoip.rb +51 -0
  35. data/lib/geocoder/lookups/geocoder_ca.rb +53 -0
  36. data/lib/geocoder/lookups/geocoder_us.rb +43 -0
  37. data/lib/geocoder/lookups/geocodio.rb +42 -0
  38. data/lib/geocoder/lookups/geoip2.rb +45 -0
  39. data/lib/geocoder/lookups/geoportail_lu.rb +65 -0
  40. data/lib/geocoder/lookups/google.rb +91 -0
  41. data/lib/geocoder/lookups/google_places_details.rb +50 -0
  42. data/lib/geocoder/lookups/google_premier.rb +47 -0
  43. data/lib/geocoder/lookups/here.rb +62 -0
  44. data/lib/geocoder/lookups/ipapi_com.rb +86 -0
  45. data/lib/geocoder/lookups/ipinfo_io.rb +55 -0
  46. data/lib/geocoder/lookups/latlon.rb +59 -0
  47. data/lib/geocoder/lookups/mapbox.rb +53 -0
  48. data/lib/geocoder/lookups/mapquest.rb +59 -0
  49. data/lib/geocoder/lookups/mapzen.rb +15 -0
  50. data/lib/geocoder/lookups/maxmind.rb +90 -0
  51. data/lib/geocoder/lookups/maxmind_geoip2.rb +69 -0
  52. data/lib/geocoder/lookups/maxmind_local.rb +65 -0
  53. data/lib/geocoder/lookups/nominatim.rb +52 -0
  54. data/lib/geocoder/lookups/okf.rb +44 -0
  55. data/lib/geocoder/lookups/opencagedata.rb +58 -0
  56. data/lib/geocoder/lookups/ovi.rb +62 -0
  57. data/lib/geocoder/lookups/pelias.rb +64 -0
  58. data/lib/geocoder/lookups/pointpin.rb +68 -0
  59. data/lib/geocoder/lookups/postcode_anywhere_uk.rb +51 -0
  60. data/lib/geocoder/lookups/smarty_streets.rb +50 -0
  61. data/lib/geocoder/lookups/telize.rb +55 -0
  62. data/lib/geocoder/lookups/test.rb +44 -0
  63. data/lib/geocoder/lookups/yandex.rb +58 -0
  64. data/lib/geocoder/models/active_record.rb +50 -0
  65. data/lib/geocoder/models/base.rb +39 -0
  66. data/lib/geocoder/models/mongo_base.rb +62 -0
  67. data/lib/geocoder/models/mongo_mapper.rb +26 -0
  68. data/lib/geocoder/models/mongoid.rb +32 -0
  69. data/lib/geocoder/query.rb +111 -0
  70. data/lib/geocoder/railtie.rb +26 -0
  71. data/lib/geocoder/request.rb +83 -0
  72. data/lib/geocoder/results/baidu.rb +79 -0
  73. data/lib/geocoder/results/baidu_ip.rb +62 -0
  74. data/lib/geocoder/results/base.rb +67 -0
  75. data/lib/geocoder/results/bing.rb +52 -0
  76. data/lib/geocoder/results/dstk.rb +6 -0
  77. data/lib/geocoder/results/esri.rb +75 -0
  78. data/lib/geocoder/results/freegeoip.rb +45 -0
  79. data/lib/geocoder/results/geocoder_ca.rb +60 -0
  80. data/lib/geocoder/results/geocoder_us.rb +39 -0
  81. data/lib/geocoder/results/geocodio.rb +70 -0
  82. data/lib/geocoder/results/geoip2.rb +62 -0
  83. data/lib/geocoder/results/geoportail_lu.rb +69 -0
  84. data/lib/geocoder/results/google.rb +139 -0
  85. data/lib/geocoder/results/google_places_details.rb +35 -0
  86. data/lib/geocoder/results/google_premier.rb +6 -0
  87. data/lib/geocoder/results/here.rb +71 -0
  88. data/lib/geocoder/results/ipapi_com.rb +45 -0
  89. data/lib/geocoder/results/ipinfo_io.rb +48 -0
  90. data/lib/geocoder/results/latlon.rb +71 -0
  91. data/lib/geocoder/results/mapbox.rb +47 -0
  92. data/lib/geocoder/results/mapquest.rb +48 -0
  93. data/lib/geocoder/results/mapzen.rb +5 -0
  94. data/lib/geocoder/results/maxmind.rb +135 -0
  95. data/lib/geocoder/results/maxmind_geoip2.rb +9 -0
  96. data/lib/geocoder/results/maxmind_local.rb +49 -0
  97. data/lib/geocoder/results/nominatim.rb +99 -0
  98. data/lib/geocoder/results/okf.rb +106 -0
  99. data/lib/geocoder/results/opencagedata.rb +90 -0
  100. data/lib/geocoder/results/ovi.rb +71 -0
  101. data/lib/geocoder/results/pelias.rb +58 -0
  102. data/lib/geocoder/results/pointpin.rb +40 -0
  103. data/lib/geocoder/results/postcode_anywhere_uk.rb +42 -0
  104. data/lib/geocoder/results/smarty_streets.rb +106 -0
  105. data/lib/geocoder/results/telize.rb +45 -0
  106. data/lib/geocoder/results/test.rb +33 -0
  107. data/lib/geocoder/results/yandex.rb +92 -0
  108. data/lib/geocoder/sql.rb +107 -0
  109. data/lib/geocoder/stores/active_record.rb +305 -0
  110. data/lib/geocoder/stores/base.rb +116 -0
  111. data/lib/geocoder/stores/mongo_base.rb +58 -0
  112. data/lib/geocoder/stores/mongo_mapper.rb +13 -0
  113. data/lib/geocoder/stores/mongoid.rb +13 -0
  114. data/lib/geocoder/version.rb +3 -0
  115. data/lib/hash_recursive_merge.rb +74 -0
  116. data/lib/maxmind_database.rb +109 -0
  117. data/lib/tasks/geocoder.rake +38 -0
  118. data/lib/tasks/maxmind.rake +73 -0
  119. metadata +167 -0
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.
@@ -0,0 +1,1193 @@
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 (finding 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
+ _Please note that this README is for the current `HEAD` and may document features not present in the latest gem release. For this reason, you may want to instead view the README for your particular version._
7
+
8
+
9
+ Compatibility
10
+ -------------
11
+
12
+ * Supports multiple Ruby versions: Ruby 1.9.3, 2.x, JRuby, and Rubinius.
13
+ * Supports multiple databases: MySQL, PostgreSQL, SQLite, and MongoDB (1.7.0 and higher).
14
+ * Supports Rails 3 and 4. If you need to use it with Rails 2 please see the `rails2` branch (no longer maintained, limited feature set).
15
+ * Works very well outside of Rails, you just need to install either the `json` (for MRI) or `json_pure` (for JRuby) gem.
16
+
17
+
18
+ Rails 4.1 Note
19
+ --------------
20
+
21
+ Due to [a change in ActiveRecord's `count` method](https://github.com/rails/rails/pull/10710) you will need to use `count(:all)` to explicitly count all columns ("*") when using a `near` scope. Using `near` and calling `count` with no argument will cause exceptions in many cases.
22
+
23
+
24
+ Installation
25
+ ------------
26
+
27
+ Install Geocoder like any other Ruby gem:
28
+
29
+ gem install geocoder
30
+
31
+ Or, if you're using Rails/Bundler, add this to your Gemfile:
32
+
33
+ gem 'geocoder'
34
+
35
+ and run at the command prompt:
36
+
37
+ bundle install
38
+
39
+
40
+ Object Geocoding
41
+ ----------------
42
+
43
+ ### ActiveRecord
44
+
45
+ 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):
46
+
47
+ rails generate migration AddLatitudeAndLongitudeToModel latitude:float longitude:float
48
+ rake db:migrate
49
+
50
+ For 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`).
51
+
52
+ Next, your model must tell Geocoder which method returns your object's geocodable address:
53
+
54
+ geocoded_by :full_street_address # can also be an IP address
55
+ after_validation :geocode # auto-fetch coordinates
56
+
57
+ For reverse geocoding, tell Geocoder which attributes store latitude and longitude:
58
+
59
+ reverse_geocoded_by :latitude, :longitude
60
+ after_validation :reverse_geocode # auto-fetch address
61
+
62
+ ### Mongoid
63
+
64
+ First, your model must have an array field for storing coordinates:
65
+
66
+ field :coordinates, :type => Array
67
+
68
+ You may also want an address field, like this:
69
+
70
+ field :address
71
+
72
+ 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.
73
+
74
+ Once your fields are defined, include the `Geocoder::Model::Mongoid` module and then call `geocoded_by`:
75
+
76
+ include Geocoder::Model::Mongoid
77
+ geocoded_by :address # can also be an IP address
78
+ after_validation :geocode # auto-fetch coordinates
79
+
80
+ Reverse geocoding is similar:
81
+
82
+ include Geocoder::Model::Mongoid
83
+ reverse_geocoded_by :coordinates
84
+ after_validation :reverse_geocode # auto-fetch address
85
+
86
+ Once you've set up your model you'll need to create the necessary spatial indices in your database:
87
+
88
+ rake db:mongoid:create_indexes
89
+
90
+ 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.
91
+
92
+ ### MongoMapper
93
+
94
+ MongoMapper is very similar to Mongoid, just be sure to include `Geocoder::Model::MongoMapper`.
95
+
96
+ ### Mongo Indices
97
+
98
+ 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:
99
+
100
+ include Geocoder::Model::Mongoid
101
+ geocoded_by :address, :skip_index => true
102
+
103
+ ### Bulk Geocoding
104
+
105
+ 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:
106
+
107
+ rake geocode:all CLASS=YourModel
108
+
109
+ If you need reverse geocoding instead, call the task with REVERSE=true:
110
+
111
+ rake geocode:all CLASS=YourModel REVERSE=true
112
+
113
+ Geocoder will print warnings if you exceed the rate limit for your geocoding service. Some services — Google notably — 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:
114
+
115
+ rake geocode:all CLASS=YourModel SLEEP=0.25 BATCH=100
116
+
117
+ ### Avoiding Unnecessary API Requests
118
+
119
+ Geocoding only needs to be performed under certain conditions. To avoid unnecessary work (and quota usage) you will probably want to geocode an object only when:
120
+
121
+ * an address is present
122
+ * the address has been changed since last save (or it has never been saved)
123
+
124
+ The exact code will vary depending on the method you use for your geocodable string, but it would be something like this:
125
+
126
+ after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }
127
+
128
+
129
+ Request Geocoding by IP Address
130
+ -------------------------------
131
+
132
+ 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:
133
+
134
+ # returns Geocoder::Result object
135
+ result = request.location
136
+
137
+ **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).
138
+
139
+ Note that these methods will usually return `nil` in your test and development environments because things like "localhost" and "0.0.0.0" are not an Internet IP addresses.
140
+
141
+ See _Advanced Geocoding_ below for more information about `Geocoder::Result` objects.
142
+
143
+
144
+ Location-Aware Database Queries
145
+ -------------------------------
146
+
147
+ ### For Mongo-backed models:
148
+
149
+ Please use MongoDB's [geospatial query language](https://docs.mongodb.org/manual/reference/command/geoNear/). Mongoid also provides [a DSL](http://mongoid.github.io/en/mongoid/docs/querying.html#geo_near) for doing near queries.
150
+
151
+ ### For ActiveRecord models:
152
+
153
+ To find objects by location, use the following scopes:
154
+
155
+ Venue.near('Omaha, NE, US', 20) # venues within 20 miles of Omaha
156
+ Venue.near([40.71, -100.23], 20) # venues within 20 miles of a point
157
+ Venue.near([40.71, -100.23], 20, :units => :km)
158
+ # venues within 20 kilometres of a point
159
+ Venue.geocoded # venues with coordinates
160
+ Venue.not_geocoded # venues without coordinates
161
+
162
+ by default, objects are ordered by distance. To remove the ORDER BY clause use the following:
163
+
164
+ Venue.near('Omaha', 20, :order => false)
165
+
166
+ With geocoded objects you can do things like this:
167
+
168
+ if obj.geocoded?
169
+ obj.nearbys(30) # other objects within 30 miles
170
+ obj.distance_from([40.714,-100.234]) # distance from arbitrary point to object
171
+ obj.bearing_to("Paris, France") # direction from object to arbitrary point
172
+ end
173
+
174
+ Some utility methods are also available:
175
+
176
+ # look up coordinates of some location (like searching Google Maps)
177
+ Geocoder.coordinates("25 Main St, Cooperstown, NY")
178
+ => [42.700149, -74.922767]
179
+
180
+ # distance between Eiffel Tower and Empire State Building
181
+ Geocoder::Calculations.distance_between([47.858205,2.294359], [40.748433,-73.985655])
182
+ => 3619.77359999382 # in configured units (default miles)
183
+
184
+ # find the geographic center (aka center of gravity) of objects or points
185
+ Geocoder::Calculations.geographic_center([city1, city2, [40.22,-73.99], city4])
186
+ => [35.14968, -90.048929]
187
+
188
+ Please see the code for more methods and detailed information about arguments (eg, working with kilometers).
189
+
190
+
191
+ Distance and Bearing
192
+ --------------------
193
+
194
+ When you run a location-aware query the returned objects have two attributes added to them (only w/ ActiveRecord):
195
+
196
+ * `obj.distance` - number of miles from the search point to this object
197
+ * `obj.bearing` - direction from the search point to this object
198
+
199
+ 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:
200
+
201
+ * `0` - due north
202
+ * `180` - due south
203
+ * `90` - due east
204
+ * `270` - due west
205
+ * `230.1` - southwest
206
+ * `359.9` - almost due north
207
+
208
+ You can convert these numbers to compass point names by using the utility method provided:
209
+
210
+ Geocoder::Calculations.compass_point(355) # => "N"
211
+ Geocoder::Calculations.compass_point(45) # => "NE"
212
+ Geocoder::Calculations.compass_point(208) # => "SW"
213
+
214
+ _Note: when using SQLite `distance` and `bearing` values are provided for interface consistency only. They are not very accurate._
215
+
216
+ To calculate accurate distance and bearing with SQLite or MongoDB:
217
+
218
+ obj.distance_to([43.9,-98.6]) # distance from obj to point
219
+ obj.bearing_to([43.9,-98.6]) # bearing from obj to point
220
+ obj.bearing_from(obj2) # bearing from obj2 to obj
221
+
222
+ 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).
223
+
224
+
225
+ Model Configuration
226
+ -------------------
227
+
228
+ 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:
229
+
230
+ geocoded_by :address, :latitude => :lat, :longitude => :lon # ActiveRecord
231
+ geocoded_by :address, :coordinates => :coords # MongoDB
232
+
233
+ The `address` method can return any string you'd use to search Google Maps. For example, any of the following are acceptable:
234
+
235
+ * "714 Green St, Big Town, MO"
236
+ * "Eiffel Tower, Paris, FR"
237
+ * "Paris, TX, US"
238
+
239
+ If your model has `street`, `city`, `state`, and `country` attributes you might do something like this:
240
+
241
+ geocoded_by :address
242
+
243
+ def address
244
+ [street, city, state, country].compact.join(', ')
245
+ end
246
+
247
+ For reverse geocoding you can also specify an alternate name attribute where the address will be stored, for example:
248
+
249
+ reverse_geocoded_by :latitude, :longitude, :address => :location # ActiveRecord
250
+ reverse_geocoded_by :coordinates, :address => :loc # MongoDB
251
+
252
+ You can also configure a specific lookup for your model which will override the globally-configured lookup, for example:
253
+
254
+ geocoded_by :address, :lookup => :yandex
255
+
256
+ You can also specify a proc if you want to choose a lookup based on a specific property of an object, for example you can use specialized lookups for different regions:
257
+
258
+ geocoded_by :address, :lookup => lambda{ |obj| obj.geocoder_lookup }
259
+
260
+ def geocoder_lookup
261
+ if country_code == "RU"
262
+ :yandex
263
+ elsif country_code == "CN"
264
+ :baidu
265
+ else
266
+ :google
267
+ end
268
+ end
269
+
270
+
271
+ Advanced Querying
272
+ -----------------
273
+
274
+ 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:
275
+
276
+ distance = 20
277
+ center_point = [40.71, 100.23]
278
+ box = Geocoder::Calculations.bounding_box(center_point, distance)
279
+ Venue.within_bounding_box(box)
280
+
281
+ 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. Note that `#near` performs both bounding box and radius queries for speed.
282
+
283
+ You can also specify a minimum radius (if you're using ActiveRecord and not Sqlite) to constrain the
284
+ lower bound (ie. think of a donut, or ring) by using the `:min_radius` option:
285
+
286
+ box = Geocoder::Calculations.bounding_box(center_point, distance, :min_radius => 10.5)
287
+
288
+ With ActiveRecord, you can specify alternate latitude and longitude column names for a geocoded model (useful if you store multiple sets of coordinates for each object):
289
+
290
+ Venue.near("Paris", 50, latitude: :secondary_latitude, longitude: :secondary_longitude)
291
+
292
+
293
+ Advanced Geocoding
294
+ ------------------
295
+
296
+ 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:
297
+
298
+ reverse_geocoded_by :latitude, :longitude do |obj,results|
299
+ if geo = results.first
300
+ obj.city = geo.city
301
+ obj.zipcode = geo.postal_code
302
+ obj.country = geo.country_code
303
+ end
304
+ end
305
+ after_validation :reverse_geocode
306
+
307
+ Every `Geocoder::Result` object, `result`, provides the following data:
308
+
309
+ * `result.latitude` - float
310
+ * `result.longitude` - float
311
+ * `result.coordinates` - array of the above two in the form of `[lat,lon]`
312
+ * `result.address` - string
313
+ * `result.city` - string
314
+ * `result.state` - string
315
+ * `result.state_code` - string
316
+ * `result.postal_code` - string
317
+ * `result.country` - string
318
+ * `result.country_code` - string
319
+
320
+ If you're familiar with the results returned by the geocoding service you're using you can access even more data (call the `#data` method of any Geocoder::Result object to get the full parsed response), 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.)
321
+
322
+
323
+ Geocoding Service ("Lookup") Configuration
324
+ ------------------------------------------
325
+
326
+ Geocoder supports a variety of street and IP address geocoding services. The default lookups are `:google` for street addresses and `:freegeoip` for IP addresses. Please see the listing and comparison below for details on specific geocoding services (not all settings are supported by all services).
327
+
328
+ To create a Rails initializer with an example configuration:
329
+
330
+ rails generate geocoder:config
331
+
332
+ Some common configuration options are:
333
+
334
+ # config/initializers/geocoder.rb
335
+ Geocoder.configure(
336
+
337
+ # geocoding service (see below for supported options):
338
+ :lookup => :yandex,
339
+
340
+ # IP address geocoding service (see below for supported options):
341
+ :ip_lookup => :maxmind,
342
+
343
+ # to use an API key:
344
+ :api_key => "...",
345
+
346
+ # geocoding service request timeout, in seconds (default 3):
347
+ :timeout => 5,
348
+
349
+ # set default units to kilometers:
350
+ :units => :km,
351
+
352
+ # caching (see below for details):
353
+ :cache => Redis.new,
354
+ :cache_prefix => "..."
355
+
356
+ )
357
+
358
+ 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:
359
+
360
+ # with Google:
361
+ Geocoder.search("Paris", :bounds => [[32.1,-95.9], [33.9,-94.3]])
362
+
363
+ 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:
364
+
365
+ # with Nominatim:
366
+ Geocoder.search("Paris", :params => {:countrycodes => "gb,de,fr,es,us"})
367
+
368
+ Or, to search within a particular region with Google:
369
+
370
+ Geocoder.search("...", :params => {:region => "..."})
371
+
372
+ You can also configure multiple geocoding services at once, like this:
373
+
374
+ Geocoder.configure(
375
+
376
+ :timeout => 2,
377
+ :cache => Redis.new,
378
+
379
+ :yandex => {
380
+ :api_key => "...",
381
+ :timeout => 5
382
+ },
383
+
384
+ :baidu => {
385
+ :api_key => "..."
386
+ },
387
+
388
+ :maxmind => {
389
+ :api_key => "...",
390
+ :service => :omni
391
+ }
392
+
393
+ )
394
+
395
+ The above combines global and service-specific options and could be useful if you specify different geocoding services for different models or under different conditions. Lookup-specific settings override global settings so, for example, in the above the timeout for all lookups would be 2 seconds, except for Yandex which would be 5.
396
+
397
+
398
+ ### Street Address Services
399
+
400
+ 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.
401
+
402
+ #### Google (`:google`)
403
+
404
+ * **API key**: optional, but quota is higher if key is used (use of key requires HTTPS so be sure to set: `:use_https => true` in `Geocoder.configure`)
405
+ * **Key signup**: https://console.developers.google.com//flows/enableapi?apiid=geocoding_backend&keyType=SERVER_SIDE
406
+ * **Quota**: 2,500 requests/24 hrs, 5 requests/second
407
+ * **Region**: world
408
+ * **SSL support**: yes (required if key is used)
409
+ * **Languages**: see https://developers.google.com/maps/faq#languagesupport
410
+ * **Extra options**: `:bounds` - pass SW and NE coordinates as an array of two arrays to bias results towards a viewport
411
+ * **Documentation**: https://developers.google.com/maps/documentation/geocoding/intro
412
+ * **Terms of Service**: http://code.google.com/apis/maps/terms.html#section_10_12
413
+ * **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..."
414
+
415
+ #### Google Maps API for Work (`:google_premier`)
416
+
417
+ Similar to `:google`, with the following differences:
418
+
419
+ * **API key**: required, plus client and channel (set `Geocoder.configure(:lookup => :google_premier, :api_key => [key, client, channel])`)
420
+ * **Key signup**: https://developers.google.com/maps/documentation/business/
421
+ * **Quota**: 100,000 requests/24 hrs, 10 requests/second
422
+
423
+ #### Google Places Details (`:google_places_details`)
424
+
425
+ The [Google Places Details API](https://developers.google.com/places/documentation/details) is not, strictly speaking, a geocoding service. It accepts a Google `place_id` and returns address information, ratings and reviews. A `place_id` can be obtained from the Google Places Autocomplete API and should be passed to Geocoder as the first search argument: `Geocoder.search("ChIJhRwB-yFawokR5Phil-QQ3zM", :lookup => :google_places_details)`.
426
+
427
+ * **API key**: required
428
+ * **Key signup**: https://code.google.com/apis/console/
429
+ * **Quota**: 1,000 request/day, 100,000 after credit card authentication
430
+ * **Region**: world
431
+ * **SSL support**: yes
432
+ * **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)
433
+ * **Documentation**: https://developers.google.com/places/documentation/details
434
+ * **Terms of Service**: https://developers.google.com/places/policies
435
+ * **Limitations**: "If your application displays Places API data on a page or view that does not also display a Google Map, you must show a "Powered by Google" logo with that data."
436
+
437
+ #### Bing (`:bing`)
438
+
439
+ * **API key**: required (set `Geocoder.configure(:lookup => :bing, :api_key => key)`)
440
+ * **Key signup**: https://www.microsoft.com/maps/create-a-bing-maps-key.aspx
441
+ * **Quota**: 50,0000 requests/day (Windows app), 125,000 requests/year (non-Windows app)
442
+ * **Region**: world
443
+ * **SSL support**: no
444
+ * **Languages**: ?
445
+ * **Documentation**: http://msdn.microsoft.com/en-us/library/ff701715.aspx
446
+ * **Terms of Service**: http://www.microsoft.com/maps/product/terms.html
447
+ * **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."
448
+
449
+ #### Nominatim (`:nominatim`)
450
+
451
+ * **API key**: none
452
+ * **Quota**: 1 request/second
453
+ * **Region**: world
454
+ * **SSL support**: no
455
+ * **Languages**: ?
456
+ * **Documentation**: http://wiki.openstreetmap.org/wiki/Nominatim
457
+ * **Terms of Service**: http://wiki.openstreetmap.org/wiki/Nominatim_usage_policy
458
+ * **Limitations**: Please limit request rate to 1 per second and include your contact information in User-Agent headers (eg: `Geocoder.configure(:http_headers => { "User-Agent" => "your contact info" })`). [Data licensed under Open Database License (ODbL) (you must provide attribution).](http://www.openstreetmap.org/copyright)
459
+
460
+ #### OpenCageData (`:opencagedata`)
461
+
462
+ * **API key**: required
463
+ * **Key signup**: http://geocoder.opencagedata.com
464
+ * **Quota**: 2500 requests / day, then ability to purchase more (free during beta)
465
+ * **Region**: world
466
+ * **SSL support**: yes
467
+ * **Languages**: worldwide
468
+ * **Documentation**: http://geocoder.opencagedata.com/api.html
469
+ * **Limitations**: [Data licensed under Open Database License (ODbL) (you must provide attribution).](http://www.openstreetmap.org/copyright)
470
+
471
+ #### Yandex (`:yandex`)
472
+
473
+ * **API key**: optional, but without it lookup is territorially limited
474
+ * **Quota**: 25000 requests / day
475
+ * **Region**: world with API key. Otherwise restricted to Russia, Ukraine, Belarus, Kazakhstan, Georgia, Abkhazia, South Ossetia, Armenia, Azerbaijan, Moldova, Turkmenistan, Tajikistan, Uzbekistan, Kyrgyzstan and Turkey
476
+ * **SSL support**: HTTPS only
477
+ * **Languages**: Russian, Belarusian, Ukrainian, English, Turkish (only for maps of Turkey)
478
+ * **Documentation**: http://api.yandex.com.tr/maps/doc/intro/concepts/intro.xml
479
+ * **Terms of Service**: http://api.yandex.com.tr/maps/doc/intro/concepts/intro.xml#rules
480
+ * **Limitations**: ?
481
+
482
+ #### Geocoder.ca (`:geocoder_ca`)
483
+
484
+ * **API key**: none
485
+ * **Quota**: ?
486
+ * **Region**: US and Canada
487
+ * **SSL support**: no
488
+ * **Languages**: English
489
+ * **Documentation**: ?
490
+ * **Terms of Service**: http://geocoder.ca/?terms=1
491
+ * **Limitations**: "Under no circumstances can our data be re-distributed or re-sold by anyone to other parties without our written permission."
492
+
493
+ #### Geocoder.us (`:geocoder_us`)
494
+
495
+ * **API key**: HTTP Basic Auth
496
+ * **Sign up**: http://geocoder.us/user/signup
497
+ * **Quota**: You can purchase 20,000 credits at a time for $50
498
+ * **Region**: US
499
+ * **SSL support**: no
500
+ * **Languages**: English
501
+ * **Documentation**: http://geocoder.us/help/
502
+ * **Terms of Service**: http://geocoder.us/terms.shtml
503
+ * **Limitations**: ?
504
+
505
+ #### Mapbox (`:mapbox`)
506
+
507
+ * **API key**: required
508
+ * **Dataset**: Uses `mapbox.places` dataset by default. Specific the `mapbox.places-permanent` dataset by setting: `Geocoder.configure(:mapbox => {:dataset => "mapbox.places-permanent"})`
509
+ * **Key signup**: https://www.mapbox.com/pricing/
510
+ * **Quota**: depends on plan
511
+ * **Region**: complete coverage of US and Canada, partial coverage elsewhere (see for details: https://www.mapbox.com/developers/api/geocoding/#coverage)
512
+ * **SSL support**: yes
513
+ * **Languages**: English
514
+ * **Documentation**: https://www.mapbox.com/developers/api/geocoding/
515
+ * **Terms of Service**: https://www.mapbox.com/tos/
516
+ * **Limitations**: For `mapbox.places` dataset, must be displayed on a Mapbox map; Cache results for up to 30 days. For `mapbox.places-permanent` dataset, depends on plan.
517
+ * **Notes**: Currently in public beta.
518
+
519
+ #### Mapquest (`:mapquest`)
520
+
521
+ * **API key**: required
522
+ * **Key signup**: https://developer.mapquest.com/plans
523
+ * **Quota**: ?
524
+ * **HTTP Headers**: when using the licensed API you can specify a referer like so:
525
+ `Geocoder.configure(:http_headers => { "Referer" => "http://foo.com" })`
526
+ * **Region**: world
527
+ * **SSL support**: no
528
+ * **Languages**: English
529
+ * **Documentation**: http://www.mapquestapi.com/geocoding/
530
+ * **Terms of Service**: http://info.mapquest.com/terms-of-use/
531
+ * **Limitations**: ?
532
+ * **Notes**: You can use the open (non-licensed) API by setting: `Geocoder.configure(:mapquest => {:open => true})` (defaults to licensed version)
533
+
534
+ #### Ovi/Nokia (`:ovi`)
535
+
536
+ * **API key**: not required, but performance restricted without it
537
+ * **Quota**: ?
538
+ * **Region**: world
539
+ * **SSL support**: no
540
+ * **Languages**: English
541
+ * **Documentation**: http://api.maps.ovi.com/devguide/overview.html
542
+ * **Terms of Service**: http://www.developer.nokia.com/Develop/Maps/TC.html
543
+ * **Limitations**: ?
544
+
545
+ #### Here/Nokia (`:here`)
546
+
547
+ * **API key**: required (set `Geocoder.configure(:api_key => [app_id, app_code])`)
548
+ * **Quota**: Depending on the API key
549
+ * **Region**: world
550
+ * **SSL support**: yes
551
+ * **Languages**: The preferred language of address elements in the result. Language code must be provided according to RFC 4647 standard.
552
+ * **Documentation**: http://developer.here.com/rest-apis/documentation/geocoder
553
+ * **Terms of Service**: http://developer.here.com/faqs#l&t
554
+ * **Limitations**: ?
555
+
556
+ #### ESRI (`:esri`)
557
+
558
+ * **API key**: optional (set `Geocoder.configure(:esri => {:api_key => ["client_id", "client_secret"]})`)
559
+ * **Quota**: Required for some scenarios (see Terms of Service)
560
+ * **Region**: world
561
+ * **SSL support**: yes
562
+ * **Languages**: English
563
+ * **Documentation**: https://developers.arcgis.com/rest/geocode/api-reference/overview-world-geocoding-service.htm
564
+ * **Terms of Service**: http://www.esri.com/legal/software-license
565
+ * **Limitations**: Requires API key if results will be stored. Using API key will also remove rate limit.
566
+ * **Notes**: You can specify which projection you want to use by setting, for example: `Geocoder.configure(:esri => {:outSR => 102100})`. If you will store results, set the flag and provide API key: `Geocoder.configure(:esri => {:api_key => ["client_id", "client_secret"], :for_storage => true})`. If you want to, you can also supply an ESRI token directly: `Geocoder.configure(:esri => {:token => Geocoder::EsriToken.new('TOKEN', Time.now + 1.day})`
567
+
568
+ #### Mapzen (`:mapzen`)
569
+
570
+ * **API key**: required
571
+ * **Quota**: 6/sec, up to 30k per day, paid plan info at https://mapzen.com/documentation/search/api-keys-rate-limits/#rate-limits
572
+ * **Region**: world
573
+ * **SSL support**: yes
574
+ * **Languages**: en
575
+ * **Documentation**: https://mapzen.com/documentation/search/search/
576
+ * **Terms of Service**: http://mapzen.com/terms
577
+ * **Limitations**: ?
578
+ * **Notes**: Mapzen is the primary author of Pelias and offers Pelias-as-a-service in free and paid versions https://mapzen.com/pelias.
579
+
580
+ #### Pelias (`:pelias`)
581
+
582
+ * **API key**: required
583
+ * **Quota**: none (self-hosted service)
584
+ * **Region**: world
585
+ * **SSL support**: yes
586
+ * **Languages**: en
587
+ * **Documentation**: https://mapzen.com/documentation/search/search/
588
+ * **Terms of Service**: http://mapzen.com/terms
589
+ * **Limitations**: See terms
590
+ * **Notes**: Configure your self-hosted pelias with the `endpoint` option: `Geocoder.configure(:lookup => :pelias, :api_key => 'your_api_key', :pelias => {:endpoint => 'self.hosted/pelias'})`. Defaults to `localhost`.
591
+
592
+ #### Data Science Toolkit (`:dstk`)
593
+
594
+ Data Science Toolkit provides an API whose reponse format is like Google's but which can be set up as a privately hosted service.
595
+
596
+ * **API key**: none
597
+ * **Quota**: None quota if you are self-hosting the service.
598
+ * **Region**: world
599
+ * **SSL support**: ?
600
+ * **Languages**: en
601
+ * **Documentation**: http://www.datasciencetoolkit.org/developerdocs
602
+ * **Terms of Service**: http://www.datasciencetoolkit.org/developerdocs#googlestylegeocoder
603
+ * **Limitations**: No reverse geocoding.
604
+ * **Notes**: If you are hosting your own DSTK server you will need to configure the host name, eg: `Geocoder.configure(:lookup => :dstk, :host => "localhost:4567")`.
605
+
606
+ #### Baidu (`:baidu`)
607
+
608
+ * **API key**: required
609
+ * **Quota**: No quota limits for geocoding
610
+ * **Region**: China
611
+ * **SSL support**: no
612
+ * **Languages**: Chinese (Simplified)
613
+ * **Documentation**: http://developer.baidu.com/map/webservice-geocoding.htm
614
+ * **Terms of Service**: http://developer.baidu.com/map/law.htm
615
+ * **Limitations**: Only good for non-commercial use. For commercial usage please check http://developer.baidu.com/map/question.htm#qa0013
616
+ * **Notes**: To use Baidu set `Geocoder.configure(:lookup => :baidu, :api_key => "your_api_key")`.
617
+
618
+ #### Geocodio (`:geocodio`)
619
+
620
+ * **API key**: required
621
+ * **Quota**: 2,500 free requests/day then purchase $.001 for each, also has volume pricing and plans
622
+ * **Region**: US
623
+ * **SSL support**: yes
624
+ * **Languages**: en
625
+ * **Documentation**: http://geocod.io/docs
626
+ * **Terms of Service**: http://geocod.io/terms-of-use
627
+ * **Limitations**: No restrictions on use
628
+
629
+ #### SmartyStreets (`:smarty_streets`)
630
+
631
+ * **API key**: requires auth_id and auth_token (set `Geocoder.configure(:api_key => [id, token])`)
632
+ * **Quota**: 10,000 free, 250/month then purchase at sliding scale.
633
+ * **Region**: US
634
+ * **SSL support**: yes (required)
635
+ * **Languages**: en
636
+ * **Documentation**: http://smartystreets.com/kb/liveaddress-api/rest-endpoint
637
+ * **Terms of Service**: http://smartystreets.com/legal/terms-of-service
638
+ * **Limitations**: No reverse geocoding.
639
+
640
+
641
+ #### OKF Geocoder (`:okf`)
642
+
643
+ * **API key**: none
644
+ * **Quota**: none
645
+ * **Region**: FI
646
+ * **SSL support**: no
647
+ * **Languages**: fi
648
+ * **Documentation**: http://books.okf.fi/geocoder/_full/
649
+ * **Terms of Service**: http://www.itella.fi/liitteet/palvelutjatuotteet/yhteystietopalvelut/Postinumeropalvelut-Palvelukuvausjakayttoehdot.pdf
650
+ * **Limitations**: ?
651
+
652
+ #### Geoportail.lu (`:geoportail_lu`)
653
+
654
+ * **API key**: none
655
+ * **Quota**: none
656
+ * **Region**: LU
657
+ * **SSL support**: yes
658
+ * **Languages**: en
659
+ * **Documentation**: http://wiki.geoportail.lu/doku.php?id=en:api
660
+ * **Terms of Service**: http://wiki.geoportail.lu/doku.php?id=en:mcg_1
661
+ * **Limitations**: ?
662
+
663
+ #### PostcodeAnywhere Uk (`:postcode_anywhere_uk`)
664
+
665
+ This uses the PostcodeAnywhere UK Geocode service, this will geocode any string from UK postcode, placename, point of interest or location.
666
+
667
+ * **API key**: required
668
+ * **Quota**: Dependant on service plan?
669
+ * **Region**: UK
670
+ * **SSL support**: yes
671
+ * **Languages**: English
672
+ * **Documentation**: [http://www.postcodeanywhere.co.uk/Support/WebService/Geocoding/UK/Geocode/2/](http://www.postcodeanywhere.co.uk/Support/WebService/Geocoding/UK/Geocode/2/)
673
+ * **Terms of Service**: ?
674
+ * **Limitations**: ?
675
+ * **Notes**: To use PostcodeAnywhere you must include an API key: `Geocoder.configure(:lookup => :postcode_anywhere_uk, :api_key => 'your_api_key')`.
676
+
677
+ #### LatLon.io (`:latlon`)
678
+
679
+ * **API key**: required
680
+ * **Quota**: Depends on the user's plan (free and paid plans available)
681
+ * **Region**: US
682
+ * **SSL support**: yes
683
+ * **Languages**: en
684
+ * **Documentation**: https://latlon.io/documentation
685
+ * **Terms of Service**: ?
686
+ * **Limitations**: No restrictions on use
687
+
688
+
689
+ ### IP Address Services
690
+
691
+ #### FreeGeoIP (`:freegeoip`)
692
+
693
+ * **API key**: none
694
+ * **Quota**: 10000 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.
695
+ * **Region**: world
696
+ * **SSL support**: no
697
+ * **Languages**: English
698
+ * **Documentation**: http://github.com/fiorix/freegeoip/blob/master/README.md
699
+ * **Terms of Service**: ?
700
+ * **Limitations**: ?
701
+ * **Notes**: If you are [running your own local instance of the FreeGeoIP service](https://github.com/fiorix/freegeoip) you can configure the host like this: `Geocoder.configure(freegeoip: {host: "..."})`.
702
+
703
+ #### Pointpin (`:pointpin`)
704
+
705
+ * **API key**: required
706
+ * **Quota**: 50,000/mo for €9 through 1m/mo for €49
707
+ * **Region**: world
708
+ * **SSL support**: yes
709
+ * **Languages**: English
710
+ * **Documentation**: https://pointp.in/docs/get-started
711
+ * **Terms of Service**: https://pointp.in/terms
712
+ * **Limitations**: ?
713
+ * **Notes**: To use Pointpin set `Geocoder.configure(:ip_lookup => :pointpin, :api_key => "your_pointpin_api_key")`.
714
+
715
+ #### Telize (`:telize`)
716
+
717
+ * **API key**: required
718
+ * **Quota**: 1,000/day for $7/mo through 100,000/day for $100/mo
719
+ * **Region**: world
720
+ * **SSL support**: yes
721
+ * **Languages**: English
722
+ * **Documentation**: https://market.mashape.com/fcambus/telize
723
+ * **Terms of Service**: ?
724
+ * **Limitations**: ?
725
+ * **Notes**: To use Telize set `Geocoder.configure(:ip_lookup => :telize, :api_key => "your_api_key")`.
726
+
727
+ #### MaxMind Legacy Web Services (`:maxmind`)
728
+
729
+ * **API key**: required
730
+ * **Quota**: Request Packs can be purchased
731
+ * **Region**: world
732
+ * **SSL support**: yes
733
+ * **Languages**: English
734
+ * **Documentation**: http://dev.maxmind.com/geoip/legacy/web-services/
735
+ * **Terms of Service**: ?
736
+ * **Limitations**: ?
737
+ * **Notes**: You must specify which MaxMind service you are using in your configuration. For example: `Geocoder.configure(:maxmind => {:service => :omni})`.
738
+
739
+ #### Baidu IP (`:baidu_ip`)
740
+
741
+ * **API key**: required
742
+ * **Quota**: No quota limits for geocoding
743
+ * **Region**: China
744
+ * **SSL support**: no
745
+ * **Languages**: Chinese (Simplified)
746
+ * **Documentation**: http://developer.baidu.com/map/webservice-geocoding.htm
747
+ * **Terms of Service**: http://developer.baidu.com/map/law.htm
748
+ * **Limitations**: Only good for non-commercial use. For commercial usage please check http://developer.baidu.com/map/question.htm#qa0013
749
+ * **Notes**: To use Baidu set `Geocoder.configure(:lookup => :baidu_ip, :api_key => "your_api_key")`.
750
+
751
+ #### MaxMind GeoIP2 Precision Web Services (`:maxmind_geoip2`)
752
+
753
+ * **API key**: required
754
+ * **Quota**: Request Packs can be purchased
755
+ * **Region**: world
756
+ * **SSL support**: yes
757
+ * **Languages**: English
758
+ * **Documentation**: http://dev.maxmind.com/geoip/geoip2/web-services/
759
+ * **Terms of Service**: ?
760
+ * **Limitations**: ?
761
+ * **Notes**: You must specify which MaxMind service you are using in your configuration, and also basic authentication. For example: `Geocoder.configure(:maxmind_geoip2 => {:service => :country, :basic_auth => {:user => '', :password => ''}})`.
762
+
763
+ #### IPInfo.io (`:ipinfo_io`)
764
+
765
+ * **API key**: optional - see http://ipinfo.io/pricing
766
+ * **Quota**: 1,000/day - more with api key
767
+ * **Region**: world
768
+ * **SSL support**: no (not without access key - see http://ipinfo.io/pricing)
769
+ * **Languages**: English
770
+ * **Documentation**: http://ipinfo.io/developers
771
+ * **Terms of Service**: http://ipinfo.io/developers
772
+
773
+ #### IP-API.com (`:ipapi_com`)
774
+
775
+ * **API key**: optional - see http://ip-api.com/docs/#usage_limits
776
+ * **Quota**: 150/minute - unlimited with api key
777
+ * **Region**: world
778
+ * **SSL support**: no (not without access key - see https://signup.ip-api.com/)
779
+ * **Languages**: English
780
+ * **Documentation**: http://ip-api.com/docs/
781
+ * **Terms of Service**: https://signup.ip-api.com/terms
782
+
783
+ ### IP Address Local Database Services
784
+
785
+ #### MaxMind Local (`:maxmind_local`) - EXPERIMENTAL
786
+
787
+ This lookup provides methods for geocoding IP addresses without making a call to a remote API (improves speed and availability). It works, but support is new and should not be considered production-ready. Please [report any bugs](https://github.com/alexreisner/geocoder/issues) you encounter.
788
+
789
+ * **API key**: none (requires the GeoLite City database which can be downloaded from [MaxMind](http://dev.maxmind.com/geoip/legacy/geolite/))
790
+ * **Quota**: none
791
+ * **Region**: world
792
+ * **SSL support**: N/A
793
+ * **Languages**: English
794
+ * **Documentation**: http://www.maxmind.com/en/city
795
+ * **Terms of Service**: ?
796
+ * **Limitations**: ?
797
+ * **Notes**: There are two supported formats for MaxMind local data: binary file, and CSV file imported into an SQL database. **You must download a database from MaxMind and set either the `:file` or `:package` configuration option for local lookups to work.**
798
+
799
+ **To use a binary file** you must add the *geoip* (or *jgeoip* for JRuby) gem to your Gemfile or have it installed in your system, and specify the path of the MaxMind database in your configuration. For example:
800
+
801
+ Geocoder.configure(ip_lookup: :maxmind_local, maxmind_local: {file: File.join('folder', 'GeoLiteCity.dat')})
802
+
803
+ **To use a CSV file** you must import it into an SQL database. The GeoLite *City* and *Country* packages are supported. Configure like so:
804
+
805
+ Geocoder.configure(ip_lookup: :maxmind_local, maxmind_local: {package: :city})
806
+
807
+ You can generate ActiveRecord migrations and download and import data via provided rake tasks:
808
+
809
+ # generate migration to create tables
810
+ rails generate geocoder:maxmind:geolite_city
811
+
812
+ # download, unpack, and import data
813
+ rake geocoder:maxmind:geolite:load PACKAGE=city
814
+
815
+ You can replace `city` with `country` in any of the above tasks, generators, and configurations.
816
+
817
+ #### GeoLite2 (`:geoip2`)
818
+
819
+ This lookup provides methods for geocoding IP addresses without making a call to a remote API (improves speed and availability). It works, but support is new and should not be considered production-ready. Please [report any bugs](https://github.com/alexreisner/geocoder/issues) you encounter.
820
+
821
+ * **API key**: none (requires a GeoIP2 or free GeoLite2 City or Country binary database which can be downloaded from [MaxMind](http://dev.maxmind.com/geoip/geoip2/))
822
+ * **Quota**: none
823
+ * **Region**: world
824
+ * **SSL support**: N/A
825
+ * **Languages**: English
826
+ * **Documentation**: http://www.maxmind.com/en/city
827
+ * **Terms of Service**: ?
828
+ * **Limitations**: ?
829
+ * **Notes**: **You must download a binary database file from MaxMind and set the `:file` configuration option.** The CSV format databases are not yet supported since they are still in alpha stage. Set the path to the database file in your configuration:
830
+
831
+ Geocoder.configure(
832
+ ip_lookup: :geoip2,
833
+ geoip2: {
834
+ file: File.join('folder', 'GeoLite2-City.mmdb')
835
+ }
836
+ )
837
+
838
+ You must add either the *[hive_geoip2](https://rubygems.org/gems/hive_geoip2)* gem (native extension that relies on libmaxminddb) or the *[maxminddb](http://rubygems.org/gems/maxminddb)* gem (pure Ruby implementation) to your Gemfile or have it installed in your system. The pure Ruby gem (maxminddb) will be used by default. To use `hive_geoip2`:
839
+
840
+ Geocoder.configure(
841
+ ip_lookup: :geoip2,
842
+ geoip2: {
843
+ lib: 'hive_geoip2',
844
+ file: File.join('folder', 'GeoLite2-City.mmdb')
845
+ }
846
+ )
847
+
848
+ Caching
849
+ -------
850
+
851
+ 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:
852
+
853
+ Geocoder.configure(:cache => Redis.new)
854
+
855
+ This example uses Redis, but the cache store can be any object that supports these methods:
856
+
857
+ * `store#[](key)` or `#get` or `#read` - retrieves a value
858
+ * `store#[]=(key, value)` or `#set` or `#write` - stores a value
859
+ * `store#del(url)` - deletes a value
860
+
861
+ 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).
862
+
863
+ You can also set a custom prefix to be used for cache keys:
864
+
865
+ Geocoder.configure(:cache_prefix => "...")
866
+
867
+ By default the prefix is `geocoder:`
868
+
869
+ If you need to expire cached content:
870
+
871
+ Geocoder::Lookup.get(Geocoder.config[:lookup]).cache.expire(:all) # expire cached results for current Lookup
872
+ Geocoder::Lookup.get(:google).cache.expire("http://...") # expire cached result for a specific URL
873
+ Geocoder::Lookup.get(:google).cache.expire(:all) # expire cached results for Google Lookup
874
+ # expire all cached results for all Lookups.
875
+ # Be aware that this methods spawns a new Lookup object for each Service
876
+ Geocoder::Lookup.all_services.each{|service| Geocoder::Lookup.get(service).cache.expire(:all)}
877
+
878
+ 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).
879
+
880
+ For an example of a cache store with URL expiry please see examples/autoexpire_cache.rb
881
+
882
+ _Before you implement caching in your app please be sure that doing so does not violate the Terms of Service for your geocoding service._
883
+
884
+
885
+ Forward and Reverse Geocoding in the Same Model
886
+ -----------------------------------------------
887
+
888
+ 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:
889
+
890
+ * one for storing the fetched address (reverse geocoding)
891
+ * one for providing an address to use when fetching coordinates (forward geocoding)
892
+
893
+ For example:
894
+
895
+ class Venue
896
+
897
+ # build an address from street, city, and state attributes
898
+ geocoded_by :address_from_components
899
+
900
+ # store the fetched address in the full_address attribute
901
+ reverse_geocoded_by :latitude, :longitude, :address => :full_address
902
+ end
903
+
904
+ However, there can be only one set of latitude/longitude attributes, and whichever you specify last will be used. For example:
905
+
906
+ class Venue
907
+
908
+ geocoded_by :address,
909
+ :latitude => :fetched_latitude, # this will be overridden by the below
910
+ :longitude => :fetched_longitude # same here
911
+
912
+ reverse_geocoded_by :latitude, :longitude
913
+ end
914
+
915
+ The reason for this is that we don't want ambiguity when doing distance calculations. We need a single, authoritative source for coordinates!
916
+
917
+ Once both forward and reverse geocoding has been applied, it is possible to call them sequentially.
918
+
919
+ For example:
920
+
921
+ class Venue
922
+
923
+ after_validation :geocode, :reverse_geocode
924
+
925
+ end
926
+
927
+ For certain geolocation services such as Google geolocation API this may cause issues during subsequent updates to database records if the longtitude and latitude coordinates cannot be associated known location address (on a large body of water for example). On subsequent callbacks the following call:
928
+
929
+ after_validation :geocode
930
+
931
+ will alter the longtitude and latitude attributes based on the location field, which would be the closest known location to the original coordinates. In this case it is better to add conditions to each call, as not to override coordinates that do not have known location addresses associated with them.
932
+
933
+ For example:
934
+
935
+ class Venue
936
+
937
+ after_validation :reverse_geocode, :if => :has_coordinates
938
+ after_validation :geocode, :if => :has_location, :unless => :has_coordinates
939
+
940
+ end
941
+
942
+ Use Outside of Rails
943
+ --------------------
944
+
945
+ You can use Geocoder outside of Rails by calling the `Geocoder.search` method:
946
+
947
+ results = Geocoder.search("McCarren Park, Brooklyn, NY")
948
+
949
+ This returns an array of `Geocoder::Result` objects with all data provided by the geocoding service.
950
+
951
+
952
+ Testing Apps that Use Geocoder
953
+ ------------------------------
954
+
955
+ 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:
956
+
957
+ Geocoder.configure(:lookup => :test)
958
+
959
+ Geocoder::Lookup::Test.add_stub(
960
+ "New York, NY", [
961
+ {
962
+ 'latitude' => 40.7143528,
963
+ 'longitude' => -74.0059731,
964
+ 'address' => 'New York, NY, USA',
965
+ 'state' => 'New York',
966
+ 'state_code' => 'NY',
967
+ 'country' => 'United States',
968
+ 'country_code' => 'US'
969
+ }
970
+ ]
971
+ )
972
+
973
+ Now, any time Geocoder looks up "New York, NY" its results array will contain one result with the above attributes. You can also set a default stub, to be returned when no other stub is found for a given query:
974
+
975
+ Geocoder.configure(:lookup => :test)
976
+
977
+ Geocoder::Lookup::Test.set_default_stub(
978
+ [
979
+ {
980
+ 'latitude' => 40.7143528,
981
+ 'longitude' => -74.0059731,
982
+ 'address' => 'New York, NY, USA',
983
+ 'state' => 'New York',
984
+ 'state_code' => 'NY',
985
+ 'country' => 'United States',
986
+ 'country_code' => 'US'
987
+ }
988
+ ]
989
+ )
990
+
991
+ Note:
992
+ Keys must be strings not symbols when calling `add_stub` or `set_default_stub`. For example `'latitude' =>` not `:latitude =>`.
993
+
994
+
995
+ Command Line Interface
996
+ ----------------------
997
+
998
+ 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:
999
+
1000
+ $ geocode 29.951,-90.081
1001
+ Latitude: 29.952211
1002
+ Longitude: -90.080563
1003
+ Full address: 1500 Sugar Bowl Dr, New Orleans, LA 70112, USA
1004
+ City: New Orleans
1005
+ State/province: Louisiana
1006
+ Postal code: 70112
1007
+ Country: United States
1008
+ Google map: http://maps.google.com/maps?q=29.952211,-90.080563
1009
+
1010
+ 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.
1011
+
1012
+ Numeric Data Types and Precision
1013
+ --------------------------------
1014
+
1015
+ Geocoder works with any numeric data type (e.g. float, double, decimal) on which trig (and other mathematical) functions can be performed.
1016
+
1017
+ A summary of the relationship between geographic precision and the number of decimal places in latitude and longitude degree values is available on [Wikipedia](http://en.wikipedia.org/wiki/Decimal_degrees#Accuracy). As an example: at the equator, latitude/longitude values with 4 decimal places give about 11 metres precision, whereas 5 decimal places gives roughly 1 metre precision.
1018
+
1019
+ Notes on MongoDB
1020
+ ----------------
1021
+
1022
+ ### The Near Method
1023
+
1024
+ 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.
1025
+
1026
+ ### Latitude/Longitude Order
1027
+
1028
+ 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.
1029
+
1030
+ To access an object's coordinates in the conventional order, use the `to_coordinates` instance method provided by Geocoder. For example:
1031
+
1032
+ obj.to_coordinates # => [37.7941013, -122.3951096] # [lat, lon]
1033
+
1034
+ 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:
1035
+
1036
+ obj.coordinates # => [-122.3951096, 37.7941013] # [lon, lat]
1037
+
1038
+ For consistency with the rest of Geocoder, always use the `to_coordinates` method instead.
1039
+
1040
+ Notes on Non-Rails Frameworks
1041
+ -----------------------------
1042
+
1043
+ 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:
1044
+
1045
+ extend Geocoder::Model::ActiveRecord
1046
+
1047
+ Optimisation of Distance Queries
1048
+ --------------------------------
1049
+
1050
+ 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.
1051
+
1052
+ To take advantage of this optimisation you need to add a composite index on latitude and longitude. In your Rails migration:
1053
+
1054
+ add_index :table, [:latitude, :longitude]
1055
+
1056
+
1057
+ Distance Queries in SQLite
1058
+ --------------------------
1059
+
1060
+ 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.
1061
+
1062
+
1063
+ ### Discussion
1064
+
1065
+ There are few options for finding objects near a given point in SQLite without installing extensions:
1066
+
1067
+ 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.
1068
+
1069
+ 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.
1070
+
1071
+ 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`.
1072
+
1073
+ 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.
1074
+
1075
+
1076
+ Tests
1077
+ -----
1078
+
1079
+ 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:
1080
+
1081
+ http://github.com/alexreisner/geocoder_test
1082
+
1083
+
1084
+ Error Handling
1085
+ --------------
1086
+
1087
+ 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:
1088
+
1089
+ Geocoder.configure(:always_raise => [SocketError, Timeout::Error])
1090
+
1091
+ You can also do this to raise all exceptions:
1092
+
1093
+ Geocoder.configure(:always_raise => :all)
1094
+
1095
+ The raise-able exceptions are:
1096
+
1097
+ SocketError
1098
+ Timeout::Error
1099
+ Geocoder::OverQueryLimitError
1100
+ Geocoder::RequestDenied
1101
+ Geocoder::InvalidRequest
1102
+ Geocoder::InvalidApiKey
1103
+ Geocoder::ServiceUnavailable
1104
+
1105
+ 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.
1106
+
1107
+
1108
+ Troubleshooting
1109
+ ---------------
1110
+
1111
+ ### Mongoid
1112
+
1113
+ If you get one of these errors:
1114
+
1115
+ uninitialized constant Geocoder::Model::Mongoid
1116
+ uninitialized constant Geocoder::Model::Mongoid::Mongo
1117
+
1118
+ 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.
1119
+
1120
+ ### ActiveRecord
1121
+
1122
+ 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:
1123
+
1124
+ * using the `pluck` method (selects only a single column)
1125
+ * specifying another model through `includes` (selects columns from other tables)
1126
+
1127
+ ### Geocoding is Slow
1128
+
1129
+ With most lookups, addresses are translated into coordinates via an API that must be accessed through the Internet. These requests are subject to the same bandwidth constraints as every other HTTP request, and will vary in speed depending on network conditions. Furthermore, many of the services supported by Geocoder are free and thus very popular. Often they cannot keep up with demand and their response times become quite bad.
1130
+
1131
+ If your application requires quick geocoding responses you will probably need to pay for a non-free service, or--if you're doing IP address geocoding--use a lookup that doesn't require an external (network-accessed) service.
1132
+
1133
+ 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.
1134
+
1135
+ 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.
1136
+
1137
+ ### Unexpected Responses from Geocoding Services
1138
+
1139
+ Take a look at the server's raw response. You can do this by getting the request URL in an app console:
1140
+
1141
+ Geocoder::Lookup.get(:google).query_url(Geocoder::Query.new("..."))
1142
+
1143
+ Replace `:google` 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.
1144
+
1145
+ You can also fetch the response in the console:
1146
+
1147
+ Geocoder::Lookup.get(:google).send(:fetch_raw_data, Geocoder::Query.new("..."))
1148
+
1149
+
1150
+ Reporting Issues
1151
+ ----------------
1152
+
1153
+ 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). Also avoid vague language like "it doesn't work." Please describe as specifically as you can what behavior your are actually seeing (eg: an error message? a nil return value?).
1154
+
1155
+ 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.
1156
+
1157
+
1158
+ ### Known Issue
1159
+
1160
+ 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).
1161
+
1162
+ 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:
1163
+
1164
+ # Pass a :select option to the near scope to get the columns you want.
1165
+ # Instead of City.near(...).includes(:venues), try:
1166
+ City.near("Omaha, NE", 20, :select => "cities.*, venues.*").joins(:venues)
1167
+
1168
+ # This preload call will normally trigger two queries regardless of the
1169
+ # number of results; one query on hotels, and one query on administrators.
1170
+ # Instead of Hotel.near(...).includes(:administrator), try:
1171
+ Hotel.near("London, UK", 50).joins(:administrator).preload(:administrator)
1172
+
1173
+ If anyone has a more elegant solution to this problem I am very interested in seeing it.
1174
+
1175
+
1176
+ Contributing
1177
+ ------------
1178
+
1179
+ 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.
1180
+
1181
+ For all contributions, please respect the following guidelines:
1182
+
1183
+ * 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.
1184
+ * Do not commit changes to files that are irrelevant to your feature or bugfix (eg: `.gitignore`).
1185
+ * Do not add dependencies on other gems.
1186
+ * Do not add unnecessary `require` statements which could cause LoadErrors on certain systems.
1187
+ * Remember: Geocoder needs to run outside of Rails. Don't assume things like ActiveSupport are available.
1188
+ * 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.
1189
+ * Be aware that the pull request review process is not immediate, and is generally proportional to the size of the pull request.
1190
+ * 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.
1191
+
1192
+
1193
+ Copyright (c) 2009-15 Alex Reisner, released under the MIT license