geocoder 1.1.9 → 1.8.0

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 (238) hide show
  1. checksums.yaml +5 -5
  2. data/CHANGELOG.md +309 -0
  3. data/LICENSE +1 -1
  4. data/README.md +544 -540
  5. data/bin/console +13 -0
  6. data/examples/app_defined_lookup_services.rb +22 -0
  7. data/examples/reverse_geocode_job.rb +40 -0
  8. data/lib/easting_northing.rb +171 -0
  9. data/lib/generators/geocoder/config/templates/initializer.rb +22 -16
  10. data/lib/generators/geocoder/maxmind/geolite_city_generator.rb +30 -0
  11. data/lib/generators/geocoder/maxmind/geolite_country_generator.rb +30 -0
  12. data/lib/generators/geocoder/maxmind/templates/migration/geolite_city.rb +30 -0
  13. data/lib/generators/geocoder/maxmind/templates/migration/geolite_country.rb +17 -0
  14. data/lib/generators/geocoder/migration_version.rb +15 -0
  15. data/lib/geocoder/cache.rb +20 -32
  16. data/lib/geocoder/cache_stores/base.rb +40 -0
  17. data/lib/geocoder/cache_stores/generic.rb +35 -0
  18. data/lib/geocoder/cache_stores/redis.rb +34 -0
  19. data/lib/geocoder/calculations.rb +67 -36
  20. data/lib/geocoder/cli.rb +2 -2
  21. data/lib/geocoder/configuration.rb +33 -16
  22. data/lib/geocoder/configuration_hash.rb +4 -4
  23. data/lib/geocoder/esri_token.rb +38 -0
  24. data/lib/geocoder/exceptions.rb +19 -0
  25. data/lib/geocoder/ip_address.rb +33 -0
  26. data/lib/geocoder/kernel_logger.rb +25 -0
  27. data/lib/geocoder/logger.rb +47 -0
  28. data/lib/geocoder/lookup.rb +74 -11
  29. data/lib/geocoder/lookups/abstract_api.rb +46 -0
  30. data/lib/geocoder/lookups/amap.rb +63 -0
  31. data/lib/geocoder/lookups/amazon_location_service.rb +54 -0
  32. data/lib/geocoder/lookups/baidu.rb +24 -15
  33. data/lib/geocoder/lookups/baidu_ip.rb +30 -0
  34. data/lib/geocoder/lookups/ban_data_gouv_fr.rb +143 -0
  35. data/lib/geocoder/lookups/base.rb +109 -23
  36. data/lib/geocoder/lookups/bing.rb +45 -10
  37. data/lib/geocoder/lookups/db_ip_com.rb +52 -0
  38. data/lib/geocoder/lookups/dstk.rb +4 -2
  39. data/lib/geocoder/lookups/esri.rb +61 -8
  40. data/lib/geocoder/lookups/freegeoip.rb +25 -6
  41. data/lib/geocoder/lookups/geoapify.rb +72 -0
  42. data/lib/geocoder/lookups/geocoder_ca.rb +5 -6
  43. data/lib/geocoder/lookups/geocodio.rb +42 -0
  44. data/lib/geocoder/lookups/geoip2.rb +49 -0
  45. data/lib/geocoder/lookups/geoportail_lu.rb +65 -0
  46. data/lib/geocoder/lookups/google.rb +45 -12
  47. data/lib/geocoder/lookups/google_places_details.rb +64 -0
  48. data/lib/geocoder/lookups/google_places_search.rb +76 -0
  49. data/lib/geocoder/lookups/google_premier.rb +16 -2
  50. data/lib/geocoder/lookups/here.rb +73 -0
  51. data/lib/geocoder/lookups/ip2location.rb +71 -0
  52. data/lib/geocoder/lookups/ipapi_com.rb +82 -0
  53. data/lib/geocoder/lookups/ipdata_co.rb +62 -0
  54. data/lib/geocoder/lookups/ipgeolocation.rb +51 -0
  55. data/lib/geocoder/lookups/ipinfo_io.rb +44 -0
  56. data/lib/geocoder/lookups/ipqualityscore.rb +50 -0
  57. data/lib/geocoder/lookups/ipregistry.rb +68 -0
  58. data/lib/geocoder/lookups/ipstack.rb +63 -0
  59. data/lib/geocoder/lookups/latlon.rb +58 -0
  60. data/lib/geocoder/lookups/location_iq.rb +54 -0
  61. data/lib/geocoder/lookups/mapbox.rb +59 -0
  62. data/lib/geocoder/lookups/mapquest.rb +9 -10
  63. data/lib/geocoder/lookups/maxmind.rb +10 -8
  64. data/lib/geocoder/lookups/maxmind_geoip2.rb +70 -0
  65. data/lib/geocoder/lookups/maxmind_local.rb +71 -0
  66. data/lib/geocoder/lookups/melissa_street.rb +41 -0
  67. data/lib/geocoder/lookups/nationaal_georegister_nl.rb +38 -0
  68. data/lib/geocoder/lookups/nominatim.rb +26 -6
  69. data/lib/geocoder/lookups/opencagedata.rb +65 -0
  70. data/lib/geocoder/lookups/osmnames.rb +57 -0
  71. data/lib/geocoder/lookups/pelias.rb +63 -0
  72. data/lib/geocoder/lookups/photon.rb +89 -0
  73. data/lib/geocoder/lookups/pickpoint.rb +41 -0
  74. data/lib/geocoder/lookups/pointpin.rb +69 -0
  75. data/lib/geocoder/lookups/postcode_anywhere_uk.rb +50 -0
  76. data/lib/geocoder/lookups/postcodes_io.rb +31 -0
  77. data/lib/geocoder/lookups/smarty_streets.rb +68 -0
  78. data/lib/geocoder/lookups/telize.rb +75 -0
  79. data/lib/geocoder/lookups/tencent.rb +59 -0
  80. data/lib/geocoder/lookups/test.rb +4 -0
  81. data/lib/geocoder/lookups/twogis.rb +58 -0
  82. data/lib/geocoder/lookups/uk_ordnance_survey_names.rb +59 -0
  83. data/lib/geocoder/lookups/yandex.rb +18 -11
  84. data/lib/geocoder/models/active_record.rb +9 -4
  85. data/lib/geocoder/models/base.rb +1 -4
  86. data/lib/geocoder/models/mongo_base.rb +6 -4
  87. data/lib/geocoder/query.rb +23 -5
  88. data/lib/geocoder/railtie.rb +2 -2
  89. data/lib/geocoder/request.rb +102 -11
  90. data/lib/geocoder/results/abstract_api.rb +146 -0
  91. data/lib/geocoder/results/amap.rb +87 -0
  92. data/lib/geocoder/results/amazon_location_service.rb +57 -0
  93. data/lib/geocoder/results/baidu.rb +10 -14
  94. data/lib/geocoder/results/baidu_ip.rb +62 -0
  95. data/lib/geocoder/results/ban_data_gouv_fr.rb +282 -0
  96. data/lib/geocoder/results/base.rb +13 -1
  97. data/lib/geocoder/results/bing.rb +5 -1
  98. data/lib/geocoder/results/db_ip_com.rb +58 -0
  99. data/lib/geocoder/results/esri.rb +35 -8
  100. data/lib/geocoder/results/freegeoip.rb +2 -7
  101. data/lib/geocoder/results/geoapify.rb +179 -0
  102. data/lib/geocoder/results/geocoder_ca.rb +3 -3
  103. data/lib/geocoder/results/geocodio.rb +78 -0
  104. data/lib/geocoder/results/geoip2.rb +76 -0
  105. data/lib/geocoder/results/geoportail_lu.rb +71 -0
  106. data/lib/geocoder/results/google.rb +26 -0
  107. data/lib/geocoder/results/google_places_details.rb +39 -0
  108. data/lib/geocoder/results/google_places_search.rb +52 -0
  109. data/lib/geocoder/results/here.rb +77 -0
  110. data/lib/geocoder/results/ip2location.rb +22 -0
  111. data/lib/geocoder/results/ipapi_com.rb +45 -0
  112. data/lib/geocoder/results/ipdata_co.rb +40 -0
  113. data/lib/geocoder/results/ipgeolocation.rb +59 -0
  114. data/lib/geocoder/results/ipinfo_io.rb +48 -0
  115. data/lib/geocoder/results/ipqualityscore.rb +54 -0
  116. data/lib/geocoder/results/ipregistry.rb +304 -0
  117. data/lib/geocoder/results/ipstack.rb +60 -0
  118. data/lib/geocoder/results/latlon.rb +71 -0
  119. data/lib/geocoder/results/location_iq.rb +6 -0
  120. data/lib/geocoder/results/mapbox.rb +63 -0
  121. data/lib/geocoder/results/mapquest.rb +5 -8
  122. data/lib/geocoder/results/maxmind.rb +0 -5
  123. data/lib/geocoder/results/maxmind_geoip2.rb +9 -0
  124. data/lib/geocoder/results/maxmind_local.rb +44 -0
  125. data/lib/geocoder/results/melissa_street.rb +46 -0
  126. data/lib/geocoder/results/nationaal_georegister_nl.rb +62 -0
  127. data/lib/geocoder/results/nominatim.rb +41 -14
  128. data/lib/geocoder/results/opencagedata.rb +100 -0
  129. data/lib/geocoder/results/osmnames.rb +56 -0
  130. data/lib/geocoder/results/pelias.rb +58 -0
  131. data/lib/geocoder/results/photon.rb +119 -0
  132. data/lib/geocoder/results/pickpoint.rb +6 -0
  133. data/lib/geocoder/results/pointpin.rb +40 -0
  134. data/lib/geocoder/results/postcode_anywhere_uk.rb +42 -0
  135. data/lib/geocoder/results/postcodes_io.rb +40 -0
  136. data/lib/geocoder/results/smarty_streets.rb +142 -0
  137. data/lib/geocoder/results/telize.rb +40 -0
  138. data/lib/geocoder/results/tencent.rb +72 -0
  139. data/lib/geocoder/results/test.rb +20 -3
  140. data/lib/geocoder/results/twogis.rb +76 -0
  141. data/lib/geocoder/results/uk_ordnance_survey_names.rb +59 -0
  142. data/lib/geocoder/results/yandex.rb +244 -32
  143. data/lib/geocoder/sql.rb +25 -21
  144. data/lib/geocoder/stores/active_record.rb +82 -26
  145. data/lib/geocoder/stores/base.rb +9 -14
  146. data/lib/geocoder/stores/mongo_base.rb +0 -31
  147. data/lib/geocoder/util.rb +29 -0
  148. data/lib/geocoder/version.rb +1 -1
  149. data/lib/geocoder.rb +6 -13
  150. data/lib/maxmind_database.rb +109 -0
  151. data/lib/tasks/geocoder.rake +30 -3
  152. data/lib/tasks/maxmind.rake +73 -0
  153. metadata +115 -98
  154. data/.gitignore +0 -5
  155. data/.travis.yml +0 -27
  156. data/Rakefile +0 -25
  157. data/examples/autoexpire_cache_dalli.rb +0 -62
  158. data/examples/autoexpire_cache_redis.rb +0 -28
  159. data/gemfiles/Gemfile.mongoid-2.4.x +0 -15
  160. data/lib/geocoder/lookups/geocoder_us.rb +0 -39
  161. data/lib/geocoder/lookups/ovi.rb +0 -62
  162. data/lib/geocoder/lookups/yahoo.rb +0 -86
  163. data/lib/geocoder/results/geocoder_us.rb +0 -39
  164. data/lib/geocoder/results/ovi.rb +0 -62
  165. data/lib/geocoder/results/yahoo.rb +0 -55
  166. data/lib/hash_recursive_merge.rb +0 -74
  167. data/lib/oauth_util.rb +0 -112
  168. data/test/active_record_test.rb +0 -15
  169. data/test/cache_test.rb +0 -35
  170. data/test/calculations_test.rb +0 -211
  171. data/test/configuration_test.rb +0 -78
  172. data/test/custom_block_test.rb +0 -32
  173. data/test/error_handling_test.rb +0 -43
  174. data/test/fixtures/baidu_invalid_key +0 -1
  175. data/test/fixtures/baidu_no_results +0 -1
  176. data/test/fixtures/baidu_reverse +0 -1
  177. data/test/fixtures/baidu_shanghai_pearl_tower +0 -12
  178. data/test/fixtures/bing_invalid_key +0 -1
  179. data/test/fixtures/bing_madison_square_garden +0 -40
  180. data/test/fixtures/bing_no_results +0 -16
  181. data/test/fixtures/bing_reverse +0 -42
  182. data/test/fixtures/esri_madison_square_garden +0 -59
  183. data/test/fixtures/esri_no_results +0 -8
  184. data/test/fixtures/esri_reverse +0 -21
  185. data/test/fixtures/freegeoip_74_200_247_59 +0 -12
  186. data/test/fixtures/freegeoip_no_results +0 -1
  187. data/test/fixtures/geocoder_ca_madison_square_garden +0 -1
  188. data/test/fixtures/geocoder_ca_no_results +0 -1
  189. data/test/fixtures/geocoder_ca_reverse +0 -34
  190. data/test/fixtures/geocoder_us_madison_square_garden +0 -1
  191. data/test/fixtures/geocoder_us_no_results +0 -1
  192. data/test/fixtures/google_garbage +0 -456
  193. data/test/fixtures/google_madison_square_garden +0 -57
  194. data/test/fixtures/google_no_city_data +0 -44
  195. data/test/fixtures/google_no_locality +0 -51
  196. data/test/fixtures/google_no_results +0 -4
  197. data/test/fixtures/google_over_limit +0 -4
  198. data/test/fixtures/mapquest_error +0 -16
  199. data/test/fixtures/mapquest_invalid_api_key +0 -16
  200. data/test/fixtures/mapquest_invalid_request +0 -16
  201. data/test/fixtures/mapquest_madison_square_garden +0 -52
  202. data/test/fixtures/mapquest_no_results +0 -16
  203. data/test/fixtures/maxmind_24_24_24_21 +0 -1
  204. data/test/fixtures/maxmind_24_24_24_22 +0 -1
  205. data/test/fixtures/maxmind_24_24_24_23 +0 -1
  206. data/test/fixtures/maxmind_24_24_24_24 +0 -1
  207. data/test/fixtures/maxmind_74_200_247_59 +0 -1
  208. data/test/fixtures/maxmind_invalid_key +0 -1
  209. data/test/fixtures/maxmind_no_results +0 -1
  210. data/test/fixtures/nominatim_madison_square_garden +0 -150
  211. data/test/fixtures/nominatim_no_results +0 -1
  212. data/test/fixtures/ovi_madison_square_garden +0 -72
  213. data/test/fixtures/ovi_no_results +0 -8
  214. data/test/fixtures/yahoo_error +0 -1
  215. data/test/fixtures/yahoo_invalid_key +0 -2
  216. data/test/fixtures/yahoo_madison_square_garden +0 -52
  217. data/test/fixtures/yahoo_no_results +0 -10
  218. data/test/fixtures/yahoo_over_limit +0 -2
  219. data/test/fixtures/yandex_invalid_key +0 -1
  220. data/test/fixtures/yandex_kremlin +0 -48
  221. data/test/fixtures/yandex_no_city_and_town +0 -112
  222. data/test/fixtures/yandex_no_results +0 -16
  223. data/test/geocoder_test.rb +0 -59
  224. data/test/https_test.rb +0 -16
  225. data/test/integration/smoke_test.rb +0 -26
  226. data/test/lookup_test.rb +0 -117
  227. data/test/method_aliases_test.rb +0 -25
  228. data/test/mongoid_test.rb +0 -46
  229. data/test/mongoid_test_helper.rb +0 -43
  230. data/test/near_test.rb +0 -61
  231. data/test/oauth_util_test.rb +0 -30
  232. data/test/proxy_test.rb +0 -36
  233. data/test/query_test.rb +0 -52
  234. data/test/request_test.rb +0 -29
  235. data/test/result_test.rb +0 -42
  236. data/test/services_test.rb +0 -393
  237. data/test/test_helper.rb +0 -289
  238. data/test/test_mode_test.rb +0 -59
