geocoder-kb 1.2.6
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/.gitignore +6 -0
- data/.travis.yml +31 -0
- data/CHANGELOG.md +384 -0
- data/LICENSE +20 -0
- data/README.md +1085 -0
- data/Rakefile +25 -0
- data/bin/geocode +5 -0
- data/examples/autoexpire_cache_dalli.rb +62 -0
- data/examples/autoexpire_cache_redis.rb +28 -0
- data/examples/cache_bypass.rb +48 -0
- data/examples/sidekiq_worker.rb +16 -0
- data/gemfiles/Gemfile.mongoid-2.4.x +16 -0
- data/lib/generators/geocoder/config/config_generator.rb +14 -0
- data/lib/generators/geocoder/config/templates/initializer.rb +21 -0
- data/lib/generators/geocoder/maxmind/geolite_city_generator.rb +28 -0
- data/lib/generators/geocoder/maxmind/geolite_country_generator.rb +28 -0
- data/lib/generators/geocoder/maxmind/templates/migration/geolite_city.rb +30 -0
- data/lib/generators/geocoder/maxmind/templates/migration/geolite_country.rb +17 -0
- data/lib/geocoder.rb +47 -0
- data/lib/geocoder/cache.rb +90 -0
- data/lib/geocoder/calculations.rb +428 -0
- data/lib/geocoder/cli.rb +121 -0
- data/lib/geocoder/configuration.rb +124 -0
- data/lib/geocoder/configuration_hash.rb +11 -0
- data/lib/geocoder/exceptions.rb +21 -0
- data/lib/geocoder/ip_address.rb +21 -0
- data/lib/geocoder/lookup.rb +102 -0
- data/lib/geocoder/lookups/amap.rb +55 -0
- data/lib/geocoder/lookups/baidu.rb +55 -0
- data/lib/geocoder/lookups/baidu_ip.rb +54 -0
- data/lib/geocoder/lookups/base.rb +302 -0
- data/lib/geocoder/lookups/bing.rb +59 -0
- data/lib/geocoder/lookups/dstk.rb +20 -0
- data/lib/geocoder/lookups/esri.rb +48 -0
- data/lib/geocoder/lookups/freegeoip.rb +47 -0
- data/lib/geocoder/lookups/geocoder_ca.rb +54 -0
- data/lib/geocoder/lookups/geocoder_us.rb +39 -0
- data/lib/geocoder/lookups/geocodio.rb +42 -0
- data/lib/geocoder/lookups/geoip2.rb +40 -0
- data/lib/geocoder/lookups/google.rb +67 -0
- data/lib/geocoder/lookups/google_places_details.rb +50 -0
- data/lib/geocoder/lookups/google_premier.rb +47 -0
- data/lib/geocoder/lookups/here.rb +62 -0
- data/lib/geocoder/lookups/mapquest.rb +60 -0
- data/lib/geocoder/lookups/maxmind.rb +90 -0
- data/lib/geocoder/lookups/maxmind_local.rb +58 -0
- data/lib/geocoder/lookups/nominatim.rb +52 -0
- data/lib/geocoder/lookups/okf.rb +43 -0
- data/lib/geocoder/lookups/opencagedata.rb +58 -0
- data/lib/geocoder/lookups/ovi.rb +62 -0
- data/lib/geocoder/lookups/pointpin.rb +68 -0
- data/lib/geocoder/lookups/postcode_anywhere_uk.rb +51 -0
- data/lib/geocoder/lookups/smarty_streets.rb +45 -0
- data/lib/geocoder/lookups/telize.rb +40 -0
- data/lib/geocoder/lookups/test.rb +44 -0
- data/lib/geocoder/lookups/yahoo.rb +88 -0
- data/lib/geocoder/lookups/yandex.rb +54 -0
- data/lib/geocoder/models/active_record.rb +50 -0
- data/lib/geocoder/models/base.rb +39 -0
- data/lib/geocoder/models/mongo_base.rb +64 -0
- data/lib/geocoder/models/mongo_mapper.rb +26 -0
- data/lib/geocoder/models/mongoid.rb +32 -0
- data/lib/geocoder/query.rb +111 -0
- data/lib/geocoder/railtie.rb +26 -0
- data/lib/geocoder/request.rb +25 -0
- data/lib/geocoder/results/amap.rb +85 -0
- data/lib/geocoder/results/baidu.rb +79 -0
- data/lib/geocoder/results/baidu_ip.rb +62 -0
- data/lib/geocoder/results/base.rb +67 -0
- data/lib/geocoder/results/bing.rb +48 -0
- data/lib/geocoder/results/dstk.rb +6 -0
- data/lib/geocoder/results/esri.rb +51 -0
- data/lib/geocoder/results/freegeoip.rb +45 -0
- data/lib/geocoder/results/geocoder_ca.rb +60 -0
- data/lib/geocoder/results/geocoder_us.rb +39 -0
- data/lib/geocoder/results/geocodio.rb +66 -0
- data/lib/geocoder/results/geoip2.rb +64 -0
- data/lib/geocoder/results/google.rb +124 -0
- data/lib/geocoder/results/google_places_details.rb +35 -0
- data/lib/geocoder/results/google_premier.rb +6 -0
- data/lib/geocoder/results/here.rb +62 -0
- data/lib/geocoder/results/mapquest.rb +51 -0
- data/lib/geocoder/results/maxmind.rb +135 -0
- data/lib/geocoder/results/maxmind_local.rb +49 -0
- data/lib/geocoder/results/nominatim.rb +94 -0
- data/lib/geocoder/results/okf.rb +106 -0
- data/lib/geocoder/results/opencagedata.rb +82 -0
- data/lib/geocoder/results/ovi.rb +62 -0
- data/lib/geocoder/results/pointpin.rb +44 -0
- data/lib/geocoder/results/postcode_anywhere_uk.rb +42 -0
- data/lib/geocoder/results/smarty_streets.rb +106 -0
- data/lib/geocoder/results/telize.rb +45 -0
- data/lib/geocoder/results/test.rb +33 -0
- data/lib/geocoder/results/yahoo.rb +55 -0
- data/lib/geocoder/results/yandex.rb +84 -0
- data/lib/geocoder/sql.rb +107 -0
- data/lib/geocoder/stores/active_record.rb +289 -0
- data/lib/geocoder/stores/base.rb +127 -0
- data/lib/geocoder/stores/mongo_base.rb +89 -0
- data/lib/geocoder/stores/mongo_mapper.rb +13 -0
- data/lib/geocoder/stores/mongoid.rb +13 -0
- data/lib/geocoder/version.rb +3 -0
- data/lib/hash_recursive_merge.rb +74 -0
- data/lib/maxmind_database.rb +109 -0
- data/lib/oauth_util.rb +112 -0
- data/lib/tasks/geocoder.rake +29 -0
- data/lib/tasks/maxmind.rake +73 -0
- data/test/fixtures/baidu_invalid_key +1 -0
- data/test/fixtures/baidu_ip_202_198_16_3 +19 -0
- data/test/fixtures/baidu_ip_invalid_key +1 -0
- data/test/fixtures/baidu_ip_no_results +1 -0
- data/test/fixtures/baidu_no_results +1 -0
- data/test/fixtures/baidu_reverse +1 -0
- data/test/fixtures/baidu_shanghai_pearl_tower +12 -0
- data/test/fixtures/bing_invalid_key +1 -0
- data/test/fixtures/bing_madison_square_garden +40 -0
- data/test/fixtures/bing_no_results +16 -0
- data/test/fixtures/bing_reverse +42 -0
- data/test/fixtures/cloudmade_invalid_key +1 -0
- data/test/fixtures/cloudmade_madison_square_garden +1 -0
- data/test/fixtures/cloudmade_no_results +1 -0
- data/test/fixtures/esri_madison_square_garden +59 -0
- data/test/fixtures/esri_no_results +8 -0
- data/test/fixtures/esri_reverse +21 -0
- data/test/fixtures/freegeoip_74_200_247_59 +12 -0
- data/test/fixtures/freegeoip_no_results +1 -0
- data/test/fixtures/geocoder_ca_madison_square_garden +1 -0
- data/test/fixtures/geocoder_ca_no_results +1 -0
- data/test/fixtures/geocoder_ca_reverse +34 -0
- data/test/fixtures/geocoder_us_madison_square_garden +1 -0
- data/test/fixtures/geocoder_us_no_results +1 -0
- data/test/fixtures/geocodio_1101_pennsylvania_ave +1 -0
- data/test/fixtures/geocodio_bad_api_key +3 -0
- data/test/fixtures/geocodio_invalid +4 -0
- data/test/fixtures/geocodio_no_results +1 -0
- data/test/fixtures/geocodio_over_query_limit +4 -0
- data/test/fixtures/google_garbage +456 -0
- data/test/fixtures/google_madison_square_garden +57 -0
- data/test/fixtures/google_no_city_data +44 -0
- data/test/fixtures/google_no_locality +51 -0
- data/test/fixtures/google_no_results +4 -0
- data/test/fixtures/google_over_limit +4 -0
- data/test/fixtures/google_places_details_invalid_request +4 -0
- data/test/fixtures/google_places_details_madison_square_garden +120 -0
- data/test/fixtures/google_places_details_no_results +4 -0
- data/test/fixtures/google_places_details_no_reviews +60 -0
- data/test/fixtures/google_places_details_no_types +66 -0
- data/test/fixtures/here_madison_square_garden +72 -0
- data/test/fixtures/here_no_results +8 -0
- data/test/fixtures/mapquest_error +16 -0
- data/test/fixtures/mapquest_invalid_api_key +16 -0
- data/test/fixtures/mapquest_invalid_request +16 -0
- data/test/fixtures/mapquest_madison_square_garden +52 -0
- data/test/fixtures/mapquest_no_results +16 -0
- data/test/fixtures/maxmind_24_24_24_21 +1 -0
- data/test/fixtures/maxmind_24_24_24_22 +1 -0
- data/test/fixtures/maxmind_24_24_24_23 +1 -0
- data/test/fixtures/maxmind_24_24_24_24 +1 -0
- data/test/fixtures/maxmind_74_200_247_59 +1 -0
- data/test/fixtures/maxmind_invalid_key +1 -0
- data/test/fixtures/maxmind_no_results +1 -0
- data/test/fixtures/nominatim_madison_square_garden +150 -0
- data/test/fixtures/nominatim_no_results +1 -0
- data/test/fixtures/nominatim_over_limit +1 -0
- data/test/fixtures/okf_kirstinmaki +67 -0
- data/test/fixtures/okf_no_results +4 -0
- data/test/fixtures/opencagedata_invalid_api_key +25 -0
- data/test/fixtures/opencagedata_invalid_request +26 -0
- data/test/fixtures/opencagedata_madison_square_garden +73 -0
- data/test/fixtures/opencagedata_no_results +29 -0
- data/test/fixtures/opencagedata_over_limit +31 -0
- data/test/fixtures/ovi_madison_square_garden +72 -0
- data/test/fixtures/ovi_no_results +8 -0
- data/test/fixtures/pointpin_10_10_10_10 +1 -0
- data/test/fixtures/pointpin_555_555_555_555 +1 -0
- data/test/fixtures/pointpin_80_111_555_555 +1 -0
- data/test/fixtures/pointpin_no_results +1 -0
- data/test/fixtures/postcode_anywhere_uk_geocode_v2_00_WR26NJ +1 -0
- data/test/fixtures/postcode_anywhere_uk_geocode_v2_00_generic_error +1 -0
- data/test/fixtures/postcode_anywhere_uk_geocode_v2_00_hampshire +1 -0
- data/test/fixtures/postcode_anywhere_uk_geocode_v2_00_key_limit_exceeded +1 -0
- data/test/fixtures/postcode_anywhere_uk_geocode_v2_00_no_results +1 -0
- data/test/fixtures/postcode_anywhere_uk_geocode_v2_00_romsey +1 -0
- data/test/fixtures/postcode_anywhere_uk_geocode_v2_00_unknown_key +1 -0
- data/test/fixtures/smarty_streets_11211 +1 -0
- data/test/fixtures/smarty_streets_madison_square_garden +47 -0
- data/test/fixtures/smarty_streets_no_results +1 -0
- data/test/fixtures/telize_10_10_10_10 +1 -0
- data/test/fixtures/telize_555_555_555_555 +4 -0
- data/test/fixtures/telize_74_200_247_59 +1 -0
- data/test/fixtures/telize_no_results +1 -0
- data/test/fixtures/yahoo_error +1 -0
- data/test/fixtures/yahoo_invalid_key +2 -0
- data/test/fixtures/yahoo_madison_square_garden +52 -0
- data/test/fixtures/yahoo_no_results +10 -0
- data/test/fixtures/yahoo_over_limit +2 -0
- data/test/fixtures/yandex_canada_rue_dupuis_14 +446 -0
- data/test/fixtures/yandex_invalid_key +1 -0
- data/test/fixtures/yandex_kremlin +48 -0
- data/test/fixtures/yandex_new_york +1 -0
- data/test/fixtures/yandex_no_city_and_town +112 -0
- data/test/fixtures/yandex_no_results +16 -0
- data/test/integration/http_client_test.rb +31 -0
- data/test/mongoid_test_helper.rb +43 -0
- data/test/test_helper.rb +416 -0
- data/test/unit/active_record_test.rb +16 -0
- data/test/unit/cache_test.rb +37 -0
- data/test/unit/calculations_test.rb +220 -0
- data/test/unit/configuration_test.rb +55 -0
- data/test/unit/error_handling_test.rb +56 -0
- data/test/unit/geocoder_test.rb +78 -0
- data/test/unit/https_test.rb +17 -0
- data/test/unit/ip_address_test.rb +27 -0
- data/test/unit/lookup_test.rb +153 -0
- data/test/unit/lookups/bing_test.rb +68 -0
- data/test/unit/lookups/dstk_test.rb +26 -0
- data/test/unit/lookups/esri_test.rb +48 -0
- data/test/unit/lookups/freegeoip_test.rb +27 -0
- data/test/unit/lookups/geocoder_ca_test.rb +17 -0
- data/test/unit/lookups/geocodio_test.rb +55 -0
- data/test/unit/lookups/geoip2_test.rb +27 -0
- data/test/unit/lookups/google_places_details_test.rb +122 -0
- data/test/unit/lookups/google_premier_test.rb +22 -0
- data/test/unit/lookups/google_test.rb +84 -0
- data/test/unit/lookups/mapquest_test.rb +60 -0
- data/test/unit/lookups/maxmind_local_test.rb +28 -0
- data/test/unit/lookups/maxmind_test.rb +63 -0
- data/test/unit/lookups/nominatim_test.rb +31 -0
- data/test/unit/lookups/okf_test.rb +38 -0
- data/test/unit/lookups/opencagedata_test.rb +64 -0
- data/test/unit/lookups/pointpin_test.rb +30 -0
- data/test/unit/lookups/postcode_anywhere_uk_test.rb +70 -0
- data/test/unit/lookups/smarty_streets_test.rb +71 -0
- data/test/unit/lookups/telize_test.rb +36 -0
- data/test/unit/lookups/yahoo_test.rb +35 -0
- data/test/unit/method_aliases_test.rb +26 -0
- data/test/unit/model_test.rb +38 -0
- data/test/unit/mongoid_test.rb +47 -0
- data/test/unit/near_test.rb +87 -0
- data/test/unit/oauth_util_test.rb +31 -0
- data/test/unit/proxy_test.rb +37 -0
- data/test/unit/query_test.rb +52 -0
- data/test/unit/rake_task_test.rb +21 -0
- data/test/unit/request_test.rb +35 -0
- data/test/unit/result_test.rb +72 -0
- data/test/unit/test_mode_test.rb +70 -0
- metadata +294 -0
data/README.md
ADDED
@@ -0,0 +1,1085 @@
|
|
1
|
+
Geocoder
|
2
|
+
========
|
3
|
+
|
4
|
+
Geocoder is a complete geocoding solution for Ruby. With Rails it adds geocoding (by street or IP address), reverse geocoding (find street address based on given coordinates), and distance queries. It's as simple as calling `geocode` on your objects, and then using a scope like `Venue.near("Billings, MT")`.
|
5
|
+
|
6
|
+
|
7
|
+
Compatibility
|
8
|
+
-------------
|
9
|
+
|
10
|
+
* Supports multiple Ruby versions: Ruby 1.9.2, 1.9.3, 2.0.0, 2.1.0, JRuby and Rubinius.
|
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.
|
14
|
+
|
15
|
+
|
16
|
+
Rails 4.1 Note
|
17
|
+
--------------
|
18
|
+
|
19
|
+
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.
|
20
|
+
|
21
|
+
|
22
|
+
Installation
|
23
|
+
------------
|
24
|
+
|
25
|
+
Install Geocoder like any other Ruby gem:
|
26
|
+
|
27
|
+
gem install geocoder
|
28
|
+
|
29
|
+
Or, if you're using Rails/Bundler, add this to your Gemfile:
|
30
|
+
|
31
|
+
gem "geocoder"
|
32
|
+
|
33
|
+
and run at the command prompt:
|
34
|
+
|
35
|
+
bundle install
|
36
|
+
|
37
|
+
|
38
|
+
Object Geocoding
|
39
|
+
----------------
|
40
|
+
|
41
|
+
### ActiveRecord
|
42
|
+
|
43
|
+
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):
|
44
|
+
|
45
|
+
rails generate migration AddLatitudeAndLongitudeToModel latitude:float longitude:float
|
46
|
+
rake db:migrate
|
47
|
+
|
48
|
+
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`).
|
49
|
+
|
50
|
+
Next, your model must tell Geocoder which method returns your object's geocodable address:
|
51
|
+
|
52
|
+
geocoded_by :full_street_address # can also be an IP address
|
53
|
+
after_validation :geocode # auto-fetch coordinates
|
54
|
+
|
55
|
+
For reverse geocoding, tell Geocoder which attributes store latitude and longitude:
|
56
|
+
|
57
|
+
reverse_geocoded_by :latitude, :longitude
|
58
|
+
after_validation :reverse_geocode # auto-fetch address
|
59
|
+
|
60
|
+
### Mongoid
|
61
|
+
|
62
|
+
First, your model must have an array field for storing coordinates:
|
63
|
+
|
64
|
+
field :coordinates, :type => Array
|
65
|
+
|
66
|
+
You may also want an address field, like this:
|
67
|
+
|
68
|
+
field :address
|
69
|
+
|
70
|
+
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.
|
71
|
+
|
72
|
+
Once your fields are defined, include the `Geocoder::Model::Mongoid` module and then call `geocoded_by`:
|
73
|
+
|
74
|
+
include Geocoder::Model::Mongoid
|
75
|
+
geocoded_by :address # can also be an IP address
|
76
|
+
after_validation :geocode # auto-fetch coordinates
|
77
|
+
|
78
|
+
Reverse geocoding is similar:
|
79
|
+
|
80
|
+
include Geocoder::Model::Mongoid
|
81
|
+
reverse_geocoded_by :coordinates
|
82
|
+
after_validation :reverse_geocode # auto-fetch address
|
83
|
+
|
84
|
+
Once you've set up your model you'll need to create the necessary spatial indices in your database:
|
85
|
+
|
86
|
+
rake db:mongoid:create_indexes
|
87
|
+
|
88
|
+
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.
|
89
|
+
|
90
|
+
### MongoMapper
|
91
|
+
|
92
|
+
MongoMapper is very similar to Mongoid, just be sure to include `Geocoder::Model::MongoMapper`.
|
93
|
+
|
94
|
+
### Mongo Indices
|
95
|
+
|
96
|
+
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:
|
97
|
+
|
98
|
+
include Geocoder::Model::Mongoid
|
99
|
+
geocoded_by :address, :skip_index => true
|
100
|
+
|
101
|
+
### Bulk Geocoding
|
102
|
+
|
103
|
+
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:
|
104
|
+
|
105
|
+
rake geocode:all CLASS=YourModel
|
106
|
+
|
107
|
+
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:
|
108
|
+
|
109
|
+
rake geocode:all CLASS=YourModel SLEEP=0.25 BATCH=100
|
110
|
+
|
111
|
+
### Avoiding Unnecessary API Requests
|
112
|
+
|
113
|
+
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:
|
114
|
+
|
115
|
+
* an address is present
|
116
|
+
* the address has been changed since last save (or it has never been saved)
|
117
|
+
|
118
|
+
The exact code will vary depending on the method you use for your geocodable string, but it would be something like this:
|
119
|
+
|
120
|
+
after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }
|
121
|
+
|
122
|
+
|
123
|
+
Request Geocoding by IP Address
|
124
|
+
-------------------------------
|
125
|
+
|
126
|
+
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:
|
127
|
+
|
128
|
+
# returns Geocoder::Result object
|
129
|
+
result = request.location
|
130
|
+
|
131
|
+
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.
|
132
|
+
|
133
|
+
See _Advanced Geocoding_ below for more information about `Geocoder::Result` objects.
|
134
|
+
|
135
|
+
|
136
|
+
Location-Aware Database Queries
|
137
|
+
-------------------------------
|
138
|
+
|
139
|
+
To find objects by location, use the following scopes:
|
140
|
+
|
141
|
+
Venue.near('Omaha, NE, US', 20) # venues within 20 miles of Omaha
|
142
|
+
Venue.near([40.71, 100.23], 20) # venues within 20 miles of a point
|
143
|
+
Venue.near([40.71, 100.23], 20, :units => :km)
|
144
|
+
# venues within 20 kilometres of a point
|
145
|
+
Venue.geocoded # venues with coordinates
|
146
|
+
Venue.not_geocoded # venues without coordinates
|
147
|
+
|
148
|
+
With geocoded objects you can do things like this:
|
149
|
+
|
150
|
+
if obj.geocoded?
|
151
|
+
obj.nearbys(30) # other objects within 30 miles
|
152
|
+
obj.distance_from([40.714,-100.234]) # distance from arbitrary point to object
|
153
|
+
obj.bearing_to("Paris, France") # direction from object to arbitrary point
|
154
|
+
end
|
155
|
+
|
156
|
+
Some utility methods are also available:
|
157
|
+
|
158
|
+
# look up coordinates of some location (like searching Google Maps)
|
159
|
+
Geocoder.coordinates("25 Main St, Cooperstown, NY")
|
160
|
+
=> [42.700149, -74.922767]
|
161
|
+
|
162
|
+
# distance (in miles) between Eiffel Tower and Empire State Building
|
163
|
+
Geocoder::Calculations.distance_between([47.858205,2.294359], [40.748433,-73.985655])
|
164
|
+
=> 3619.77359999382
|
165
|
+
|
166
|
+
# find the geographic center (aka center of gravity) of objects or points
|
167
|
+
Geocoder::Calculations.geographic_center([city1, city2, [40.22,-73.99], city4])
|
168
|
+
=> [35.14968, -90.048929]
|
169
|
+
|
170
|
+
Please see the code for more methods and detailed information about arguments (eg, working with kilometers).
|
171
|
+
|
172
|
+
|
173
|
+
Distance and Bearing
|
174
|
+
--------------------
|
175
|
+
|
176
|
+
When you run a location-aware query the returned objects have two attributes added to them (only w/ ActiveRecord):
|
177
|
+
|
178
|
+
* `obj.distance` - number of miles from the search point to this object
|
179
|
+
* `obj.bearing` - direction from the search point to this object
|
180
|
+
|
181
|
+
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:
|
182
|
+
|
183
|
+
* `0` - due north
|
184
|
+
* `180` - due south
|
185
|
+
* `90` - due east
|
186
|
+
* `270` - due west
|
187
|
+
* `230.1` - southwest
|
188
|
+
* `359.9` - almost due north
|
189
|
+
|
190
|
+
You can convert these numbers to compass point names by using the utility method provided:
|
191
|
+
|
192
|
+
Geocoder::Calculations.compass_point(355) # => "N"
|
193
|
+
Geocoder::Calculations.compass_point(45) # => "NE"
|
194
|
+
Geocoder::Calculations.compass_point(208) # => "SW"
|
195
|
+
|
196
|
+
_Note: when using SQLite `distance` and `bearing` values are provided for interface consistency only. They are not very accurate._
|
197
|
+
|
198
|
+
To calculate accurate distance and bearing with SQLite or MongoDB:
|
199
|
+
|
200
|
+
obj.distance_to([43.9,-98.6]) # distance from obj to point
|
201
|
+
obj.bearing_to([43.9,-98.6]) # bearing from obj to point
|
202
|
+
obj.bearing_from(obj2) # bearing from obj2 to obj
|
203
|
+
|
204
|
+
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).
|
205
|
+
|
206
|
+
|
207
|
+
Model Configuration
|
208
|
+
-------------------
|
209
|
+
|
210
|
+
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:
|
211
|
+
|
212
|
+
geocoded_by :address, :latitude => :lat, :longitude => :lon # ActiveRecord
|
213
|
+
geocoded_by :address, :coordinates => :coords # MongoDB
|
214
|
+
|
215
|
+
This means you can geocode multiple addresses as well:
|
216
|
+
|
217
|
+
geocoded_by :start_address, latitude: :start_latitude, longitude: :start_longitude
|
218
|
+
geocoded_by :end_address, latitude: :end_latitude, longitude: :end_longitude
|
219
|
+
|
220
|
+
The `address` method can return any string you'd use to search Google Maps. For example, any of the following are acceptable:
|
221
|
+
|
222
|
+
* "714 Green St, Big Town, MO"
|
223
|
+
* "Eiffel Tower, Paris, FR"
|
224
|
+
* "Paris, TX, US"
|
225
|
+
|
226
|
+
If your model has `street`, `city`, `state`, and `country` attributes you might do something like this:
|
227
|
+
|
228
|
+
geocoded_by :address
|
229
|
+
|
230
|
+
def address
|
231
|
+
[street, city, state, country].compact.join(', ')
|
232
|
+
end
|
233
|
+
|
234
|
+
For reverse geocoding you can also specify an alternate name attribute where the address will be stored, for example:
|
235
|
+
|
236
|
+
reverse_geocoded_by :latitude, :longitude, :address => :location # ActiveRecord
|
237
|
+
reverse_geocoded_by :coordinates, :address => :loc # MongoDB
|
238
|
+
|
239
|
+
You can also configure a specific lookup for your model which will override the globally-configured lookup, for example:
|
240
|
+
|
241
|
+
geocoded_by :address, :lookup => :yandex
|
242
|
+
|
243
|
+
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:
|
244
|
+
|
245
|
+
geocoded_by :address, :lookup => lambda{ |obj| obj.geocoder_lookup }
|
246
|
+
|
247
|
+
def geocoder_lookup
|
248
|
+
if country_code == "RU"
|
249
|
+
:yandex
|
250
|
+
elsif country_code == "CN"
|
251
|
+
:baidu
|
252
|
+
else
|
253
|
+
:google
|
254
|
+
end
|
255
|
+
end
|
256
|
+
|
257
|
+
|
258
|
+
Advanced Querying
|
259
|
+
-----------------
|
260
|
+
|
261
|
+
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:
|
262
|
+
|
263
|
+
distance = 20
|
264
|
+
center_point = [40.71, 100.23]
|
265
|
+
box = Geocoder::Calculations.bounding_box(center_point, distance)
|
266
|
+
Venue.within_bounding_box(box)
|
267
|
+
|
268
|
+
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.
|
269
|
+
|
270
|
+
You can also specify a minimum radius (if you're using ActiveRecord and not Sqlite) to constrain the
|
271
|
+
lower bound (ie. think of a donut, or ring) by using the `:min_radius` option:
|
272
|
+
|
273
|
+
box = Geocoder::Calculations.bounding_box(center_point, distance, :min_radius => 10.5)
|
274
|
+
|
275
|
+
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):
|
276
|
+
|
277
|
+
Venue.near("Paris", 50, latitude: :secondary_latitude, longitude: :secondary_longitude)
|
278
|
+
|
279
|
+
|
280
|
+
Advanced Geocoding
|
281
|
+
------------------
|
282
|
+
|
283
|
+
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:
|
284
|
+
|
285
|
+
reverse_geocoded_by :latitude, :longitude do |obj,results|
|
286
|
+
if geo = results.first
|
287
|
+
obj.city = geo.city
|
288
|
+
obj.zipcode = geo.postal_code
|
289
|
+
obj.country = geo.country_code
|
290
|
+
end
|
291
|
+
end
|
292
|
+
after_validation :reverse_geocode
|
293
|
+
|
294
|
+
Every `Geocoder::Result` object, `result`, provides the following data:
|
295
|
+
|
296
|
+
* `result.latitude` - float
|
297
|
+
* `result.longitude` - float
|
298
|
+
* `result.coordinates` - array of the above two
|
299
|
+
* `result.address` - string
|
300
|
+
* `result.city` - string
|
301
|
+
* `result.state` - string
|
302
|
+
* `result.state_code` - string
|
303
|
+
* `result.postal_code` - string
|
304
|
+
* `result.country` - string
|
305
|
+
* `result.country_code` - string
|
306
|
+
|
307
|
+
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.)
|
308
|
+
|
309
|
+
|
310
|
+
Geocoding Service ("Lookup") Configuration
|
311
|
+
------------------------------------------
|
312
|
+
|
313
|
+
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).
|
314
|
+
|
315
|
+
To create a Rails initializer with an example configuration:
|
316
|
+
|
317
|
+
rails generate geocoder:config
|
318
|
+
|
319
|
+
Some common configuration options are:
|
320
|
+
|
321
|
+
# config/initializers/geocoder.rb
|
322
|
+
Geocoder.configure(
|
323
|
+
|
324
|
+
# geocoding service (see below for supported options):
|
325
|
+
:lookup => :yandex,
|
326
|
+
|
327
|
+
# IP address geocoding service (see below for supported options):
|
328
|
+
:ip_lookup => :maxmind,
|
329
|
+
|
330
|
+
# to use an API key:
|
331
|
+
:api_key => "...",
|
332
|
+
|
333
|
+
# geocoding service request timeout, in seconds (default 3):
|
334
|
+
:timeout => 5,
|
335
|
+
|
336
|
+
# set default units to kilometers:
|
337
|
+
:units => :km,
|
338
|
+
|
339
|
+
# caching (see below for details):
|
340
|
+
:cache => Redis.new,
|
341
|
+
:cache_prefix => "..."
|
342
|
+
|
343
|
+
)
|
344
|
+
|
345
|
+
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:
|
346
|
+
|
347
|
+
# with Google:
|
348
|
+
Geocoder.search("Paris", :bounds => [[32.1,-95.9], [33.9,-94.3]])
|
349
|
+
|
350
|
+
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:
|
351
|
+
|
352
|
+
# with Nominatim:
|
353
|
+
Geocoder.search("Paris", :params => {:countrycodes => "gb,de,fr,es,us"})
|
354
|
+
|
355
|
+
You can also configure multiple geocoding services at once, like this:
|
356
|
+
|
357
|
+
Geocoder.configure(
|
358
|
+
|
359
|
+
:timeout => 2,
|
360
|
+
:cache => Redis.new,
|
361
|
+
|
362
|
+
:yandex => {
|
363
|
+
:api_key => "...",
|
364
|
+
:timeout => 5
|
365
|
+
},
|
366
|
+
|
367
|
+
:baidu => {
|
368
|
+
:api_key => "..."
|
369
|
+
},
|
370
|
+
|
371
|
+
:maxmind => {
|
372
|
+
:api_key => "...",
|
373
|
+
:service => :omni
|
374
|
+
}
|
375
|
+
|
376
|
+
)
|
377
|
+
|
378
|
+
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.
|
379
|
+
|
380
|
+
|
381
|
+
### Street Address Services
|
382
|
+
|
383
|
+
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.
|
384
|
+
|
385
|
+
#### Google (`:google`, `:google_premier`)
|
386
|
+
|
387
|
+
* **API key**: required for Premier, optional for the free service (if using the free service with API key, https is required. Add `:use_https => true` to `Geocoder.configure`)
|
388
|
+
* **Key signup**: https://developers.google.com/maps/documentation/business/
|
389
|
+
* **Quota**: 2,500 requests/day, 100,000 with Google Maps API Premier
|
390
|
+
* **Region**: world
|
391
|
+
* **SSL support**: yes
|
392
|
+
* **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)
|
393
|
+
* **Extra options**: `:bounds` - pass SW and NE coordinates as an array of two arrays to bias results towards a viewport
|
394
|
+
* **Documentation**: http://code.google.com/apis/maps/documentation/geocoding/#JSON
|
395
|
+
* **Terms of Service**: http://code.google.com/apis/maps/terms.html#section_10_12
|
396
|
+
* **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..."
|
397
|
+
* **Notes**: To use Google Premier set `Geocoder.configure(:lookup => :google_premier, :api_key => [key, client, channel])`.
|
398
|
+
|
399
|
+
#### Google Places Details (`:google_places_details`)
|
400
|
+
|
401
|
+
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)`.
|
402
|
+
|
403
|
+
* **API key**: required
|
404
|
+
* **Key signup**: https://code.google.com/apis/console/
|
405
|
+
* **Quota**: 1,000 request/day, 100,000 after credit card authentication
|
406
|
+
* **Region**: world
|
407
|
+
* **SSL support**: yes
|
408
|
+
* **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)
|
409
|
+
* **Documentation**: https://developers.google.com/places/documentation/details
|
410
|
+
* **Terms of Service**: https://developers.google.com/places/policies
|
411
|
+
* **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."
|
412
|
+
|
413
|
+
#### Yahoo BOSS (`:yahoo`)
|
414
|
+
|
415
|
+
* **API key**: requires OAuth consumer key and secret (set `Geocoder.configure(:api_key => [key, secret])`)
|
416
|
+
* **Key signup**: http://developer.yahoo.com/boss/geo/
|
417
|
+
* **Quota**: unlimited, but subject to usage fees
|
418
|
+
* **Region**: world
|
419
|
+
* **SSL support**: no
|
420
|
+
* **Languages**: en, fr, de, it, es, pt, nl, zh, ja, ko
|
421
|
+
* **Documentation**: http://developer.yahoo.com/boss/geo/docs/index.html
|
422
|
+
* **Terms of Service**: http://info.yahoo.com/legal/us/yahoo/boss/tou/?pir=ucJPcJ1ibUn.h.d.lVmlcbcEkoHjwJ_PvxG9SLK9VIbIQAw1XFrnDqY-
|
423
|
+
* **Limitations**: No mass downloads, no commercial map production based on the data, no storage of data except for caching.
|
424
|
+
|
425
|
+
#### Bing (`:bing`)
|
426
|
+
|
427
|
+
* **API key**: required (set `Geocoder.configure(:lookup => :bing, :api_key => key)`)
|
428
|
+
* **Key signup**: http://www.bingmapsportal.com
|
429
|
+
* **Quota**: 50,000 requests/24 hrs
|
430
|
+
* **Region**: world
|
431
|
+
* **SSL support**: no
|
432
|
+
* **Languages**: ?
|
433
|
+
* **Documentation**: http://msdn.microsoft.com/en-us/library/ff701715.aspx
|
434
|
+
* **Terms of Service**: http://www.microsoft.com/maps/product/terms.html
|
435
|
+
* **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."
|
436
|
+
|
437
|
+
#### Nominatim (`:nominatim`)
|
438
|
+
|
439
|
+
* **API key**: none
|
440
|
+
* **Quota**: 1 request/second
|
441
|
+
* **Region**: world
|
442
|
+
* **SSL support**: no
|
443
|
+
* **Languages**: ?
|
444
|
+
* **Documentation**: http://wiki.openstreetmap.org/wiki/Nominatim
|
445
|
+
* **Terms of Service**: http://wiki.openstreetmap.org/wiki/Nominatim_usage_policy
|
446
|
+
* **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).
|
447
|
+
|
448
|
+
#### OpenCageData (`:opencagedata`)
|
449
|
+
|
450
|
+
* **API key**: required
|
451
|
+
* **Key signup**: http://geocoder.opencagedata.com
|
452
|
+
* **Quota**: 2500 requests / day, then ability to purchase more (free during beta)
|
453
|
+
* **Region**: world
|
454
|
+
* **SSL support**: yes
|
455
|
+
* **Languages**: worldwide
|
456
|
+
* **Documentation**: http://geocoder.opencagedata.com/api.html
|
457
|
+
* **Limitations**: Data licensed under CC-BY-SA or (you must provide attribution).
|
458
|
+
|
459
|
+
#### Yandex (`:yandex`)
|
460
|
+
|
461
|
+
* **API key**: none
|
462
|
+
* **Quota**: 25000 requests / day
|
463
|
+
* **Region**: world
|
464
|
+
* **SSL support**: no
|
465
|
+
* **Languages**: Russian, Belarusian, Ukrainian, English, Turkish (only for maps of Turkey)
|
466
|
+
* **Documentation**: http://api.yandex.com.tr/maps/doc/intro/concepts/intro.xml
|
467
|
+
* **Terms of Service**: http://api.yandex.com.tr/maps/doc/intro/concepts/intro.xml#rules
|
468
|
+
* **Limitations**: ?
|
469
|
+
|
470
|
+
#### Geocoder.ca (`:geocoder_ca`)
|
471
|
+
|
472
|
+
* **API key**: none
|
473
|
+
* **Quota**: ?
|
474
|
+
* **Region**: US and Canada
|
475
|
+
* **SSL support**: no
|
476
|
+
* **Languages**: English
|
477
|
+
* **Documentation**: ?
|
478
|
+
* **Terms of Service**: http://geocoder.ca/?terms=1
|
479
|
+
* **Limitations**: "Under no circumstances can our data be re-distributed or re-sold by anyone to other parties without our written permission."
|
480
|
+
|
481
|
+
#### Geocoder.us (`:geocoder_us`)
|
482
|
+
|
483
|
+
* **API key**: HTTP Basic Auth
|
484
|
+
* **Sign up**: http://geocoder.us/user/signup
|
485
|
+
* **Quota**: You can purchase 20,000 credits at a time for $50
|
486
|
+
* **Region**: US
|
487
|
+
* **SSL support**: no
|
488
|
+
* **Languages**: English
|
489
|
+
* **Documentation**: http://geocoder.us/help/
|
490
|
+
* **Terms of Service**: http://geocoder.us/terms.shtml
|
491
|
+
* **Limitations**: ?
|
492
|
+
|
493
|
+
#### Mapquest (`:mapquest`)
|
494
|
+
|
495
|
+
* **API key**: required
|
496
|
+
* **Key signup**: http://developer.mapquest.com/web/products/open
|
497
|
+
* **Quota**: ?
|
498
|
+
* **HTTP Headers**: in order to use the licensed API you can configure the http_headers to include a referer as so:
|
499
|
+
`Geocoder.configure(:http_headers => { "Referer" => "http://foo.com" })`
|
500
|
+
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.
|
501
|
+
* **Region**: world
|
502
|
+
* **SSL support**: no
|
503
|
+
* **Languages**: English
|
504
|
+
* **Documentation**: http://www.mapquestapi.com/geocoding/
|
505
|
+
* **Terms of Service**: http://info.mapquest.com/terms-of-use/
|
506
|
+
* **Limitations**: ?
|
507
|
+
* **Notes**: You can specify the licensed API by setting: `Geocoder.configure(:mapquest => {:licensed => true})` (defaults to free "open" version)
|
508
|
+
|
509
|
+
#### Ovi/Nokia (`:ovi`)
|
510
|
+
|
511
|
+
* **API key**: not required, but performance restricted without it
|
512
|
+
* **Quota**: ?
|
513
|
+
* **Region**: world
|
514
|
+
* **SSL support**: no
|
515
|
+
* **Languages**: English
|
516
|
+
* **Documentation**: http://api.maps.ovi.com/devguide/overview.html
|
517
|
+
* **Terms of Service**: http://www.developer.nokia.com/Develop/Maps/TC.html
|
518
|
+
* **Limitations**: ?
|
519
|
+
|
520
|
+
#### Here/Nokia (`:here`)
|
521
|
+
|
522
|
+
* **API key**: required
|
523
|
+
* **Quota**: Depending on the API key
|
524
|
+
* **Region**: world
|
525
|
+
* **SSL support**: yes
|
526
|
+
* **Languages**: The preferred language of address elements in the result. Language code must be provided according to RFC 4647 standard.
|
527
|
+
* **Documentation**: http://developer.here.com/rest-apis/documentation/geocoder
|
528
|
+
* **Terms of Service**: http://developer.here.com/faqs#l&t
|
529
|
+
* **Limitations**: ?
|
530
|
+
|
531
|
+
#### ESRI (`:esri`)
|
532
|
+
|
533
|
+
* **API key**: none
|
534
|
+
* **Quota**: Required for some scenarios (see Terms of Service)
|
535
|
+
* **Region**: world
|
536
|
+
* **SSL support**: yes
|
537
|
+
* **Languages**: English
|
538
|
+
* **Documentation**: http://resources.arcgis.com/en/help/arcgis-online-geocoding-rest-api/
|
539
|
+
* **Terms of Service**: http://www.esri.com/legal/software-license
|
540
|
+
* **Limitations**: ?
|
541
|
+
* **Notes**: You can specify which projection you want to use by setting, for example: `Geocoder.configure(:esri => {:outSR => 102100})`.
|
542
|
+
|
543
|
+
#### Data Science Toolkit (`:dstk`)
|
544
|
+
|
545
|
+
Data Science Toolkit provides an API whose reponse format is like Google's but which can be set up as a privately hosted service.
|
546
|
+
|
547
|
+
* **API key**: none
|
548
|
+
* **Quota**: None quota if you are self-hosting the service.
|
549
|
+
* **Region**: world
|
550
|
+
* **SSL support**: ?
|
551
|
+
* **Languages**: en
|
552
|
+
* **Documentation**: http://www.datasciencetoolkit.org/developerdocs
|
553
|
+
* **Terms of Service**: http://www.datasciencetoolkit.org/developerdocs#googlestylegeocoder
|
554
|
+
* **Limitations**: No reverse geocoding.
|
555
|
+
* **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")`.
|
556
|
+
|
557
|
+
#### Baidu (`:baidu`)
|
558
|
+
|
559
|
+
* **API key**: required
|
560
|
+
* **Quota**: No quota limits for geocoding
|
561
|
+
* **Region**: China
|
562
|
+
* **SSL support**: no
|
563
|
+
* **Languages**: Chinese (Simplified)
|
564
|
+
* **Documentation**: http://developer.baidu.com/map/webservice-geocoding.htm
|
565
|
+
* **Terms of Service**: http://developer.baidu.com/map/law.htm
|
566
|
+
* **Limitations**: Only good for non-commercial use. For commercial usage please check http://developer.baidu.com/map/question.htm#qa0013
|
567
|
+
* **Notes**: To use Baidu set `Geocoder.configure(:lookup => :baidu, :api_key => "your_api_key")`.
|
568
|
+
|
569
|
+
#### Geocodio (`:geocodio`)
|
570
|
+
|
571
|
+
* **API key**: required
|
572
|
+
* **Quota**: 2,500 free requests/day then purchase $.001 for each
|
573
|
+
* **Region**: US
|
574
|
+
* **SSL support**: no
|
575
|
+
* **Languages**: en
|
576
|
+
* **Documentation**: http://geocod.io/docs
|
577
|
+
* **Terms of Service**: http://geocod.io/terms-of-use
|
578
|
+
* **Limitations**: ?
|
579
|
+
|
580
|
+
#### SmartyStreets (`:smarty_streets`)
|
581
|
+
|
582
|
+
* **API key**: requires auth_id and auth_token (set `Geocoder.configure(:api_key => [id, token])`)
|
583
|
+
* **Quota**: 10,000 free, 250/month then purchase at sliding scale.
|
584
|
+
* **Region**: US
|
585
|
+
* **SSL support**: yes
|
586
|
+
* **Languages**: en
|
587
|
+
* **Documentation**: http://smartystreets.com/kb/liveaddress-api/rest-endpoint
|
588
|
+
* **Terms of Service**: http://smartystreets.com/legal/terms-of-service
|
589
|
+
* **Limitations**: No reverse geocoding.
|
590
|
+
|
591
|
+
|
592
|
+
#### OKF Geocoder (`:okf`)
|
593
|
+
|
594
|
+
* **API key**: none
|
595
|
+
* **Quota**: none
|
596
|
+
* **Region**: FI
|
597
|
+
* **SSL support**: no
|
598
|
+
* **Languages**: fi
|
599
|
+
* **Documentation**: http://books.okf.fi/geocoder/_full/
|
600
|
+
* **Terms of Service**: http://www.itella.fi/liitteet/palvelutjatuotteet/yhteystietopalvelut/Postinumeropalvelut-Palvelukuvausjakayttoehdot.pdf
|
601
|
+
* **Limitations**: ?
|
602
|
+
|
603
|
+
|
604
|
+
#### PostcodeAnywhere Uk (`:postcode_anywhere_uk`)
|
605
|
+
|
606
|
+
This uses the PostcodeAnywhere UK Geocode service, this will geocode any string from UK postcode, placename, point of interest or location.
|
607
|
+
|
608
|
+
* **API key**: required
|
609
|
+
* **Quota**: Dependant on service plan?
|
610
|
+
* **Region**: UK
|
611
|
+
* **SSL support**: yes
|
612
|
+
* **Languages**: English
|
613
|
+
* **Documentation**: [http://www.postcodeanywhere.co.uk/Support/WebService/Geocoding/UK/Geocode/2/](http://www.postcodeanywhere.co.uk/Support/WebService/Geocoding/UK/Geocode/2/)
|
614
|
+
* **Terms of Service**: ?
|
615
|
+
* **Limitations**: ?
|
616
|
+
* **Notes**: To use PostcodeAnywhere you must include an API key: `Geocoder.configure(:lookup => :postcode_anywhere_uk, :api_key => 'your_api_key')`.
|
617
|
+
|
618
|
+
#### AutoNavi (`:amap`)
|
619
|
+
|
620
|
+
* **API key**: required
|
621
|
+
* **Quota**: none
|
622
|
+
* **Region**: China
|
623
|
+
* **SSL support**: yes
|
624
|
+
* **Languages**: Chinese (Simplified)
|
625
|
+
* **Documentation**: http://lbs.amap.com/
|
626
|
+
* **Terms of Service**: http://lbs.amap.com/home/terms/
|
627
|
+
* **Limitations**: Only good for non-commercial use. For commercial usage please check http://lbs.amap.com/home/terms/
|
628
|
+
* **Notes**: To use AutoNavi set `Geocoder.configure(:lookup => :amap, :api_key => "your_api_key")`.
|
629
|
+
|
630
|
+
|
631
|
+
### IP Address Services
|
632
|
+
|
633
|
+
#### FreeGeoIP (`:freegeoip`)
|
634
|
+
|
635
|
+
* **API key**: none
|
636
|
+
* **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.
|
637
|
+
* **Region**: world
|
638
|
+
* **SSL support**: no
|
639
|
+
* **Languages**: English
|
640
|
+
* **Documentation**: http://github.com/fiorix/freegeoip/blob/master/README.md
|
641
|
+
* **Terms of Service**: ?
|
642
|
+
* **Limitations**: ?
|
643
|
+
* **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: "..."})`.
|
644
|
+
|
645
|
+
#### Pointpin (`:pointpin`)
|
646
|
+
|
647
|
+
* **API key**: required
|
648
|
+
* **Quota**: 50,000/mo for €9 through 1m/mo for €49
|
649
|
+
* **Region**: world
|
650
|
+
* **SSL support**: yes
|
651
|
+
* **Languages**: English
|
652
|
+
* **Documentation**: https://pointp.in/docs/get-started
|
653
|
+
* **Terms of Service**: https://pointp.in/terms
|
654
|
+
* **Limitations**: ?
|
655
|
+
* **Notes**: To use Pointpin set `Geocoder.configure(:ip_lookup => :pointpin, :api_key => "your_pointpin_api_key")`.
|
656
|
+
|
657
|
+
#### Telize (`:telize`)
|
658
|
+
|
659
|
+
* **API key**: none
|
660
|
+
* **Quota**: none
|
661
|
+
* **Region**: world
|
662
|
+
* **SSL support**: no
|
663
|
+
* **Languages**: English
|
664
|
+
* **Documentation**: http://www.telize.com/
|
665
|
+
* **Terms of Service**: ?
|
666
|
+
* **Limitations**: ?
|
667
|
+
|
668
|
+
#### MaxMind Web Services (`:maxmind`)
|
669
|
+
|
670
|
+
* **API key**: required
|
671
|
+
* **Quota**: Request Packs can be purchased
|
672
|
+
* **Region**: world
|
673
|
+
* **SSL support**: yes
|
674
|
+
* **Languages**: English
|
675
|
+
* **Documentation**: http://www.maxmind.com/app/web_services
|
676
|
+
* **Terms of Service**: ?
|
677
|
+
* **Limitations**: ?
|
678
|
+
* **Notes**: You must specify which MaxMind service you are using in your configuration. For example: `Geocoder.configure(:maxmind => {:service => :omni})`.
|
679
|
+
|
680
|
+
#### MaxMind Local (`:maxmind_local`) - EXPERIMENTAL
|
681
|
+
|
682
|
+
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.
|
683
|
+
|
684
|
+
* **API key**: none (requires the GeoLite City database which can be downloaded from [MaxMind](http://dev.maxmind.com/geoip/legacy/geolite/))
|
685
|
+
* **Quota**: none
|
686
|
+
* **Region**: world
|
687
|
+
* **SSL support**: N/A
|
688
|
+
* **Languages**: English
|
689
|
+
* **Documentation**: http://www.maxmind.com/en/city
|
690
|
+
* **Terms of Service**: ?
|
691
|
+
* **Limitations**: ?
|
692
|
+
* **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.**
|
693
|
+
|
694
|
+
**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:
|
695
|
+
|
696
|
+
Geocoder.configure(ip_lookup: :maxmind_local, maxmind_local: {file: File.join('folder', 'GeoLiteCity.dat')})
|
697
|
+
|
698
|
+
**To use a CSV file** you must import it into an SQL database. The GeoLite *City* and *Country* packages are supported. Configure like so:
|
699
|
+
|
700
|
+
Geocoder.configure(ip_lookup: :maxmind_local, maxmind_local: {package: :city})
|
701
|
+
|
702
|
+
You can generate ActiveRecord migrations and download and import data via provided rake tasks:
|
703
|
+
|
704
|
+
# generate migration to create tables
|
705
|
+
rails generate geocoder:maxmind:geolite PACKAGE=city
|
706
|
+
|
707
|
+
# download, unpack, and import data
|
708
|
+
rake geocoder:maxmind:geolite:load PACKAGE=city
|
709
|
+
|
710
|
+
You can replace `city` with `country` in any of the above tasks, generators, and configurations.
|
711
|
+
|
712
|
+
#### Baidu IP (`:baidu_ip`)
|
713
|
+
|
714
|
+
* **API key**: required
|
715
|
+
* **Quota**: No quota limits for geocoding
|
716
|
+
* **Region**: China
|
717
|
+
* **SSL support**: no
|
718
|
+
* **Languages**: Chinese (Simplified)
|
719
|
+
* **Documentation**: http://developer.baidu.com/map/webservice-geocoding.htm
|
720
|
+
* **Terms of Service**: http://developer.baidu.com/map/law.htm
|
721
|
+
* **Limitations**: Only good for non-commercial use. For commercial usage please check http://developer.baidu.com/map/question.htm#qa0013
|
722
|
+
* **Notes**: To use Baidu set `Geocoder.configure(:lookup => :baidu_ip, :api_key => "your_api_key")`.
|
723
|
+
|
724
|
+
#### GeoLite2 (`:geoip2`)
|
725
|
+
|
726
|
+
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.
|
727
|
+
|
728
|
+
* **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/geoip2/))
|
729
|
+
* **Quota**: none
|
730
|
+
* **Region**: world
|
731
|
+
* **SSL support**: N/A
|
732
|
+
* **Languages**: English
|
733
|
+
* **Documentation**: http://www.maxmind.com/en/city
|
734
|
+
* **Terms of Service**: ?
|
735
|
+
* **Limitations**: ?
|
736
|
+
* **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:
|
737
|
+
|
738
|
+
Geocoder.configure(
|
739
|
+
ip_lookup: :geoip2,
|
740
|
+
geoip2: {
|
741
|
+
file: File.join('folder', 'GeoLite2-City.mmdb')
|
742
|
+
}
|
743
|
+
)
|
744
|
+
|
745
|
+
|
746
|
+
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`:
|
747
|
+
|
748
|
+
Geocoder.configure(
|
749
|
+
ip_lookup: :geoip2,
|
750
|
+
geoip2: {
|
751
|
+
lib: 'hive_geoip2',
|
752
|
+
file: File.join('folder', 'GeoLite2-City.mmdb')
|
753
|
+
}
|
754
|
+
)
|
755
|
+
|
756
|
+
Caching
|
757
|
+
-------
|
758
|
+
|
759
|
+
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:
|
760
|
+
|
761
|
+
Geocoder.configure(:cache => Redis.new)
|
762
|
+
|
763
|
+
This example uses Redis, but the cache store can be any object that supports these methods:
|
764
|
+
|
765
|
+
* `store#[](key)` or `#get` or `#read` - retrieves a value
|
766
|
+
* `store#[]=(key, value)` or `#set` or `#write` - stores a value
|
767
|
+
* `store#del(url)` - deletes a value
|
768
|
+
|
769
|
+
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).
|
770
|
+
|
771
|
+
You can also set a custom prefix to be used for cache keys:
|
772
|
+
|
773
|
+
Geocoder.configure(:cache_prefix => "...")
|
774
|
+
|
775
|
+
By default the prefix is `geocoder:`
|
776
|
+
|
777
|
+
If you need to expire cached content:
|
778
|
+
|
779
|
+
Geocoder::Lookup.get(Geocoder.config[:lookup]).cache.expire(:all) # expire cached results for current Lookup
|
780
|
+
Geocoder::Lookup.get(:google).cache.expire("http://...") # expire cached result for a specific URL
|
781
|
+
Geocoder::Lookup.get(:google).cache.expire(:all) # expire cached results for Google Lookup
|
782
|
+
# expire all cached results for all Lookups.
|
783
|
+
# Be aware that this methods spawns a new Lookup object for each Service
|
784
|
+
Geocoder::Lookup.all_services.each{|service| Geocoder::Lookup.get(service).cache.expire(:all)}
|
785
|
+
|
786
|
+
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).
|
787
|
+
|
788
|
+
For an example of a cache store with URL expiry please see examples/autoexpire_cache.rb
|
789
|
+
|
790
|
+
_Before you implement caching in your app please be sure that doing so does not violate the Terms of Service for your geocoding service._
|
791
|
+
|
792
|
+
|
793
|
+
Forward and Reverse Geocoding in the Same Model
|
794
|
+
-----------------------------------------------
|
795
|
+
|
796
|
+
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:
|
797
|
+
|
798
|
+
* one for storing the fetched address (reverse geocoding)
|
799
|
+
* one for providing an address to use when fetching coordinates (forward geocoding)
|
800
|
+
|
801
|
+
For example:
|
802
|
+
|
803
|
+
class Venue
|
804
|
+
|
805
|
+
# build an address from street, city, and state attributes
|
806
|
+
geocoded_by :address_from_components
|
807
|
+
|
808
|
+
# store the fetched address in the full_address attribute
|
809
|
+
reverse_geocoded_by :latitude, :longitude, :address => :full_address
|
810
|
+
end
|
811
|
+
|
812
|
+
However, there can be only one set of latitude/longitude attributes, and whichever you specify last will be used. For example:
|
813
|
+
|
814
|
+
class Venue
|
815
|
+
|
816
|
+
geocoded_by :address,
|
817
|
+
:latitude => :fetched_latitude, # this will be overridden by the below
|
818
|
+
:longitude => :fetched_longitude # same here
|
819
|
+
|
820
|
+
reverse_geocoded_by :latitude, :longitude
|
821
|
+
end
|
822
|
+
|
823
|
+
The reason for this is that we don't want ambiguity when doing distance calculations. We need a single, authoritative source for coordinates!
|
824
|
+
|
825
|
+
Once both forward and reverse geocoding has been applied, it is possible to call them sequentially.
|
826
|
+
|
827
|
+
For example:
|
828
|
+
|
829
|
+
class Venue
|
830
|
+
|
831
|
+
after_validation :geocode, :reverse_geocode
|
832
|
+
|
833
|
+
end
|
834
|
+
|
835
|
+
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:
|
836
|
+
|
837
|
+
after_validation :geocode
|
838
|
+
|
839
|
+
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.
|
840
|
+
|
841
|
+
For example:
|
842
|
+
|
843
|
+
class Venue
|
844
|
+
|
845
|
+
after_validation :reverse_geocode, :if => :has_coordinates
|
846
|
+
after_validation :geocode, :if => :has_location, :unless => :has_coordinates
|
847
|
+
|
848
|
+
end
|
849
|
+
|
850
|
+
Use Outside of Rails
|
851
|
+
--------------------
|
852
|
+
|
853
|
+
You can use Geocoder outside of Rails by calling the `Geocoder.search` method:
|
854
|
+
|
855
|
+
results = Geocoder.search("McCarren Park, Brooklyn, NY")
|
856
|
+
|
857
|
+
This returns an array of `Geocoder::Result` objects with all data provided by the geocoding service.
|
858
|
+
|
859
|
+
|
860
|
+
Testing Apps that Use Geocoder
|
861
|
+
------------------------------
|
862
|
+
|
863
|
+
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:
|
864
|
+
|
865
|
+
Geocoder.configure(:lookup => :test)
|
866
|
+
|
867
|
+
Geocoder::Lookup::Test.add_stub(
|
868
|
+
"New York, NY", [
|
869
|
+
{
|
870
|
+
'latitude' => 40.7143528,
|
871
|
+
'longitude' => -74.0059731,
|
872
|
+
'address' => 'New York, NY, USA',
|
873
|
+
'state' => 'New York',
|
874
|
+
'state_code' => 'NY',
|
875
|
+
'country' => 'United States',
|
876
|
+
'country_code' => 'US'
|
877
|
+
}
|
878
|
+
]
|
879
|
+
)
|
880
|
+
|
881
|
+
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:
|
882
|
+
|
883
|
+
Geocoder.configure(:lookup => :test)
|
884
|
+
|
885
|
+
Geocoder::Lookup::Test.set_default_stub(
|
886
|
+
[
|
887
|
+
{
|
888
|
+
'latitude' => 40.7143528,
|
889
|
+
'longitude' => -74.0059731,
|
890
|
+
'address' => 'New York, NY, USA',
|
891
|
+
'state' => 'New York',
|
892
|
+
'state_code' => 'NY',
|
893
|
+
'country' => 'United States',
|
894
|
+
'country_code' => 'US'
|
895
|
+
}
|
896
|
+
]
|
897
|
+
)
|
898
|
+
|
899
|
+
Any query that hasn't been explicitly stubbed will return that result.
|
900
|
+
|
901
|
+
Command Line Interface
|
902
|
+
----------------------
|
903
|
+
|
904
|
+
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:
|
905
|
+
|
906
|
+
$ geocode 29.951,-90.081
|
907
|
+
Latitude: 29.952211
|
908
|
+
Longitude: -90.080563
|
909
|
+
Full address: 1500 Sugar Bowl Dr, New Orleans, LA 70112, USA
|
910
|
+
City: New Orleans
|
911
|
+
State/province: Louisiana
|
912
|
+
Postal code: 70112
|
913
|
+
Country: United States
|
914
|
+
Google map: http://maps.google.com/maps?q=29.952211,-90.080563
|
915
|
+
|
916
|
+
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.
|
917
|
+
|
918
|
+
Numeric Data Types and Precision
|
919
|
+
--------------------------------
|
920
|
+
|
921
|
+
Geocoder works with any numeric data type (e.g. float, double, decimal) on which trig (and other mathematical) functions can be performed.
|
922
|
+
|
923
|
+
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.
|
924
|
+
|
925
|
+
Notes on MongoDB
|
926
|
+
----------------
|
927
|
+
|
928
|
+
### The Near Method
|
929
|
+
|
930
|
+
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.
|
931
|
+
|
932
|
+
### Latitude/Longitude Order
|
933
|
+
|
934
|
+
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.
|
935
|
+
|
936
|
+
To access an object's coordinates in the conventional order, use the `to_coordinates` instance method provided by Geocoder. For example:
|
937
|
+
|
938
|
+
obj.to_coordinates # => [37.7941013, -122.3951096] # [lat, lon]
|
939
|
+
|
940
|
+
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:
|
941
|
+
|
942
|
+
obj.coordinates # => [-122.3951096, 37.7941013] # [lon, lat]
|
943
|
+
|
944
|
+
For consistency with the rest of Geocoder, always use the `to_coordinates` method instead.
|
945
|
+
|
946
|
+
Notes on Non-Rails Frameworks
|
947
|
+
-----------------------------
|
948
|
+
|
949
|
+
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:
|
950
|
+
|
951
|
+
extend Geocoder::Model::ActiveRecord
|
952
|
+
|
953
|
+
Optimisation of Distance Queries
|
954
|
+
--------------------------------
|
955
|
+
|
956
|
+
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.
|
957
|
+
|
958
|
+
To take advantage of this optimisation you need to add a composite index on latitude and longitude. In your Rails migration:
|
959
|
+
|
960
|
+
add_index :table, [:latitude, :longitude]
|
961
|
+
|
962
|
+
|
963
|
+
Distance Queries in SQLite
|
964
|
+
--------------------------
|
965
|
+
|
966
|
+
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.
|
967
|
+
|
968
|
+
|
969
|
+
### Discussion
|
970
|
+
|
971
|
+
There are few options for finding objects near a given point in SQLite without installing extensions:
|
972
|
+
|
973
|
+
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.
|
974
|
+
|
975
|
+
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.
|
976
|
+
|
977
|
+
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`.
|
978
|
+
|
979
|
+
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.
|
980
|
+
|
981
|
+
|
982
|
+
Tests
|
983
|
+
-----
|
984
|
+
|
985
|
+
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:
|
986
|
+
|
987
|
+
http://github.com/alexreisner/geocoder_test
|
988
|
+
|
989
|
+
|
990
|
+
Error Handling
|
991
|
+
--------------
|
992
|
+
|
993
|
+
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:
|
994
|
+
|
995
|
+
Geocoder.configure(:always_raise => [SocketError, TimeoutError])
|
996
|
+
|
997
|
+
You can also do this to raise all exceptions:
|
998
|
+
|
999
|
+
Geocoder.configure(:always_raise => :all)
|
1000
|
+
|
1001
|
+
The raise-able exceptions are:
|
1002
|
+
|
1003
|
+
SocketError
|
1004
|
+
TimeoutError
|
1005
|
+
Geocoder::OverQueryLimitError
|
1006
|
+
Geocoder::RequestDenied
|
1007
|
+
Geocoder::InvalidRequest
|
1008
|
+
Geocoder::InvalidApiKey
|
1009
|
+
|
1010
|
+
Note that not all lookups support all exceptions.
|
1011
|
+
|
1012
|
+
|
1013
|
+
Troubleshooting
|
1014
|
+
---------------
|
1015
|
+
|
1016
|
+
### Mongoid
|
1017
|
+
|
1018
|
+
If you get one of these errors:
|
1019
|
+
|
1020
|
+
uninitialized constant Geocoder::Model::Mongoid
|
1021
|
+
uninitialized constant Geocoder::Model::Mongoid::Mongo
|
1022
|
+
|
1023
|
+
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.
|
1024
|
+
|
1025
|
+
### ActiveRecord
|
1026
|
+
|
1027
|
+
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:
|
1028
|
+
|
1029
|
+
* using the `pluck` method (selects only a single column)
|
1030
|
+
* specifying another model through `includes` (selects columns from other tables)
|
1031
|
+
|
1032
|
+
### Unexpected Responses from Geocoding Services
|
1033
|
+
|
1034
|
+
Take a look at the server's raw response. You can do this by getting the request URL in an app console:
|
1035
|
+
|
1036
|
+
Geocoder::Lookup.get(:google).query_url(Geocoder::Query.new("..."))
|
1037
|
+
|
1038
|
+
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.
|
1039
|
+
|
1040
|
+
You can also fetch the response in the console:
|
1041
|
+
|
1042
|
+
Geocoder::Lookup.get(:google).send(:fetch_raw_data, Geocoder::Query.new("..."))
|
1043
|
+
|
1044
|
+
|
1045
|
+
Reporting Issues
|
1046
|
+
----------------
|
1047
|
+
|
1048
|
+
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?).
|
1049
|
+
|
1050
|
+
|
1051
|
+
Known Issue
|
1052
|
+
-----------
|
1053
|
+
|
1054
|
+
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).
|
1055
|
+
|
1056
|
+
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:
|
1057
|
+
|
1058
|
+
# Pass a :select option to the near scope to get the columns you want.
|
1059
|
+
# Instead of City.near(...).includes(:venues), try:
|
1060
|
+
City.near("Omaha, NE", 20, :select => "cities.*, venues.*").joins(:venues)
|
1061
|
+
|
1062
|
+
# This preload call will normally trigger two queries regardless of the
|
1063
|
+
# number of results; one query on hotels, and one query on administrators.
|
1064
|
+
# Instead of Hotel.near(...).includes(:administrator), try:
|
1065
|
+
Hotel.near("London, UK", 50).joins(:administrator).preload(:administrator)
|
1066
|
+
|
1067
|
+
If anyone has a more elegant solution to this problem I am very interested in seeing it.
|
1068
|
+
|
1069
|
+
|
1070
|
+
Contributing
|
1071
|
+
------------
|
1072
|
+
|
1073
|
+
Contributions are welcome via pull requests on Github. Please respect the following guidelines:
|
1074
|
+
|
1075
|
+
* 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.
|
1076
|
+
* Do not commit changes to files that are irrelevant to your feature or bugfix (eg: `.gitignore`).
|
1077
|
+
* Do not add dependencies on other gems.
|
1078
|
+
* Do not add unnecessary `require` statements which could cause LoadErrors on certain systems.
|
1079
|
+
* Remember: Geocoder needs to run outside of Rails. Don't assume things like ActiveSupport are available.
|
1080
|
+
* Do not add to base configuration options; instead document required lookup-specific options in the README.
|
1081
|
+
* 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.
|
1082
|
+
* Be aware that the pull request review process is not immediate, and is generally proportional to the size of the pull request.
|
1083
|
+
|
1084
|
+
|
1085
|
+
Copyright (c) 2009-12 Alex Reisner, released under the MIT license
|