data/README.md CHANGED
@@ -1,728 +1,721 @@
1
1
  Geocoder
2
2
  ========
3
3
 
4
- Geocoder is a complete geocoding solution for Ruby. With Rails it adds geocoding (by street or IP address), reverse geocoding (find street address based on given coordinates), and distance queries. It's as simple as calling `geocode` on your objects, and then using a scope like `Venue.near("Billings, MT")`.
4
+ **Complete geocoding solution for Ruby.**
5
5
 
6
+ [![Gem Version](https://badge.fury.io/rb/geocoder.svg)](http://badge.fury.io/rb/geocoder)
7
+ [![Code Climate](https://codeclimate.com/github/alexreisner/geocoder/badges/gpa.svg)](https://codeclimate.com/github/alexreisner/geocoder)
8
+ [![Build Status](https://travis-ci.com/alexreisner/geocoder.svg?branch=master)](https://travis-ci.com/alexreisner/geocoder)
6
9
 
7
- Compatibility
8
- -------------
10
+ Key features:
9
11
 
10
- * Supports multiple Ruby versions: Ruby 1.8.7, 1.9.2, 1.9.3, 2.0.0, and JRuby.
11
- * Supports multiple databases: MySQL, PostgreSQL, SQLite, and MongoDB (1.7.0 and higher).
12
- * 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).
13
- * Works very well outside of Rails, you just need to install either the `json` (for MRI) or `json_pure` (for JRuby) gem.
12
+ * Forward and reverse geocoding.
13
+ * IP address geocoding.
14
+ * Connects to more than 40 APIs worldwide.
15
+ * Performance-enhancing features like caching.
16
+ * Integrates with ActiveRecord and Mongoid.
17
+ * Basic geospatial queries: search within radius (or rectangle, or ring).
14
18
 
19
+ Compatibility:
20
+
21
+ * Ruby versions: 2.1+, and JRuby.
22
+ * Databases: MySQL, PostgreSQL, SQLite, and MongoDB.
23
+ * Rails: 5.x, 6.x, and 7.x.
24
+ * Works outside of Rails with the `json` (for MRI) or `json_pure` (for JRuby) gem.
15
25
 
16
- Installation
17
- ------------
18
26
 
19
- Install Geocoder like any other Ruby gem:
27
+ Table of Contents
28
+ -----------------
20
29
 
21
- gem install geocoder
30
+ Basic Features:
22
31
 
23
- Or, if you're using Rails/Bundler, add this to your Gemfile:
32
+ * [Basic Search](#basic-search)
33
+ * [Geocoding Objects](#geocoding-objects)
34
+ * [Geospatial Database Queries](#geospatial-database-queries)
35
+ * [Geocoding HTTP Requests](#geocoding-http-requests)
36
+ * [Geocoding Service ("Lookup") Configuration](#geocoding-service-lookup-configuration)
24
37
 
25
- gem "geocoder"
38
+ Advanced Features:
26
39
 
27
- and run at the command prompt:
40
+ * [Performance and Optimization](#performance-and-optimization)
41
+ * [Advanced Model Configuration](#advanced-model-configuration)
42
+ * [Advanced Database Queries](#advanced-database-queries)
43
+ * [Geospatial Calculations](#geospatial-calculations)
44
+ * [Batch Geocoding](#batch-geocoding)
45
+ * [Testing](#testing)
46
+ * [Error Handling](#error-handling)
47
+ * [Command Line Interface](#command-line-interface)
28
48
 
29
- bundle install
49
+ The Rest:
30
50
 
51
+ * [Technical Discussions](#technical-discussions)
52
+ * [Troubleshooting](#troubleshooting)
53
+ * [Known Issues](#known-issues)
54
+ * [Reporting Issues](https://github.com/alexreisner/geocoder/blob/master/CONTRIBUTING.md#reporting-bugs)
55
+ * [Contributing](https://github.com/alexreisner/geocoder/blob/master/CONTRIBUTING.md#making-changes)
31
56
 
32
- Object Geocoding
33
- ----------------
57
+ See Also:
34
58
 
35
- ### ActiveRecord
59
+ * [Guide to Geocoding APIs](https://github.com/alexreisner/geocoder/blob/master/README_API_GUIDE.md) (formerly part of this README)
36
60
 
37
- Your model must have two attributes (database columns) for storing latitude and longitude coordinates. By default they should be called `latitude` and `longitude` but this can be changed (see "Model Configuration" below):
38
61
 
39
- rails generate migration AddLatitudeAndLongitudeToModel latitude:float longitude:float
40
- rake db:migrate
62
+ Basic Search
63
+ ------------
41
64
 
42
- For reverse geocoding your model must provide a method that returns an address. This can be a single attribute, but it can also be a method that returns a string assembled from different attributes (eg: `city`, `state`, and `country`).
65
+ In its simplest form, Geocoder takes an address and searches for its latitude/longitude coordinates:
43
66
 
44
- Next, your model must tell Geocoder which method returns your object's geocodable address:
67
+ ```ruby
68
+ results = Geocoder.search("Paris")
69
+ results.first.coordinates
70
+ # => [48.856614, 2.3522219] # latitude and longitude
71
+ ```
45
72
 
46
- geocoded_by :full_street_address # can also be an IP address
47
- after_validation :geocode # auto-fetch coordinates
73
+ The reverse is possible too. Given coordinates, it finds an address:
48
74
 
49
- For reverse geocoding, tell Geocoder which attributes store latitude and longitude:
75
+ ```ruby
76
+ results = Geocoder.search([48.856614, 2.3522219])
77
+ results.first.address
78
+ # => "Hôtel de Ville, 75004 Paris, France"
79
+ ```
50
80
 
51
- reverse_geocoded_by :latitude, :longitude
52
- after_validation :reverse_geocode # auto-fetch address
81
+ You can also look up the location of an IP address:
53
82
 
54
- ### Mongoid
83
+ ```ruby
84
+ results = Geocoder.search("172.56.21.89")
85
+ results.first.coordinates
86
+ # => [30.267153, -97.7430608]
87
+ results.first.country
88
+ # => "United States"
89
+ ```
55
90
 
56
- First, your model must have an array field for storing coordinates:
91
+ **The success and accuracy of geocoding depends entirely on the API being used to do these lookups.** Most queries work fairly well with the default configuration, but every application has different needs and every API has its particular strengths and weaknesses. If you need better coverage for your application you'll want to get familiar with the large number of supported APIs, listed in the [API Guide](https://github.com/alexreisner/geocoder/blob/master/README_API_GUIDE.md).
57
92
 
58
- field :coordinates, :type => Array
59
93
 
60
- You may also want an address field, like this:
94
+ Geocoding Objects
95
+ -----------------
96
+
97
+ To automatically geocode your objects:
61
98
 
62
- field :address
99
+ **1.** Your model must provide a method that returns an address to geocode. This can be a single attribute, but it can also be a method that returns a string assembled from different attributes (eg: `city`, `state`, and `country`). For example, if your model has `street`, `city`, `state`, and `country` attributes you might do something like this:
63
100
 
64
- but if you store address components (city, state, country, etc) in separate fields you can instead define a method called `address` that combines them into a single string which will be used to query the geocoding service.
101
+ ```ruby
102
+ def address
103
+ [street, city, state, country].compact.join(', ')
104
+ end
105
+ ```
65
106
 
66
- Once your fields are defined, include the `Geocoder::Model::Mongoid` module and then call `geocoded_by`:
107
+ **2.** Your model must have a way to store latitude/longitude coordinates. With ActiveRecord, add two attributes/columns (of type float or decimal) called `latitude` and `longitude`. For MongoDB, use a single field (of type Array) called `coordinates` (i.e., `field :coordinates, type: Array`). (See [Advanced Model Configuration](#advanced-model-configuration) for using different attribute names.)
67
108
 
68
- include Geocoder::Model::Mongoid
69
- geocoded_by :address # can also be an IP address
70
- after_validation :geocode # auto-fetch coordinates
109
+ **3.** In your model, tell geocoder where to find the object's address:
71
110
 
72
- Reverse geocoding is similar:
111
+ ```ruby
112
+ geocoded_by :address
113
+ ```
73
114
 
74
- include Geocoder::Model::Mongoid
75
- reverse_geocoded_by :coordinates
76
- after_validation :reverse_geocode # auto-fetch address
115
+ This adds a `geocode` method which you can invoke via callback:
77
116
 
78
- Once you've set up your model you'll need to create the necessary spatial indices in your database:
117
+ ```ruby
118
+ after_validation :geocode
119
+ ```
79
120
 
80
- rake db:mongoid:create_indexes
121
+ Reverse geocoding (given lat/lon coordinates, find an address) is similar:
81
122
 
82
- Be sure to read _Latitude/Longitude Order_ in the _Notes on MongoDB_ section below on how to properly retrieve latitude/longitude coordinates from your objects.
123
+ ```ruby
124
+ reverse_geocoded_by :latitude, :longitude
125
+ after_validation :reverse_geocode
126
+ ```
83
127
 
84
- ### MongoMapper
128
+ With any geocoded objects, you can do the following:
85
129
 
86
- MongoMapper is very similar to Mongoid, just be sure to include `Geocoder::Model::MongoMapper`.
130
+ ```ruby
131
+ obj.distance_to([43.9,-98.6]) # distance from obj to point
132
+ obj.bearing_to([43.9,-98.6]) # bearing from obj to point
133
+ obj.bearing_from(obj2) # bearing from obj2 to obj
134
+ ```
87
135
 
88
- ### Mongo Indices
136
+ The `bearing_from/to` methods take a single argument which can be: a `[lat,lon]` array, a geocoded object, or a geocodable address (string). The `distance_from/to` methods also take a units argument (`:mi`, `:km`, or `:nm` for nautical miles). See [Distance and Bearing](#distance-and-bearing) below for more info.
89
137
 
90
- By default, the methods `geocoded_by` and `reverse_geocoded_by` create a geospatial index. You can avoid index creation with the `:skip_index option`, for example:
138
+ ### One More Thing for MongoDB!
91
139
 
92
- include Geocoder::Model::Mongoid
93
- geocoded_by :address, :skip_index => true
140
+ Before you can call `geocoded_by` you'll need to include the necessary module using one of the following:
94
141
 
95
- ### Bulk Geocoding
142
+ ```ruby
143
+ include Geocoder::Model::Mongoid
144
+ include Geocoder::Model::MongoMapper
145
+ ```
96
146
 
97
- If you have just added geocoding to an existing application with a lot of objects you can use this Rake task to geocode them all:
147
+ ### Latitude/Longitude Order in MongoDB
98
148
 
99
- rake geocode:all CLASS=YourModel
149
+ Everywhere coordinates are passed to methods as two-element arrays, Geocoder expects them to be in the order: `[lat, lon]`. However, as per [the GeoJSON spec](http://geojson.org/geojson-spec.html#positions), MongoDB requires that coordinates be stored longitude-first (`[lon, lat]`), so internally they are stored "backwards." Geocoder's methods attempt to hide this, so calling `obj.to_coordinates` (a method added to the object by Geocoder via `geocoded_by`) returns coordinates in the conventional order:
100
150
 
101
- 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 the rake task, like so:
151
+ ```ruby
152
+ obj.to_coordinates # => [37.7941013, -122.3951096] # [lat, lon]
153
+ ```
102
154
 
103
- rake geocode:all CLASS=YourModel sleep=0.25
155
+ whereas calling the object's coordinates attribute directly (`obj.coordinates` by default) returns the internal representation which is probably the reverse of what you want:
104
156
 
157
+ ```ruby
158
+ obj.coordinates # => [-122.3951096, 37.7941013] # [lon, lat]
159
+ ```
105
160
 
106
- Request Geocoding by IP Address
107
- -------------------------------
161
+ So, be careful.
108
162
 
109
- Geocoder adds a `location` method to the standard `Rack::Request` object so you can easily look up the location of any HTTP request by IP address. For example, in a Rails controller or a Sinatra app:
163
+ ### Use Outside of Rails
110
164
 
111
- # returns Geocoder::Result object
112
- result = request.location
165
+ To use Geocoder with ActiveRecord and a framework other than Rails (like Sinatra or Padrino), you will need to add this in your model before calling Geocoder methods:
113
166
 
114
- Note that this 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.
167
+ ```ruby
168
+ extend Geocoder::Model::ActiveRecord
169
+ ```
115
170
 
116
- See _Advanced Geocoding_ below for more information about `Geocoder::Result` objects.
117
171
 
172
+ Geospatial Database Queries
173
+ ---------------------------
118
174
 
119
- Location-Aware Database Queries
120
- -------------------------------
175
+ ### For ActiveRecord models:
121
176
 
122
177
  To find objects by location, use the following scopes:
123
178
 
124
- Venue.near('Omaha, NE, US', 20) # venues within 20 miles of Omaha
125
- Venue.near([40.71, 100.23], 20) # venues within 20 miles of a point
126
- Venue.near([40.71, 100.23], 20, :units => :km)
127
- # venues within 20 kilometres of a point
128
- Venue.geocoded # venues with coordinates
129
- Venue.not_geocoded # venues without coordinates
179
+ ```ruby
180
+ Venue.near('Omaha, NE, US') # venues within 20 miles of Omaha
181
+ Venue.near([40.71, -100.23], 50) # venues within 50 miles of a point
182
+ Venue.near([40.71, -100.23], 50, units: :km) # venues within 50 kilometres of a point
183
+ Venue.geocoded # venues with coordinates
184
+ Venue.not_geocoded # venues without coordinates
185
+ ```
130
186
 
131
187
  With geocoded objects you can do things like this:
132
188
 
133
- if obj.geocoded?
134
- obj.nearbys(30) # other objects within 30 miles
135
- obj.distance_from([40.714,-100.234]) # distance from arbitrary point to object
136
- obj.bearing_to("Paris, France") # direction from object to arbitrary point
137
- end
189
+ ```ruby
190
+ if obj.geocoded?
191
+ obj.nearbys(30) # other objects within 30 miles
192
+ obj.distance_from([40.714,-100.234]) # distance from arbitrary point to object
193
+ obj.bearing_to("Paris, France") # direction from object to arbitrary point
194
+ end
195
+ ```
138
196
 
139
- Some utility methods are also available:
197
+ ### For MongoDB-backed models:
140
198
 
141
- # look up coordinates of some location (like searching Google Maps)
142
- Geocoder.coordinates("25 Main St, Cooperstown, NY")
143
- => [42.700149, -74.922767]
199
+ Please do not use Geocoder's `near` method. Instead use MongoDB's built-in [geospatial query language](https://docs.mongodb.org/manual/reference/command/geoNear/), which is faster. Mongoid also provides [a DSL](http://mongoid.github.io/en/mongoid/docs/querying.html#geo_near) for geospatial queries.
144
200
 
145
- # distance (in miles) between Eiffel Tower and Empire State Building
146
- Geocoder::Calculations.distance_between([47.858205,2.294359], [40.748433,-73.985655])
147
- => 3619.77359999382
148
201
 
149
- # find the geographic center (aka center of gravity) of objects or points
150
- Geocoder::Calculations.geographic_center([city1, city2, [40.22,-73.99], city4])
151
- => [35.14968, -90.048929]
202
+ Geocoding HTTP Requests
203
+ -----------------------
152
204
 
153
- Please see the code for more methods and detailed information about arguments (eg, working with kilometers).
205
+ Geocoder adds `location` and `safe_location` methods to the standard `Rack::Request` object so you can easily look up the location of any HTTP request by IP address. For example, in a Rails controller or a Sinatra app:
154
206
 
207
+ ```ruby
208
+ # returns Geocoder::Result object
209
+ result = request.location
210
+ ```
155
211
 
156
- Distance and Bearing
157
- --------------------
212
+ **The `location` method is vulnerable to trivial IP address spoofing via HTTP headers.** If that's a problem for your application, use `safe_location` instead, but be aware that `safe_location` will *not* try to trace a request's originating IP through proxy headers; you will instead get the location of the last proxy the request passed through, if any (excepting any proxies you have explicitly whitelisted in your Rack config).
158
213
 
159
- When you run a location-aware query the returned objects have two attributes added to them (only w/ ActiveRecord):
214
+ Note that these methods will usually return `nil` in test and development environments because things like "localhost" and "0.0.0.0" are not geocodable IP addresses.
160
215
 
161
- * `obj.distance` - number of miles from the search point to this object
162
- * `obj.bearing` - direction from the search point to this object
163
216
 
164
- 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:
217
+ Geocoding Service ("Lookup") Configuration
218
+ ------------------------------------------
165
219
 
166
- * `0` - due north
167
- * `180` - due south
168
- * `90` - due east
169
- * `270` - due west
170
- * `230.1` - southwest
171
- * `359.9` - almost due north
172
-
173
- You can convert these numbers to compass point names by using the utility method provided:
220
+ Geocoder supports a variety of street and IP address geocoding services. The default lookups are `:nominatim` for street addresses and `:ipinfo_io` for IP addresses. Please see the [API Guide](https://github.com/alexreisner/geocoder/blob/master/README_API_GUIDE.md) for details on specific geocoding services (not all settings are supported by all services).
174
221
 
175
- Geocoder::Calculations.compass_point(355) # => "N"
176
- Geocoder::Calculations.compass_point(45) # => "NE"
177
- Geocoder::Calculations.compass_point(208) # => "SW"
222
+ To create a Rails initializer with sample configuration:
178
223
 
179
- _Note: when using SQLite `distance` and `bearing` values are provided for interface consistency only. They are not very accurate._
224
+ ```sh
225
+ rails generate geocoder:config
226
+ ```
180
227
 
181
- To calculate accurate distance and bearing with SQLite or MongoDB:
228
+ Some common options are:
182
229
 
183
- obj.distance_to([43.9,-98.6]) # distance from obj to point
184
- obj.bearing_to([43.9,-98.6]) # bearing from obj to point
185
- obj.bearing_from(obj2) # bearing from obj2 to obj
230
+ ```ruby
231
+ # config/initializers/geocoder.rb
232
+ Geocoder.configure(
233
+ # street address geocoding service (default :nominatim)
234
+ lookup: :yandex,
186
235
 
187
- 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).
236
+ # IP address geocoding service (default :ipinfo_io)
237
+ ip_lookup: :maxmind,
188
238
 
239
+ # to use an API key:
240
+ api_key: "...",
189
241
 
190
- Model Configuration
191
- -------------------
242
+ # geocoding service request timeout, in seconds (default 3):
243
+ timeout: 5,
192
244
 
193
- 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:
245
+ # set default units to kilometers:
246
+ units: :km,
194
247
 
195
- geocoded_by :address, :latitude => :lat, :longitude => :lon # ActiveRecord
196
- geocoded_by :address, :coordinates => :coords # MongoDB
248
+ # caching (see Caching section below for details):
249
+ cache: Redis.new,
250
+ cache_options: {
251
+ expiration: 1.day, # Defaults to `nil`
252
+ prefix: "another_key:" # Defaults to `geocoder:`
253
+ }
254
+ )
255
+ ```
197
256
 
198
- The `address` method can return any string you'd use to search Google Maps. For example, any of the following are acceptable:
257
+ 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:
199
258
 
200
- * "714 Green St, Big Town, MO"
201
- * "Eiffel Tower, Paris, FR"
202
- * "Paris, TX, US"
259
+ ```ruby
260
+ # with Google:
261
+ Geocoder.search("Middletown", bounds: [[40.6,-77.9], [39.9,-75.9]])
262
+ ```
203
263
 
204
- If your model has `street`, `city`, `state`, and `country` attributes you might do something like this:
264
+ 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:
205
265
 
206
- geocoded_by :address
266
+ ```ruby
267
+ # Nominatim's `countrycodes` parameter:
268
+ Geocoder.search("Rome", params: {countrycodes: "us,ca"})
207
269
 
208
- def address
209
- [street, city, state, country].compact.join(', ')
210
- end
270
+ # Google's `region` parameter:
271
+ Geocoder.search("Rome", params: {region: "..."})
272
+ ```
211
273
 
212
- For reverse geocoding you can also specify an alternate name attribute where the address will be stored, for example:
274
+ ### Configuring Multiple Services
213
275
 
214
- reverse_geocoded_by :latitude, :longitude, :address => :location # ActiveRecord
215
- reverse_geocoded_by :coordinates, :address => :loc # MongoDB
276
+ You can configure multiple geocoding services at once by using the service's name as a key for a sub-configuration hash, like this:
216
277
 
278
+ ```ruby
279
+ Geocoder.configure(
217
280
 
218
- Advanced Querying
219
- -----------------
281
+ timeout: 2,
282
+ cache: Redis.new,
220
283
 
221
- 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:
284
+ yandex: {
285
+ api_key: "...",
286
+ timeout: 5
287
+ },
222
288
 
223
- distance = 20
224
- center_point = [40.71, 100.23]
225
- box = Geocoder::Calculations.bounding_box(center_point, distance)
226
- Venue.within_bounding_box(box)
289
+ baidu: {
290
+ api_key: "..."
291
+ },
227
292
 
228
- 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.
293
+ maxmind: {
294
+ api_key: "...",
295
+ service: :omni
296
+ }
229
297
 
298
+ )
299
+ ```
230
300
 
231
- Advanced Geocoding
232
- ------------------
301
+ Lookup-specific settings override global settings so, in this example, the timeout for all lookups is 2 seconds, except for Yandex which is 5.
233
302
 
234
- 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:
235
303
 
236
- reverse_geocoded_by :latitude, :longitude do |obj,results|
237
- if geo = results.first
238
- obj.city = geo.city
239
- obj.zipcode = geo.postal_code
240
- obj.country = geo.country_code
241
- end
242
- end
243
- after_validation :reverse_geocode
304
+ Performance and Optimization
305
+ ----------------------------
244
306
 
245
- Every `Geocoder::Result` object, `result`, provides the following data:
246
-
247
- * `result.latitude` - float
248
- * `result.longitude` - float
249
- * `result.coordinates` - array of the above two
250
- * `result.address` - string
251
- * `result.city` - string
252
- * `result.state` - string
253
- * `result.state_code` - string
254
- * `result.postal_code` - string
255
- * `result.country` - string
256
- * `result.country_code` - string
307
+ ### Database Indices
257
308
 
258
- If you're familiar with the results returned by the geocoding service you're using you can access even more data, but you'll need to be familiar with the particular `Geocoder::Result` object you're using and the structure of your geocoding service's responses. (See below for links to geocoding service documentation.)
309
+ 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:
259
310
 
311
+ ```ruby
312
+ add_index :table, [:latitude, :longitude]
313
+ ```
260
314
 
261
- Geocoding Services
262
- ------------------
315
+ 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:
263
316
 
264
- By default Geocoder uses Google's geocoding API to fetch coordinates and street addresses (FreeGeoIP is the default for IP address info). However there are several other APIs supported, as well as a variety of settings. Please see the listing and comparison below for details on specific geocoding services (not all settings are supported by all services). Some common configuration options are:
317
+ ```ruby
318
+ include Geocoder::Model::Mongoid
319
+ geocoded_by :address, skip_index: true
320
+ ```
265
321
 
266
- # config/initializers/geocoder.rb
267
- Geocoder.configure(
322
+ ### Avoiding Unnecessary API Requests
268
323
 
269
- # geocoding service (see below for supported options):
270
- :lookup => :yandex,
324
+ 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:
271
325
 
272
- # to use an API key:
273
- :api_key => "...",
326
+ * an address is present
327
+ * the address has been changed since last save (or it has never been saved)
274
328
 
275
- # geocoding service request timeout, in seconds (default 3):
276
- :timeout => 5,
329
+ The exact code will vary depending on the method you use for your geocodable string, but it would be something like this:
277
330
 
278
- # set default units to kilometers:
279
- :units => :km,
331
+ ```ruby
332
+ after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }
333
+ ```
280
334
 
281
- # caching (see below for details):
282
- :cache => Redis.new,
283
- :cache_prefix => "..."
335
+ ### Caching
284
336
 
285
- )
337
+ 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:
286
338
 
287
- 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:
288
-
289
- # with Google:
290
- Geocoder.search("Paris", :bounds => [[32.1,-95.9], [33.9,-94.3]])
291
-
292
- 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:
293
-
294
- # with Nominatim:
295
- Geocoder.search("Paris", :params => {:countrycodes => "gb,de,fr,es,us"})
296
-
297
-
298
- ### Listing and Comparison
299
-
300
- 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.
301
-
302
- #### Google (`:google`, `:google_premier`)
303
-
304
- * **API key**: required for Premier (do NOT use a key for the free version)
305
- * **Key signup**: https://developers.google.com/maps/documentation/business/
306
- * **Quota**: 2,500 requests/day, 100,000 with Google Maps API Premier
307
- * **Region**: world
308
- * **SSL support**: yes
309
- * **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)
310
- * **Extra options**: `:bounds` - pass SW and NE coordinates as an array of two arrays to bias results towards a viewport
311
- * **Documentation**: http://code.google.com/apis/maps/documentation/geocoding/#JSON
312
- * **Terms of Service**: http://code.google.com/apis/maps/terms.html#section_10_12
313
- * **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..."
314
- * **Notes**: To use Google Premier set `Geocoder.configure(:lookup => :google_premier, :api_key => [key, client, channel])`.
315
-
316
- #### Yahoo BOSS (`:yahoo`)
317
-
318
- Yahoo BOSS is **not a free service**. As of November 17, 2012 Yahoo no longer offers a free geocoding API.
319
-
320
- * **API key**: requires OAuth consumer key and secret (set `Geocoder.configure(:api_key => [key, secret])`)
321
- * **Key signup**: http://developer.yahoo.com/boss/geo/
322
- * **Quota**: unlimited, but subject to usage fees
323
- * **Region**: world
324
- * **SSL support**: no
325
- * **Languages**: en, fr, de, it, es, pt, nl, zh, ja, ko
326
- * **Documentation**: http://developer.yahoo.com/boss/geo/docs/index.html
327
- * **Terms of Service**: http://info.yahoo.com/legal/us/yahoo/boss/tou/?pir=ucJPcJ1ibUn.h.d.lVmlcbcEkoHjwJ_PvxG9SLK9VIbIQAw1XFrnDqY-
328
- * **Limitations**: No mass downloads, no commercial map production based on the data, no storage of data except for caching.
329
-
330
- #### Bing (`:bing`)
331
-
332
- * **API key**: required
333
- * **Key signup**: http://www.bingmapsportal.com
334
- * **Quota**: 50,000 requests/24 hrs
335
- * **Region**: world
336
- * **SSL support**: no
337
- * **Languages**: ?
338
- * **Documentation**: http://msdn.microsoft.com/en-us/library/ff701715.aspx
339
- * **Terms of Service**: http://www.microsoft.com/maps/product/terms.html
340
- * **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."
341
-
342
- #### Nominatim (`:nominatim`)
343
-
344
- * **API key**: none
345
- * **Quota**: 1 request/second
346
- * **Region**: world
347
- * **SSL support**: no
348
- * **Languages**: ?
349
- * **Documentation**: http://wiki.openstreetmap.org/wiki/Nominatim
350
- * **Terms of Service**: http://wiki.openstreetmap.org/wiki/Nominatim_usage_policy
351
- * **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 CC-BY-SA (you must provide attribution).
352
-
353
- #### Yandex (`:yandex`)
354
-
355
- * **API key**: none
356
- * **Quota**: 25000 requests / day
357
- * **Region**: world
358
- * **SSL support**: no
359
- * **Languages**: Russian, Belarusian, Ukrainian, English, Turkish (only for maps of Turkey)
360
- * **Documentation**: http://api.yandex.com.tr/maps/doc/intro/concepts/intro.xml
361
- * **Terms of Service**: http://api.yandex.com.tr/maps/doc/intro/concepts/intro.xml#rules
362
- * **Limitations**: ?
363
-
364
- #### Geocoder.ca (`:geocoder_ca`)
365
-
366
- * **API key**: none
367
- * **Quota**: ?
368
- * **Region**: US and Canada
369
- * **SSL support**: no
370
- * **Languages**: English
371
- * **Documentation**: ?
372
- * **Terms of Service**: http://geocoder.ca/?terms=1
373
- * **Limitations**: "Under no circumstances can our data be re-distributed or re-sold by anyone to other parties without our written permission."
374
-
375
- #### Geocoder.us (`:geocoder_us`)
376
-
377
- * **API key**: HTTP Basic Auth
378
- * **Sign up**: http://geocoder.us/user/signup
379
- * **Quota**: You can purchase 20,000 credits at a time for $50
380
- * **Region**: US
381
- * **SSL support**: no
382
- * **Languages**: English
383
- * **Documentation**: http://geocoder.us/help/
384
- * **Terms of Service**: http://geocoder.us/terms.shtml
385
- * **Limitations**: ?
386
-
387
- #### Mapquest (`:mapquest`)
388
-
389
- * **API key**: required
390
- * **Key signup**: http://developer.mapquest.com/web/products/open
391
- * **Quota**: ?
392
- * **HTTP Headers**: in order to use the licensed API you can configure the http_headers to include a referer as so:
393
- `Geocoder.configure(:http_headers => { "Referer" => "http://foo.com" })`
394
- You can also allow a blank referer from the API management console via mapquest but it is potentially a security risk that someone else could use your API key from another domain.
395
- * **Region**: world
396
- * **SSL support**: no
397
- * **Languages**: English
398
- * **Documentation**: http://www.mapquestapi.com/geocoding/
399
- * **Terms of Service**: http://info.mapquest.com/terms-of-use/
400
- * **Limitations**: ?
401
- * **Notes**: You can specify the licensed API by setting: `Geocoder.configure(:mapquest => {:licensed => true})` (defaults to free "open" version)
402
-
403
- #### Ovi/Nokia (`:ovi`)
404
-
405
- * **API key**: not required, but performance restricted without it
406
- * **Quota**: ?
407
- * **Region**: world
408
- * **SSL support**: no
409
- * **Languages**: English
410
- * **Documentation**: http://api.maps.ovi.com/devguide/overview.html
411
- * **Terms of Service**: http://www.developer.nokia.com/Develop/Maps/TC.html
412
- * **Limitations**: ?
413
-
414
- #### ESRI (`:esri`)
415
-
416
- * **API key**: none
417
- * **Quota**: Required for some scenarios (see Terms of Service)
418
- * **Region**: world
419
- * **SSL support**: yes
420
- * **Languages**: English
421
- * **Documentation**: http://resources.arcgis.com/en/help/arcgis-online-geocoding-rest-api/
422
- * **Terms of Service**: http://www.esri.com/software/arcgis/arcgisonline/services/geoservices
423
- * **Limitations**: ?
424
- * **Notes**: You can specify which projection you want to use by setting, for example: `Geocoder.configure(:esri => {:outSR => 102100})`.
425
-
426
- #### Data Science Toolkit (`:dstk`)
427
-
428
- Data Science Toolkit provides an API whose reponse format is like Google's but which can be set up as a privately hosted service.
429
-
430
- * **API key**: none
431
- * **Quota**: None quota if you are self-hosting the service.
432
- * **Region**: world
433
- * **SSL support**: ?
434
- * **Languages**: en
435
- * **Documentation**: http://www.datasciencetoolkit.org/developerdocs
436
- * **Terms of Service**: http://www.datasciencetoolkit.org/developerdocs#googlestylegeocoder
437
- * **Limitations**: No reverse geocoding.
438
- * **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")`.
439
-
440
- #### FreeGeoIP (`:freegeoip`)
441
-
442
- * **API key**: none
443
- * **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.
444
- * **Region**: world
445
- * **SSL support**: no
446
- * **Languages**: English
447
- * **Documentation**: http://github.com/fiorix/freegeoip/blob/master/README.md
448
- * **Terms of Service**: ?
449
- * **Limitations**: ?
450
-
451
- #### MaxMind Web Services (`:maxmind`)
452
-
453
- * **API key**: required
454
- * **Quota**: Request Packs can be purchased
455
- * **Region**: world
456
- * **SSL support**: yes
457
- * **Languages**: English
458
- * **Documentation**: http://www.maxmind.com/app/web_services
459
- * **Terms of Service**: ?
460
- * **Limitations**: ?
461
- * **Notes**: You must specify which MaxMind service you are using in your configuration. For example: `Geocoder.configure(:maxmind => {:service => :omni})`.
462
-
463
- #### Baidu (`:baidu`)
464
-
465
- * **API key**: required
466
- * **Quota**: No quota limits for geocoding
467
- * **Region**: China
468
- * **SSL support**: no
469
- * **Languages**: Chinese (Simplified)
470
- * **Documentation**: http://developer.baidu.com/map/webservice-geocoding.htm
471
- * **Terms of Service**: http://developer.baidu.com/map/law.htm
472
- * **Limitations**: Only good for non-commercial use. For commercial usage please check http://developer.baidu.com/map/question.htm#qa0013
473
- * **Notes**: To use Baidu set `Geocoder.configure(:lookup => :baidu, :api_key => "your_api_key")`.
474
-
475
- Caching
476
- -------
477
-
478
- 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:
479
-
480
- Geocoder.configure(:cache => Redis.new)
339
+ ```ruby
340
+ Geocoder.configure(cache: Redis.new)
341
+ ```
481
342
 
482
343
  This example uses Redis, but the cache store can be any object that supports these methods:
483
344
 
484
345
  * `store#[](key)` or `#get` or `#read` - retrieves a value
485
346
  * `store#[]=(key, value)` or `#set` or `#write` - stores a value
486
347
  * `store#del(url)` - deletes a value
348
+ * `store#keys` - (Optional) Returns array of keys. Used if you wish to expire the entire cache (see below).
487
349
 
488
350
  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).
489
351
 
352
+ When using Rails use the Generic cache store as an adapter around `Rails.cache`:
353
+
354
+ ```ruby
355
+ Geocoder.configure(cache: Geocoder::CacheStore::Generic.new(Rails.cache, {}))
356
+ ```
357
+
490
358
  You can also set a custom prefix to be used for cache keys:
491
359
 
492
- Geocoder.configure(:cache_prefix => "...")
360
+ ```ruby
361
+ Geocoder.configure(cache_options: { prefix: "..." })
362
+ ```
493
363
 
494
364
  By default the prefix is `geocoder:`
495
365
 
496
366
  If you need to expire cached content:
497
367
 
498
- Geocoder.cache.expire("http://...") # expire cached result for a URL
499
- Geocoder.cache.expire(:all) # expire all cached results
368
+ ```ruby
369
+ Geocoder::Lookup.get(Geocoder.config[:lookup]).cache.expire(:all) # expire cached results for current Lookup
370
+ Geocoder::Lookup.get(:nominatim).cache.expire("http://...") # expire cached result for a specific URL
371
+ Geocoder::Lookup.get(:nominatim).cache.expire(:all) # expire cached results for Google Lookup
372
+ # expire all cached results for all Lookups.
373
+ # Be aware that this methods spawns a new Lookup object for each Service
374
+ Geocoder::Lookup.all_services.each{|service| Geocoder::Lookup.get(service).cache.expire(:all)}
375
+ ```
500
376
 
501
- 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).
377
+ 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.
502
378
 
503
- For an example of a cache store with URL expiry please see examples/autoexpire_cache.rb
379
+ For an example of a cache store with URL expiry, please see examples/autoexpire_cache.rb
504
380
 
505
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._
506
382
 
507
383
 
508
- Forward and Reverse Geocoding in the Same Model
509
- -----------------------------------------------
384
+ Advanced Model Configuration
385
+ ----------------------------
510
386
 
511
- 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:
387
+ You are not stuck with the `latitude` and `longitude` database column names (with ActiveRecord) or the `coordinates` array (Mongo) for storing coordinates. For example:
512
388
 
513
- * one for storing the fetched address (reverse geocoding)
514
- * one for providing an address to use when fetching coordinates (forward geocoding)
389
+ ```ruby
390
+ geocoded_by :address, latitude: :lat, longitude: :lon # ActiveRecord
391
+ geocoded_by :address, coordinates: :coords # MongoDB
392
+ ```
515
393
 
516
- For example:
394
+ For reverse geocoding, you can specify the attribute where the address will be stored. For example:
517
395
 
518
- class Venue
396
+ ```ruby
397
+ reverse_geocoded_by :latitude, :longitude, address: :loc # ActiveRecord
398
+ reverse_geocoded_by :coordinates, address: :street_address # MongoDB
399
+ ```
519
400
 
520
- # build an address from street, city, and state attributes
521
- geocoded_by :address_from_components
401
+ To specify geocoding parameters in your model:
522
402
 
523
- # store the fetched address in the full_address attribute
524
- reverse_geocoded_by :latitude, :longitude, :address => :full_address
525
- end
403
+ ```ruby
404
+ geocoded_by :address, params: {region: "..."}
405
+ ```
526
406
 
527
- However, there can be only one set of latitude/longitude attributes, and whichever you specify last will be used. For example:
407
+ 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:
528
408
 
529
- class Venue
409
+ ```ruby
410
+ geocoded_by :address, lookup: lambda{ |obj| obj.geocoder_lookup }
530
411
 
531
- geocoded_by :address,
532
- :latitude => :fetched_latitude, # this will be overridden by the below
533
- :longitude => :fetched_longitude # same here
412
+ def geocoder_lookup
413
+ if country_code == "RU"
414
+ :yandex
415
+ elsif country_code == "CN"
416
+ :baidu
417
+ else
418
+ :nominatim
419
+ end
420
+ end
421
+ ```
534
422
 
535
- reverse_geocoded_by :latitude, :longitude
536
- end
423
+ ### Custom Result Handling
537
424
 
538
- The reason for this is that we don't want ambiguity when doing distance calculations. We need a single, authoritative source for coordinates!
425
+ 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:
539
426
 
540
- Once both forward and reverse geocoding has been applied, it is possible to call them sequentially.
427
+ ```ruby
428
+ reverse_geocoded_by :latitude, :longitude do |obj,results|
429
+ if geo = results.first
430
+ obj.city = geo.city
431
+ obj.zipcode = geo.postal_code
432
+ obj.country = geo.country_code
433
+ end
434
+ end
541
435
 
542
- For example:
436
+ after_validation :reverse_geocode
437
+ ```
543
438
 
544
- class Venue
439
+ Every `Geocoder::Result` object, `result`, provides the following data:
545
440
 
546
- after_validation :geocode, :reverse_geocode
441
+ * `result.latitude` - float
442
+ * `result.longitude` - float
443
+ * `result.coordinates` - array of the above two in the form of `[lat,lon]`
444
+ * `result.address` - string
445
+ * `result.city` - string
446
+ * `result.state` - string
447
+ * `result.state_code` - string
448
+ * `result.postal_code` - string
449
+ * `result.country` - string
450
+ * `result.country_code` - string
547
451
 
548
- end
452
+ Most APIs return other data in addition to these globally-supported attributes. To directly access the full response, call the `#data` method of any Geocoder::Result object. See the [API Guide](https://github.com/alexreisner/geocoder/blob/master/README_API_GUIDE.md) for links to documentation for all geocoding services.
549
453
 
550
- 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:
454
+ ### Forward and Reverse Geocoding in the Same Model
551
455
 
552
- after_validation :geocode
456
+ You can apply both forward and reverse geocoding to the same model (i.e. users can supply an address or coordinates and Geocoder fills in whatever's missing) but you'll need to provide two different address methods:
553
457
 
554
- 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.
458
+ * one for storing the fetched address (when reverse geocoding)
459
+ * one for providing an address to use when fetching coordinates (forward geocoding)
555
460
 
556
461
  For example:
557
462
 
558
- class Venue
463
+ ```ruby
464
+ class Venue
465
+ # build an address from street, city, and state attributes
466
+ geocoded_by :address_from_components
559
467
 
560
- after_validation :reverse_geocode, :if => :has_coordinates
561
- after_validation :geocode, :if => :has_location, :unless => :has_coordinates
468
+ # store the fetched address in the full_address attribute
469
+ reverse_geocoded_by :latitude, :longitude, address: :full_address
470
+ end
471
+ ```
562
472
 
563
- end
473
+ 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:
564
474
 
565
- Use Outside of Rails
566
- --------------------
475
+ ```ruby
476
+ class Venue
477
+ geocoded_by :address,
478
+ latitude: :fetched_latitude,
479
+ longitude: :fetched_longitude
480
+ reverse_geocoded_by :latitude, :longitude
481
+ end
482
+ ```
567
483
 
568
- You can use Geocoder outside of Rails by calling the `Geocoder.search` method:
569
484
 
570
- results = Geocoder.search("McCarren Park, Brooklyn, NY")
485
+ Advanced Database Queries
486
+ -------------------------
571
487
 
572
- This returns an array of `Geocoder::Result` objects with all data provided by the geocoding service.
488
+ *The following apply to ActiveRecord only. For MongoDB, please use the built-in geospatial features.*
573
489
 
490
+ The default `near` search looks for objects within a circle. To search within a doughnut or ring use the `:min_radius` option:
574
491
 
575
- Testing Apps that Use Geocoder
576
- ------------------------------
492
+ ```ruby
493
+ Venue.near("Austin, TX", 200, min_radius: 40)
494
+ ```
577
495
 
578
- 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:
496
+ To search within a rectangle (note that results will *not* include `distance` and `bearing` attributes):
579
497
 
580
- Geocoder.configure(:lookup => :test)
498
+ ```ruby
499
+ sw_corner = [40.71, 100.23]
500
+ ne_corner = [36.12, 88.65]
501
+ Venue.within_bounding_box(sw_corner, ne_corner)
502
+ ```
581
503
 
582
- Geocoder::Lookup::Test.add_stub(
583
- "New York, NY", [
584
- {
585
- 'latitude' => 40.7143528,
586
- 'longitude' => -74.0059731,
587
- 'address' => 'New York, NY, USA',
588
- 'state' => 'New York',
589
- 'state_code' => 'NY',
590
- 'country' => 'United States',
591
- 'country_code' => 'US'
592
- }
593
- ]
594
- )
504
+ 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:
595
505
 
596
- 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:
506
+ ```ruby
507
+ Venue.near([40.71, 99.23], :effective_radius)
508
+ ```
597
509
 
598
- Geocoder.configure(:lookup => :test)
510
+ If you store multiple sets of coordinates for each object, you can specify latitude and longitude columns to use for a search:
599
511
 
600
- Geocoder::Lookup::Test.set_default_stub(
601
- [
602
- {
603
- 'latitude' => 40.7143528,
604
- 'longitude' => -74.0059731,
605
- 'address' => 'New York, NY, USA',
606
- 'state' => 'New York',
607
- 'state_code' => 'NY',
608
- 'country' => 'United States',
609
- 'country_code' => 'US'
610
- }
611
- ]
612
- )
512
+ ```ruby
513
+ Venue.near("Paris", 50, latitude: :secondary_latitude, longitude: :secondary_longitude)
514
+ ```
613
515
 
614
- Any query that hasn't been explicitly stubbed will return that result.
516
+ ### Distance and Bearing
615
517
 
616
- Command Line Interface
617
- ----------------------
518
+ When you run a geospatial query, the returned objects have two attributes added:
618
519
 
619
- 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:
520
+ * `obj.distance` - number of miles from the search point to this object
521
+ * `obj.bearing` - direction from the search point to this object
620
522
 
621
- $ geocode 29.951,-90.081
622
- Latitude: 29.952211
623
- Longitude: -90.080563
624
- Full address: 1500 Sugar Bowl Dr, New Orleans, LA 70112, USA
625
- City: New Orleans
626
- State/province: Louisiana
627
- Postal code: 70112
628
- Country: United States
629
- Google map: http://maps.google.com/maps?q=29.952211,-90.080563
523
+ Results are automatically sorted by distance from the search point, closest to farthest. Bearing is given as a number of degrees clockwise from due north, for example:
630
524
 
631
- 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.
525
+ * `0` - due north
526
+ * `180` - due south
527
+ * `90` - due east
528
+ * `270` - due west
529
+ * `230.1` - southwest
530
+ * `359.9` - almost due north
632
531
 
633
- Numeric Data Types and Precision
634
- --------------------------------
532
+ You can convert these to compass point names via provided method:
635
533
 
636
- Geocoder works with any numeric data type (e.g. float, double, decimal) on which trig (and other mathematical) functions can be performed.
534
+ ```ruby
535
+ Geocoder::Calculations.compass_point(355) # => "N"
536
+ Geocoder::Calculations.compass_point(45) # => "NE"
537
+ Geocoder::Calculations.compass_point(208) # => "SW"
538
+ ```
637
539
 
638
- 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.
540
+ _Note: when running queries on SQLite, `distance` and `bearing` are provided for consistency only. They are not very accurate._
639
541
 
640
- Notes on MongoDB
641
- ----------------
542
+ For more advanced geospatial querying, please see the [rgeo gem](https://github.com/rgeo/rgeo).
642
543
 
643
- ### The Near Method
644
544
 
645
- 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.
545
+ Geospatial Calculations
546
+ -----------------------
646
547
 
647
- ### Latitude/Longitude Order
548
+ The `Geocoder::Calculations` module contains some useful methods:
648
549
 
649
- 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.
550
+ ```ruby
551
+ # find the distance between two arbitrary points
552
+ Geocoder::Calculations.distance_between([47.858205,2.294359], [40.748433,-73.985655])
553
+ => 3619.77359999382 # in configured units (default miles)
650
554
 
651
- To access an object's coordinates in the conventional order, use the `to_coordinates` instance method provided by Geocoder. For example:
555
+ # find the geographic center (aka center of gravity) of objects or points
556
+ Geocoder::Calculations.geographic_center([city1, city2, [40.22,-73.99], city4])
557
+ => [35.14968, -90.048929]
558
+ ```
652
559
 
653
- obj.to_coordinates # => [37.7941013, -122.3951096] # [lat, lon]
560
+ See [the code](https://github.com/alexreisner/geocoder/blob/master/lib/geocoder/calculations.rb) for more!
654
561
 
655
- 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:
656
562
 
657
- obj.coordinates # => [-122.3951096, 37.7941013] # [lon, lat]
563
+ Batch Geocoding
564
+ ---------------
658
565
 
659
- For consistency with the rest of Geocoder, always use the `to_coordinates` method instead.
566
+ 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:
660
567
 
661
- Notes on Non-Rails Frameworks
662
- -----------------------------
568
+ ```sh
569
+ rake geocode:all CLASS=YourModel
570
+ ```
663
571
 
664
- 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:
572
+ If you need reverse geocoding instead, call the task with REVERSE=true:
665
573
 
666
- extend Geocoder::Model::ActiveRecord
574
+ ```sh
575
+ rake geocode:all CLASS=YourModel REVERSE=true
576
+ ```
667
577
 
668
- Optimisation of Distance Queries
669
- --------------------------------
578
+ 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:
670
579
 
671
- 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.
580
+ ```sh
581
+ rake geocode:all CLASS=YourModel SLEEP=0.25 BATCH=100
582
+ ```
672
583
 
673
- To take advantage of this optimisation you need to add a composite index on latitude and longitude. In your Rails migration:
584
+ To avoid exceeding per-day limits you can add a `LIMIT` option. However, this will ignore the `BATCH` value, if provided.
674
585
 
675
- add_index :table, [:latitude, :longitude]
586
+ ```sh
587
+ rake geocode:all CLASS=YourModel LIMIT=1000
588
+ ```
676
589
 
677
590
 
678
- Distance Queries in SQLite
679
- --------------------------
591
+ Testing
592
+ -------
680
593
 
681
- 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.
594
+ 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`
595
+
596
+ ```ruby
597
+ Geocoder.configure(lookup: :test, ip_lookup: :test)
598
+ ```
599
+
600
+ Add stubs to define the results that will be returned:
601
+
602
+ ```ruby
603
+ Geocoder::Lookup::Test.add_stub(
604
+ "New York, NY", [
605
+ {
606
+ 'coordinates' => [40.7143528, -74.0059731],
607
+ 'address' => 'New York, NY, USA',
608
+ 'state' => 'New York',
609
+ 'state_code' => 'NY',
610
+ 'country' => 'United States',
611
+ 'country_code' => 'US'
612
+ }
613
+ ]
614
+ )
615
+ ```
616
+
617
+ 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:
618
+
619
+ ```ruby
620
+ Geocoder::Lookup::Test.set_default_stub(
621
+ [
622
+ {
623
+ 'coordinates' => [40.7143528, -74.0059731],
624
+ 'address' => 'New York, NY, USA',
625
+ 'state' => 'New York',
626
+ 'state_code' => 'NY',
627
+ 'country' => 'United States',
628
+ 'country_code' => 'US'
629
+ }
630
+ ]
631
+ )
632
+ ```
633
+
634
+ You may also delete a single stub, or reset all stubs _including the default stub_:
635
+
636
+ ```ruby
637
+ Geocoder::Lookup::Test.delete_stub('New York, NY')
638
+ Geocoder::Lookup::Test.reset
639
+ ```
640
+
641
+ Notes:
642
+
643
+ - Keys must be strings (not symbols) when calling `add_stub` or `set_default_stub`. For example `'country' =>` not `:country =>`.
644
+ - The stubbed result objects returned by the Test lookup do not support all the methods real result objects do. If you need to test interaction with real results it may be better to use an external stubbing tool and something like WebMock or VCR to prevent network calls.
682
645
 
683
646
 
684
- ### Discussion
647
+ Error Handling
648
+ --------------
685
649
 
686
- There are few options for finding objects near a given point in SQLite without installing extensions:
650
+ 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:
687
651
 
688
- 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.
652
+ ```ruby
653
+ Geocoder.configure(always_raise: [SocketError, Timeout::Error])
654
+ ```
689
655
 
690
- 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.
656
+ You can also do this to raise all exceptions:
691
657
 
692
- 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`.
658
+ ```ruby
659
+ Geocoder.configure(always_raise: :all)
660
+ ```
693
661
 
694
- 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.
662
+ The raise-able exceptions are:
695
663
 
664
+ ```ruby
665
+ SocketError
666
+ Timeout::Error
667
+ Geocoder::OverQueryLimitError
668
+ Geocoder::RequestDenied
669
+ Geocoder::InvalidRequest
670
+ Geocoder::InvalidApiKey
671
+ Geocoder::ServiceUnavailable
672
+ ```
696
673
 
697
- Tests
698
- -----
674
+ 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.
699
675
 
700
- 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:
701
676
 
702
- http://github.com/alexreisner/geocoder_test
677
+ Command Line Interface
678
+ ----------------------
703
679
 
680
+ 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:
704
681
 
705
- Error Handling
706
- --------------
682
+ ```sh
683
+ $ geocode 29.951,-90.081
684
+ Latitude: 29.952211
685
+ Longitude: -90.080563
686
+ Full address: 1500 Sugar Bowl Dr, New Orleans, LA 70112, USA
687
+ City: New Orleans
688
+ State/province: Louisiana
689
+ Postal code: 70112
690
+ Country: United States
691
+ Map: http://maps.google.com/maps?q=29.952211,-90.080563
692
+ ```
707
693
 
708
- By default Geocoder will rescue any exceptions raised by calls to a geocoding service and return an empty array (using warn() to inform you of the error). You can override this on a per-exception basis, and also have Geocoder raise its own exceptions for certain events (eg: API quota exceeded) by using the `:always_raise` option:
694
+ 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.
709
695
 
710
- Geocoder.configure(:always_raise => [SocketError, TimeoutError])
711
696
 
712
- You can also do this to raise all exceptions:
697
+ Technical Discussions
698
+ ---------------------
713
699
 
714
- Geocoder.configure(:always_raise => :all)
700
+ ### Distance Queries in SQLite
715
701
 
716
- The raise-able exceptions are:
702
+ 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.
703
+
704
+ There are few options for finding objects near a given point in SQLite without installing extensions:
705
+
706
+ 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.
707
+
708
+ 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.
709
+
710
+ 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`.
711
+
712
+ 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.
717
713
 
718
- SocketError
719
- TimeoutError
720
- Geocoder::OverQueryLimitError
721
- Geocoder::RequestDenied
722
- Geocoder::InvalidRequest
723
- Geocoder::InvalidApiKey
714
+ ### Numeric Data Types and Precision
724
715
 
725
- Note that not all lookups support all exceptions.
716
+ Geocoder works with any numeric data type (e.g. float, double, decimal) on which trig (and other mathematical) functions can be performed.
717
+
718
+ 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.
726
719
 
727
720
 
728
721
  Troubleshooting
@@ -732,8 +725,10 @@ Troubleshooting
732
725
 
733
726
  If you get one of these errors:
734
727
 
735
- uninitialized constant Geocoder::Model::Mongoid
736
- uninitialized constant Geocoder::Model::Mongoid::Mongo
728
+ ```ruby
729
+ uninitialized constant Geocoder::Model::Mongoid
730
+ uninitialized constant Geocoder::Model::Mongoid::Mongo
731
+ ```
737
732
 
738
733
  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.
739
734
 
@@ -744,53 +739,62 @@ A lot of debugging time can be saved by understanding how Geocoder works with Ac
744
739
  * using the `pluck` method (selects only a single column)
745
740
  * specifying another model through `includes` (selects columns from other tables)
746
741
 
742
+ ### Geocoding is Slow
743
+
744
+ 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.
745
+
746
+ 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.
747
+
748
+ 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.
749
+
750
+ 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.
751
+
747
752
  ### Unexpected Responses from Geocoding Services
748
753
 
749
- Take a look at the server's raw JSON response. You can do this by getting the request URL in an app console:
754
+ Take a look at the server's raw response. You can do this by getting the request URL in an app console:
755
+
756
+ ```ruby
757
+ Geocoder::Lookup.get(:nominatim).query_url(Geocoder::Query.new("..."))
758
+ ```
750
759
 
751
- Geocoder::Lookup.get(:google).query_url(Geocoder::Query.new("..."))
760
+ 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.
752
761
 
753
- 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.
762
+ You can also fetch the response in the console:
754
763
 
764
+ ```ruby
765
+ Geocoder::Lookup.get(:nominatim).send(:fetch_raw_data, Geocoder::Query.new("..."))
766
+ ```
755
767
 
756
- Reporting Issues
757
- ----------------
758
768
 
759
- 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?).
769
+ Known Issues
770
+ ------------
771
+
772
+ ### Using `count` with Rails 4.1+
760
773
 
774
+ 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.
761
775
 
762
- Known Issue
763
- -----------
776
+ ### Using `near` with `includes`
764
777
 
765
778
  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).
766
779
 
767
780
  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:
768
781
 
769
- # Pass a :select option to the near scope to get the columns you want.
770
- # Instead of City.near(...).includes(:venues), try:
771
- City.near("Omaha, NE", 20, :select => "cities.*, venues.*").joins(:venues)
782
+ ```ruby
783
+ # Pass a :select option to the near scope to get the columns you want.
784
+ # Instead of City.near(...).includes(:venues), try:
785
+ City.near("Omaha, NE", 20, select: "cities.*, venues.*").joins(:venues)
772
786
 
773
- # This preload call will normally trigger two queries regardless of the
774
- # number of results; one query on hotels, and one query on administrators.
775
- # Instead of Hotel.near(...).includes(:administrator), try:
776
- Hotel.near("London, UK", 50).joins(:administrator).preload(:administrator)
787
+ # This preload call will normally trigger two queries regardless of the
788
+ # number of results; one query on hotels, and one query on administrators.
789
+ # Instead of Hotel.near(...).includes(:administrator), try:
790
+ Hotel.near("London, UK", 50).joins(:administrator).preload(:administrator)
791
+ ```
777
792
 
778
793
  If anyone has a more elegant solution to this problem I am very interested in seeing it.
779
794
 
795
+ ### Using `near` with objects close to the 180th meridian
780
796
 
781
- Contributing
782
- ------------
783
-
784
- Contributions are welcome via pull requests on Github. Please respect the following guidelines:
785
-
786
- * 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.
787
- * Do not commit changes to files that are irrelevant to your feature or bugfix (eg: `.gitignore`).
788
- * Do not add dependencies on other gems.
789
- * Do not add unnecessary `require` statements which could cause LoadErrors on certain systems.
790
- * Remember: Geocoder needs to run outside of Rails. Don't assume things like ActiveSupport are available.
791
- * Do not add to base configuration options; instead document required lookup-specific options in the README.
792
- * 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.
793
- * Be aware that the pull request review process is not immediate, and is generally proportional to the size of the pull request.
797
+ The `near` method will not look across the 180th meridian to find objects close to a given point. In practice this is rarely an issue outside of New Zealand and certain surrounding islands. This problem does not exist with the zero-meridian. The problem is due to a shortcoming of the Haversine formula which Geocoder uses to calculate distances.
794
798
 
795
799
 
796
- Copyright (c) 2009-12 Alex Reisner, released under the MIT license
800
+ Copyright :copyright: 2009-2021 Alex Reisner, released under the MIT license.