geocoder 1.1.3 → 1.1.4

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of geocoder might be problematic. Click here for more details.

Files changed (45) hide show
  1. data/CHANGELOG.rdoc +12 -0
  2. data/README.md +580 -0
  3. data/examples/autoexpire_cache.rb +30 -0
  4. data/lib/geocoder.rb +9 -85
  5. data/lib/geocoder/calculations.rb +1 -1
  6. data/lib/geocoder/cli.rb +9 -10
  7. data/lib/geocoder/configuration.rb +3 -1
  8. data/lib/geocoder/lookup.rb +81 -0
  9. data/lib/geocoder/lookups/base.rb +20 -32
  10. data/lib/geocoder/lookups/bing.rb +12 -8
  11. data/lib/geocoder/lookups/freegeoip.rb +5 -5
  12. data/lib/geocoder/lookups/geocoder_ca.rb +13 -9
  13. data/lib/geocoder/lookups/google.rb +19 -7
  14. data/lib/geocoder/lookups/google_premier.rb +8 -7
  15. data/lib/geocoder/lookups/mapquest.rb +5 -23
  16. data/lib/geocoder/lookups/nominatim.rb +16 -13
  17. data/lib/geocoder/lookups/test.rb +8 -6
  18. data/lib/geocoder/lookups/yahoo.rb +49 -10
  19. data/lib/geocoder/lookups/yandex.rb +15 -8
  20. data/lib/geocoder/models/mongoid.rb +0 -1
  21. data/lib/geocoder/query.rb +88 -0
  22. data/lib/geocoder/results/mapquest.rb +2 -61
  23. data/lib/geocoder/results/nominatim.rb +24 -3
  24. data/lib/geocoder/sql.rb +104 -0
  25. data/lib/geocoder/stores/active_record.rb +68 -140
  26. data/lib/geocoder/stores/mongo_base.rb +2 -2
  27. data/lib/geocoder/version.rb +1 -1
  28. data/test/active_record_test.rb +15 -0
  29. data/test/calculations_test.rb +7 -0
  30. data/test/error_handling_test.rb +7 -7
  31. data/test/fixtures/yahoo_madison_square_garden.json +49 -43
  32. data/test/fixtures/yahoo_v1_madison_square_garden.json +46 -0
  33. data/test/fixtures/yahoo_v1_no_results.json +10 -0
  34. data/test/https_test.rb +2 -2
  35. data/test/integration/smoke_test.rb +6 -4
  36. data/test/lookup_test.rb +13 -6
  37. data/test/query_test.rb +34 -0
  38. data/test/result_test.rb +1 -1
  39. data/test/services_test.rb +48 -7
  40. data/test/test_helper.rb +64 -49
  41. data/test/test_mode_test.rb +0 -1
  42. metadata +13 -7
  43. data/README.rdoc +0 -552
  44. data/test/fixtures/yahoo_garbage.json +0 -50
  45. data/test/input_handling_test.rb +0 -43
@@ -35,6 +35,17 @@ module ActiveRecord
35
35
  read_attribute name
36
36
  end
37
37
  end
38
+
39
+ class << self
40
+ def table_name
41
+ 'test_table_name'
42
+ end
43
+
44
+ def primary_key
45
+ :id
46
+ end
47
+ end
48
+
38
49
  end
39
50
  end
40
51
 
@@ -60,10 +71,10 @@ module Geocoder
60
71
 
61
72
  class Google < Base
62
73
  private #-----------------------------------------------------------------
63
- def fetch_raw_data(query, reverse = false)
64
- raise TimeoutError if query == "timeout"
65
- raise SocketError if query == "socket_error"
66
- file = case query
74
+ def fetch_raw_data(query)
75
+ raise TimeoutError if query.text == "timeout"
76
+ raise SocketError if query.text == "socket_error"
77
+ file = case query.text
67
78
  when "no results"; :no_results
68
79
  when "no locality"; :no_locality
69
80
  when "no city data"; :no_city_data
@@ -78,12 +89,14 @@ module Geocoder
78
89
 
79
90
  class Yahoo < Base
80
91
  private #-----------------------------------------------------------------
81
- def fetch_raw_data(query, reverse = false)
82
- raise TimeoutError if query == "timeout"
83
- raise SocketError if query == "socket_error"
84
- file = case query
85
- when "no results"; :no_results
86
- else :madison_square_garden
92
+ def fetch_raw_data(query)
93
+ raise TimeoutError if query.text == "timeout"
94
+ raise SocketError if query.text == "socket_error"
95
+ file = case query.text
96
+ when "no results v1"; :v1_no_results
97
+ when "madison square garden v1"; :v1_madison_square_garden
98
+ when "no results"; :no_results
99
+ else :madison_square_garden
87
100
  end
88
101
  read_fixture "yahoo_#{file}.json"
89
102
  end
@@ -91,10 +104,10 @@ module Geocoder
91
104
 
92
105
  class Yandex < Base
93
106
  private #-----------------------------------------------------------------
94
- def fetch_raw_data(query, reverse = false)
95
- raise TimeoutError if query == "timeout"
96
- raise SocketError if query == "socket_error"
97
- file = case query
107
+ def fetch_raw_data(query)
108
+ raise TimeoutError if query.text == "timeout"
109
+ raise SocketError if query.text == "socket_error"
110
+ file = case query.text
98
111
  when "no results"; :no_results
99
112
  when "invalid key"; :invalid_key
100
113
  else :kremlin
@@ -105,13 +118,13 @@ module Geocoder
105
118
 
106
119
  class GeocoderCa < Base
107
120
  private #-----------------------------------------------------------------
108
- def fetch_raw_data(query, reverse = false)
109
- raise TimeoutError if query == "timeout"
110
- raise SocketError if query == "socket_error"
111
- if reverse
121
+ def fetch_raw_data(query)
122
+ raise TimeoutError if query.text == "timeout"
123
+ raise SocketError if query.text == "socket_error"
124
+ if query.reverse_geocode?
112
125
  read_fixture "geocoder_ca_reverse.json"
113
126
  else
114
- file = case query
127
+ file = case query.text
115
128
  when "no results"; :no_results
116
129
  else :madison_square_garden
117
130
  end
@@ -122,10 +135,10 @@ module Geocoder
122
135
 
123
136
  class Freegeoip < Base
124
137
  private #-----------------------------------------------------------------
125
- def fetch_raw_data(query, reverse = false)
126
- raise TimeoutError if query == "timeout"
127
- raise SocketError if query == "socket_error"
128
- file = case query
138
+ def fetch_raw_data(query)
139
+ raise TimeoutError if query.text == "timeout"
140
+ raise SocketError if query.text == "socket_error"
141
+ file = case query.text
129
142
  when "no results"; :no_results
130
143
  else "74_200_247_59"
131
144
  end
@@ -135,13 +148,13 @@ module Geocoder
135
148
 
136
149
  class Bing < Base
137
150
  private #-----------------------------------------------------------------
138
- def fetch_raw_data(query, reverse = false)
139
- raise TimeoutError if query == "timeout"
140
- raise SocketError if query == "socket_error"
141
- if reverse
151
+ def fetch_raw_data(query)
152
+ raise TimeoutError if query.text == "timeout"
153
+ raise SocketError if query.text == "socket_error"
154
+ if query.reverse_geocode?
142
155
  read_fixture "bing_reverse.json"
143
156
  else
144
- file = case query
157
+ file = case query.text
145
158
  when "no results"; :no_results
146
159
  else :madison_square_garden
147
160
  end
@@ -152,10 +165,10 @@ module Geocoder
152
165
 
153
166
  class Nominatim < Base
154
167
  private #-----------------------------------------------------------------
155
- def fetch_raw_data(query, reverse = false)
156
- raise TimeoutError if query == "timeout"
157
- raise SocketError if query == "socket_error"
158
- file = case query
168
+ def fetch_raw_data(query)
169
+ raise TimeoutError if query.text == "timeout"
170
+ raise SocketError if query.text == "socket_error"
171
+ file = case query.text
159
172
  when "no results"; :no_results
160
173
  else :madison_square_garden
161
174
  end
@@ -163,12 +176,12 @@ module Geocoder
163
176
  end
164
177
  end
165
178
 
166
- class Mapquest < Base
179
+ class Mapquest < Nominatim
167
180
  private #-----------------------------------------------------------------
168
- def fetch_raw_data(query, reverse = false)
169
- raise TimeoutError if query == "timeout"
170
- raise SocketError if query == "socket_error"
171
- file = case query
181
+ def fetch_raw_data(query)
182
+ raise TimeoutError if query.text == "timeout"
183
+ raise SocketError if query.text == "socket_error"
184
+ file = case query.text
172
185
  when "no results"; :no_results
173
186
  else :madison_square_garden
174
187
  end
@@ -192,6 +205,20 @@ class Venue < ActiveRecord::Base
192
205
  end
193
206
  end
194
207
 
208
+ ##
209
+ # Geocoded model.
210
+ # - Has user-defined primary key (not just 'id')
211
+ #
212
+ class VenuePlus < Venue
213
+
214
+ class << self
215
+ def primary_key
216
+ :custom_primary_key_id
217
+ end
218
+ end
219
+
220
+ end
221
+
195
222
  ##
196
223
  # Reverse geocoded model.
197
224
  #
@@ -277,18 +304,6 @@ class Test::Unit::TestCase
277
304
  }[abbrev]
278
305
  end
279
306
 
280
- def all_lookups
281
- Geocoder.valid_lookups
282
- end
283
-
284
- def all_lookups_except_test
285
- Geocoder.valid_lookups - [:test]
286
- end
287
-
288
- def street_lookups
289
- all_lookups - [:freegeoip]
290
- end
291
-
292
307
  def is_nan_coordinates?(coordinates)
293
308
  return false unless coordinates.respond_to? :size # Should be an array
294
309
  return false unless coordinates.size == 2 # Should have dimension 2
@@ -1,5 +1,4 @@
1
1
  require 'test_helper'
2
- require 'geocoder/lookups/test'
3
2
 
4
3
  class TestModeTest < Test::Unit::TestCase
5
4
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: geocoder
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.1.3
4
+ version: 1.1.4
5
5
  prerelease:
6
6
  platform: ruby
7
7
  authors:
@@ -9,7 +9,7 @@ authors:
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2012-08-26 00:00:00.000000000 Z
12
+ date: 2012-10-02 00:00:00.000000000 Z
13
13
  dependencies: []
14
14
  description: Provides object geocoding (by street or IP address), reverse geocoding
15
15
  (coordinates to street address), distance queries for ActiveRecord and Mongoid,
@@ -26,9 +26,10 @@ files:
26
26
  - .travis.yml
27
27
  - CHANGELOG.rdoc
28
28
  - LICENSE
29
- - README.rdoc
29
+ - README.md
30
30
  - Rakefile
31
31
  - bin/geocode
32
+ - examples/autoexpire_cache.rb
32
33
  - gemfiles/Gemfile.mongoid-2.4.x
33
34
  - lib/generators/geocoder/config/config_generator.rb
34
35
  - lib/generators/geocoder/config/templates/initializer.rb
@@ -38,6 +39,7 @@ files:
38
39
  - lib/geocoder/cli.rb
39
40
  - lib/geocoder/configuration.rb
40
41
  - lib/geocoder/exceptions.rb
42
+ - lib/geocoder/lookup.rb
41
43
  - lib/geocoder/lookups/base.rb
42
44
  - lib/geocoder/lookups/bing.rb
43
45
  - lib/geocoder/lookups/freegeoip.rb
@@ -54,6 +56,7 @@ files:
54
56
  - lib/geocoder/models/mongo_base.rb
55
57
  - lib/geocoder/models/mongo_mapper.rb
56
58
  - lib/geocoder/models/mongoid.rb
59
+ - lib/geocoder/query.rb
57
60
  - lib/geocoder/railtie.rb
58
61
  - lib/geocoder/request.rb
59
62
  - lib/geocoder/results/base.rb
@@ -67,6 +70,7 @@ files:
67
70
  - lib/geocoder/results/test.rb
68
71
  - lib/geocoder/results/yahoo.rb
69
72
  - lib/geocoder/results/yandex.rb
73
+ - lib/geocoder/sql.rb
70
74
  - lib/geocoder/stores/active_record.rb
71
75
  - lib/geocoder/stores/base.rb
72
76
  - lib/geocoder/stores/mongo_base.rb
@@ -74,6 +78,7 @@ files:
74
78
  - lib/geocoder/stores/mongoid.rb
75
79
  - lib/geocoder/version.rb
76
80
  - lib/tasks/geocoder.rake
81
+ - test/active_record_test.rb
77
82
  - test/calculations_test.rb
78
83
  - test/configuration_test.rb
79
84
  - test/custom_block_test.rb
@@ -95,21 +100,22 @@ files:
95
100
  - test/fixtures/mapquest_no_results.json
96
101
  - test/fixtures/nominatim_madison_square_garden.json
97
102
  - test/fixtures/nominatim_no_results.json
98
- - test/fixtures/yahoo_garbage.json
99
103
  - test/fixtures/yahoo_madison_square_garden.json
100
104
  - test/fixtures/yahoo_no_results.json
105
+ - test/fixtures/yahoo_v1_madison_square_garden.json
106
+ - test/fixtures/yahoo_v1_no_results.json
101
107
  - test/fixtures/yandex_invalid_key.json
102
108
  - test/fixtures/yandex_kremlin.json
103
109
  - test/fixtures/yandex_no_results.json
104
110
  - test/geocoder_test.rb
105
111
  - test/https_test.rb
106
- - test/input_handling_test.rb
107
112
  - test/integration/smoke_test.rb
108
113
  - test/lookup_test.rb
109
114
  - test/method_aliases_test.rb
110
115
  - test/mongoid_test.rb
111
116
  - test/mongoid_test_helper.rb
112
117
  - test/proxy_test.rb
118
+ - test/query_test.rb
113
119
  - test/result_test.rb
114
120
  - test/services_test.rb
115
121
  - test/test_helper.rb
@@ -128,7 +134,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
128
134
  version: '0'
129
135
  segments:
130
136
  - 0
131
- hash: 585705263
137
+ hash: -301313299
132
138
  required_rubygems_version: !ruby/object:Gem::Requirement
133
139
  none: false
134
140
  requirements:
@@ -137,7 +143,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
137
143
  version: '0'
138
144
  segments:
139
145
  - 0
140
- hash: 585705263
146
+ hash: -301313299
141
147
  requirements: []
142
148
  rubyforge_project:
143
149
  rubygems_version: 1.8.24
@@ -1,552 +0,0 @@
1
- = Geocoder
2
-
3
- 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 <tt>Venue.near("Billings, MT")</tt>.
4
-
5
-
6
- == Compatibility
7
-
8
- * Supports multiple Ruby versions: Ruby 1.8.7, 1.9.2, and JRuby.
9
- * Supports multiple databases: MySQL, PostgreSQL, SQLite, and MongoDB (1.7.0 and higher).
10
- * Supports Rails 3. If you need to use it with Rails 2 please see the <tt>rails2</tt> branch (no longer maintained, limited feature set).
11
- * Works very well outside of Rails, you just need to install either the +json+ (for MRI) or +json_pure+ (for JRuby) gem.
12
-
13
-
14
- == Install
15
-
16
- === As a Gem
17
-
18
- Add to your Gemfile:
19
-
20
- gem "geocoder"
21
-
22
- and run at the command prompt:
23
-
24
- bundle install
25
-
26
- === Or As a Plugin
27
-
28
- At the command prompt:
29
-
30
- rails plugin install git://github.com/alexreisner/geocoder.git
31
-
32
-
33
- == Configure Object Geocoding
34
-
35
- In the below, note that addresses may be street or IP addresses.
36
-
37
- === ActiveRecord
38
-
39
- 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 "More on Configuration" below):
40
-
41
- rails generate migration AddLatitudeAndLongitudeToModel latitude:float longitude:float
42
- rake db:migrate
43
-
44
- 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+).
45
-
46
- Next, your model must tell Geocoder which method returns your object's geocodable address:
47
-
48
- geocoded_by :full_street_address # can also be an IP address
49
- after_validation :geocode # auto-fetch coordinates
50
-
51
- For reverse geocoding, tell Geocoder which attributes store latitude and longitude:
52
-
53
- reverse_geocoded_by :latitude, :longitude
54
- after_validation :reverse_geocode # auto-fetch address
55
-
56
- === Mongoid
57
-
58
- First, your model must have an array field for storing coordinates:
59
-
60
- field :coordinates, :type => Array
61
-
62
- You may also want an address field, like this:
63
-
64
- field :address
65
-
66
- 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.
67
-
68
- Once your fields are defined, include the <tt>Geocoder::Model::Mongoid</tt> module and then call <tt>geocoded_by</tt>:
69
-
70
- include Geocoder::Model::Mongoid
71
- geocoded_by :address # can also be an IP address
72
- after_validation :geocode # auto-fetch coordinates
73
-
74
- Reverse geocoding is similar:
75
-
76
- include Geocoder::Model::Mongoid
77
- reverse_geocoded_by :coordinates
78
- after_validation :reverse_geocode # auto-fetch address
79
-
80
- Be sure to read <i>Latitude/Longitude Order</i> in the <i>Notes on MongoDB</i> section below on how to properly retrieve latitude/longitude coordinates from your objects.
81
-
82
- === MongoMapper
83
-
84
- MongoMapper is very similar to Mongoid, just be sure to include <tt>Geocoder::Model::MongoMapper</tt>.
85
-
86
- === Mongo Indices
87
-
88
- By default, the methods <tt>geocoded_by</tt> and <tt>reverse_geocoded_by</tt> create a geospatial index. You can avoid index creation with the <tt>:skip_index option</tt>, for example:
89
-
90
- include Geocoder::Model::Mongoid
91
- geocoded_by :address, :skip_index => true
92
-
93
- === Bulk Geocoding
94
-
95
- 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:
96
-
97
- rake geocode:all CLASS=YourModel
98
-
99
- Geocoder will print warnings if you exceed the rate limit for your geocoding service.
100
-
101
-
102
- == Request Geocoding by IP Address
103
-
104
- Geocoder adds a +location+ method to the standard <tt>Rack::Request</tt> 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:
105
-
106
- # returns Geocoder::Result object
107
- result = request.location
108
-
109
- See "Advanced Geocoding" below for more information about Geocoder::Result objects.
110
-
111
-
112
- == Location-Aware Database Queries
113
-
114
- To find objects by location, use the following scopes:
115
-
116
- Venue.near('Omaha, NE, US', 20) # venues within 20 miles of Omaha
117
- Venue.near([40.71, 100.23], 20) # venues within 20 miles of a point
118
- Venue.geocoded # venues with coordinates
119
- Venue.not_geocoded # venues without coordinates
120
-
121
- With geocoded objects you can do things like this:
122
-
123
- obj.nearbys(30) # other objects within 30 miles
124
- obj.distance_from([40.714,-100.234]) # distance from arbitrary point to object
125
- obj.bearing_to("Paris, France") # direction from object to arbitrary point
126
-
127
- Some utility methods are also available:
128
-
129
- # look up coordinates of some location (like searching Google Maps)
130
- Geocoder.coordinates("25 Main St, Cooperstown, NY")
131
- => [42.700149, -74.922767]
132
-
133
- # distance (in miles) between Eiffel Tower and Empire State Building
134
- Geocoder::Calculations.distance_between([47.858205,2.294359], [40.748433,-73.985655])
135
- => 3619.77359999382
136
-
137
- # find the geographic center (aka center of gravity) of objects or points
138
- Geocoder::Calculations.geographic_center([city1, city2, [40.22,-73.99], city4])
139
- => [35.14968, -90.048929]
140
-
141
- Please see the code for more methods and detailed information about arguments (eg, working with kilometers).
142
-
143
-
144
- == Distance and Bearing
145
-
146
- When you run a location-aware query the returned objects have two attributes added to them (only w/ ActiveRecord):
147
-
148
- * <tt>obj.distance</tt> - number of miles from the search point to this object
149
- * <tt>obj.bearing</tt> - direction from the search point to this object
150
-
151
- 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:
152
-
153
- * <tt>0</tt> - due north
154
- * <tt>180</tt> - due south
155
- * <tt>90</tt> - due east
156
- * <tt>270</tt> - due west
157
- * <tt>230.1</tt> - southwest
158
- * <tt>359.9</tt> - almost due north
159
-
160
- You can convert these numbers to compass point names by using the utility method provided:
161
-
162
- Geocoder::Calculations.compass_point(355) # => "N"
163
- Geocoder::Calculations.compass_point(45) # => "NE"
164
- Geocoder::Calculations.compass_point(208) # => "SW"
165
-
166
- <i>Note: when using SQLite +distance+ and +bearing+ values are provided for interface consistency only. They are not very accurate.</i>
167
-
168
- To calculate accurate distance and bearing with SQLite or MongoDB:
169
-
170
- obj.distance_to([43.9,-98.6]) # distance from obj to point
171
- obj.bearing_to([43.9,-98.6]) # bearing from obj to point
172
- obj.bearing_from(obj2) # bearing from obj2 to obj
173
-
174
- The <tt>bearing_from/to</tt> methods take a single argument which can be: a <tt>[lat,lon]</tt> array, a geocoded object, or a geocodable address (string). The <tt>distance_from/to</tt> methods also take a units argument (<tt>:mi</tt> or <tt>:km</tt>).
175
-
176
-
177
- == More on Configuration
178
-
179
- 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:
180
-
181
- geocoded_by :address, :latitude => :lat, :longitude => :lon # ActiveRecord
182
- geocoded_by :address, :coordinates => :coords # MongoDB
183
-
184
- The +address+ method can return any string you'd use to search Google Maps. For example, any of the following are acceptable:
185
-
186
- * "714 Green St, Big Town, MO"
187
- * "Eiffel Tower, Paris, FR"
188
- * "Paris, TX, US"
189
-
190
- If your model has +street+, +city+, +state+, and +country+ attributes you might do something like this:
191
-
192
- geocoded_by :address
193
-
194
- def address
195
- [street, city, state, country].compact.join(', ')
196
- end
197
-
198
- For reverse geocoding you can also specify an alternate name attribute where the address will be stored, for example:
199
-
200
- reverse_geocoded_by :latitude, :longitude, :address => :location # ActiveRecord
201
- reverse_geocoded_by :coordinates, :address => :loc # MongoDB
202
-
203
-
204
- == Advanced Querying
205
-
206
- When querying for objects (if you're using ActiveRecord) you can also look within a square rather than a radius (circle) by using the <tt>within_bounding_box</tt> scope:
207
-
208
- distance = 20
209
- center_point = [40.71, 100.23]
210
- box = Geocoder::Calculations.bounding_box(center_point, distance)
211
- Venue.within_bounding_box(box, distance)
212
-
213
- 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. If you want to improve performance AND have access to distance and bearing info, use both scopes:
214
-
215
- Venue.near(center_point, distance).within_bounding_box(box, distance)
216
-
217
-
218
- == Advanced Geocoding
219
-
220
- 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 <tt>Geocoder::Result</tt> objects) in which you handle the parsed geocoding result any way you like, for example:
221
-
222
- reverse_geocoded_by :latitude, :longitude do |obj,results|
223
- if geo = results.first
224
- obj.city = geo.city
225
- obj.zipcode = geo.postal_code
226
- obj.country = geo.country_code
227
- end
228
- end
229
- after_validation :reverse_geocode
230
-
231
- Every <tt>Geocoder::Result</tt> object, +result+, provides the following data:
232
-
233
- * <tt>result.latitude</tt> - float
234
- * <tt>result.longitude</tt> - float
235
- * <tt>result.coordinates</tt> - array of the above two
236
- * <tt>result.address</tt> - string
237
- * <tt>result.city</tt> - string
238
- * <tt>result.state</tt> - string
239
- * <tt>result.state_code</tt> - string
240
- * <tt>result.postal_code</tt> - string
241
- * <tt>result.country</tt> - string
242
- * <tt>result.country_code</tt> - string
243
-
244
- 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 <tt>Geocoder::Result</tt> object you're using and the structure of your geocoding service's responses. (See below for links to geocoding service documentation.)
245
-
246
-
247
- == Geocoding Services
248
-
249
- By default Geocoder uses Google's geocoding API to fetch coordinates and street addresses (FreeGeoIP is used 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:
250
-
251
- # config/initializers/geocoder.rb
252
- Geocoder.configure do |config|
253
-
254
- # geocoding service (see below for supported options):
255
- config.lookup = :yahoo
256
-
257
- # to use an API key:
258
- config.api_key = "..."
259
-
260
- # geocoding service request timeout, in seconds (default 3):
261
- config.timeout = 5
262
-
263
- # set default units to kilometers:
264
- config.units = :km
265
-
266
- # caching (see below for details):
267
- config.cache = Redis.new
268
- config.cache_prefix = "..."
269
-
270
- end
271
-
272
- Please see lib/geocoder/configuration.rb for a complete list of configuration options.
273
-
274
-
275
- === Listing and Comparison
276
-
277
- 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.
278
-
279
- ==== Google (<tt>:google</tt>)
280
-
281
- API key:: required for Premier (do NOT use a key for the free version)
282
- Key signup:: http://code.google.com/apis/maps/signup.html
283
- Quota:: 2,500 requests/day, 100,000 with Google Maps API Premier
284
- Region:: world
285
- SSL support:: yes
286
- 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)
287
- Documentation:: http://code.google.com/apis/maps/documentation/geocoding/#JSON
288
- Terms of Service:: http://code.google.com/apis/maps/terms.html#section_10_12
289
- 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..."
290
- Notes:: To use Google Premier set <tt>Geocoder::Configuration.lookup = :google_premier</tt> and <tt>Geocoder::Configuration.api_key = [key, client, channel]</tt>.
291
-
292
- ==== Yahoo (<tt>:yahoo</tt>)
293
-
294
- API key:: optional in development (required for production apps)
295
- Key signup:: https://developer.apps.yahoo.com/wsregapp
296
- Quota:: 50,000 requests/day, more available by special arrangement
297
- Region:: world
298
- SSL support:: no
299
- Languages:: ?
300
- Documentation:: http://developer.yahoo.com/geo/placefinder/guide/responses.html
301
- Terms of Service:: http://info.yahoo.com/legal/us/yahoo/maps/mapsapi/mapsapi-2141.html
302
- Limitations:: "YOU SHALL NOT... (viii) store or allow end users to store map imagery, map data or geocoded location information from the Yahoo! Maps APIs for any future use; (ix) use the stand-alone geocoder for any use other than displaying Yahoo! Maps or displaying points on Yahoo! Maps;"
303
-
304
- ==== Bing (<tt>:bing</tt>)
305
-
306
- API key:: required
307
- Key signup:: http://www.bingmapsportal.com
308
- Quota:: 50,000 requests/24 hrs
309
- Region:: world
310
- SSL support:: no
311
- Languages:: ?
312
- Documentation:: http://msdn.microsoft.com/en-us/library/ff701715.aspx
313
- Terms of Service:: http://www.microsoft.com/maps/product/terms.html
314
- 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."
315
-
316
- ==== Nominatim (<tt>:nominatim</tt>)
317
-
318
- API key:: none
319
- Quota:: 1 request/second
320
- Region:: world
321
- SSL support:: no
322
- Languages:: ?
323
- Documentation:: http://wiki.openstreetmap.org/wiki/Nominatim
324
- Terms of Service:: http://wiki.openstreetmap.org/wiki/Nominatim_usage_policy
325
- Limitations:: Please limit request rate to 1 per second and include your contact information in User-Agent headers. Data licensed under CC-BY-SA (you must provide attribution).
326
-
327
- ==== Yandex (<tt>:yandex</tt>)
328
-
329
- API key:: none
330
- Quota:: 25000 requests / day
331
- Region:: Russia
332
- SSL support:: no
333
- Languages:: Russian, Belarusian, and Ukrainian
334
- Documentation:: http://api.yandex.ru/maps/geocoder/doc/desc/concepts/response_structure.xml
335
- Terms of Service:: http://api.yandex.com/direct/eula.xml?ncrnd=8453
336
- Limitations:: ?
337
-
338
- ==== Geocoder.ca (<tt>:geocoder_ca</tt>)
339
-
340
- API key:: none
341
- Quota:: ?
342
- Region:: US and Canada
343
- SSL support:: no
344
- Languages:: English
345
- Documentation:: ?
346
- Terms of Service:: http://geocoder.ca/?terms=1
347
- Limitations:: "Under no circumstances can our data be re-distributed or re-sold by anyone to other parties without our written permission."
348
-
349
- ==== Mapquest (<tt>:mapquest</tt>)
350
-
351
- API key:: none
352
- Quota:: ?
353
- Region:: world
354
- SSL support:: no
355
- Languages:: English
356
- Documentation:: http://www.mapquestapi.com/geocoding/
357
- Terms of Service:: http://info.mapquest.com/terms-of-use/
358
- Limitations:: ?
359
-
360
- ==== FreeGeoIP
361
-
362
- API key:: none
363
- Quota:: 1000 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.
364
- Region:: world
365
- SSL support:: no
366
- Languages:: English
367
- Documentation:: http://github.com/fiorix/freegeoip/blob/master/README.rst
368
- Terms of Service:: ?
369
- Limitations:: ?
370
-
371
-
372
- == Caching
373
-
374
- 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:
375
-
376
- Geocoder::Configuration.cache = Redis.new
377
-
378
- This example uses Redis, but the cache store can be any object that supports these methods:
379
-
380
- * <tt>store#[](key)</tt> - retrieves a value
381
- * <tt>store#[]=(key, value)</tt> - stores a value
382
- * <tt>store#keys</tt> - lists all keys
383
-
384
- 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).
385
-
386
- You can also set a custom prefix to be used for cache keys:
387
-
388
- Geocoder::Configuration.cache_prefix = "..."
389
-
390
- By default the prefix is <tt>geocoder:</tt>
391
-
392
- If you need to expire cached content:
393
-
394
- Geocoder.cache.expire("http://...") # expire cached result for a URL
395
- Geocoder.cache.expire(:all) # expire all cached results
396
-
397
- Do *not* include the prefix when passing a URL to be expired. Expiring <tt>:all</tt> will only expire keys with the configured prefix (won't kill every entry in your key/value store).
398
-
399
- <i>Before you implement caching in your app please be sure that doing so does not violate the Terms of Service for your geocoding service.</i>
400
-
401
-
402
- == Forward and Reverse Geocoding in the Same Model
403
-
404
- 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:
405
-
406
- * one for storing the fetched address (reverse geocoding)
407
- * one for providing an address to use when fetching coordinates (forward geocoding)
408
-
409
- For example:
410
-
411
- class Venue
412
-
413
- # build an address from street, city, and state attributes
414
- geocoded_by :address_from_components
415
-
416
- # store the fetched address in the full_address attribute
417
- reverse_geocoded_by :latitude, :longitude, :address => :full_address
418
- end
419
-
420
- However, there can be only one set of latitude/longitude attributes, and whichever you specify last will be used. For example:
421
-
422
- class Venue
423
-
424
- geocoded_by :address,
425
- :latitude => :fetched_latitude, # this will be overridden by the below
426
- :longitude => :fetched_longitude # same here
427
-
428
- reverse_geocoded_by :latitude, :longitude
429
- end
430
-
431
- The reason for this is that we don't want ambiguity when doing distance calculations. We need a single, authoritative source for coordinates!
432
-
433
-
434
- == Use Outside of Rails
435
-
436
- You can use Geocoder outside of Rails by calling the <tt>Geocoder.search</tt> method:
437
-
438
- results = Geocoder.search("McCarren Park, Brooklyn, NY")
439
-
440
- This returns an array of <tt>Geocoder::Result</tt> objects with all information provided by the geocoding service. Please see above and in the code for details.
441
-
442
-
443
- == Testing Apps that Use Geocoder
444
-
445
- 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 <tt>:test</tt> lookup. For example:
446
-
447
- Geocoder::Configuration.lookup = :test
448
-
449
- Geocoder::Lookup::Test.add_stub(
450
- "New York, NY", [
451
- {
452
- 'latitude' => 40.7143528,
453
- 'longitude' => -74.0059731,
454
- 'address' => 'New York, NY, USA',
455
- 'state' => 'New York',
456
- 'state_code' => 'NY',
457
- 'country' => 'United States',
458
- 'country_code' => 'US'
459
- }
460
- ]
461
- )
462
-
463
- Now, any time Geocoder looks up "New York, NY" its results array will contain one result with the above attributes.
464
-
465
-
466
- == Command Line Interface
467
-
468
- 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:
469
-
470
- $ geocode 29.951,-90.081
471
- Latitude: 29.952211
472
- Longitude: -90.080563
473
- Full address: 1500 Sugar Bowl Dr, New Orleans, LA 70112, USA
474
- City: New Orleans
475
- State/province: Louisiana
476
- Postal code: 70112
477
- Country: United States
478
- Google map: http://maps.google.com/maps?q=29.952211,-90.080563
479
-
480
- There are also a number of options for setting the geocoding API, key, and language, viewing the raw JSON reponse, and more. Please run <tt>geocode -h</tt> for details.
481
-
482
-
483
- == Notes on MongoDB
484
-
485
- === The Near Method
486
-
487
- 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.
488
-
489
- === Latitude/Longitude Order
490
-
491
- 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.
492
-
493
- To access an object's coordinates in the conventional order, use the <tt>to_coordinates</tt> instance method provided by Geocoder. For example:
494
-
495
- obj.to_coordinates # => [37.7941013, -122.3951096] # [lat, lon]
496
-
497
- Calling <tt>obj.coordinates</tt> directly returns the internal representation of the coordinates which, in the case of MongoDB, is probably the reverse of what you want:
498
-
499
- obj.coordinates # => [-122.3951096, 37.7941013] # [lon, lat]
500
-
501
- For consistency with the rest of Geocoder, always use the <tt>to_coordinates</tt> method instead.
502
-
503
-
504
- == Distance Queries in SQLite
505
-
506
- 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.
507
-
508
-
509
- === Discussion
510
-
511
- There are few options for finding objects near a given point in SQLite without installing extensions:
512
-
513
- 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.
514
-
515
- 2. Load all objects into memory and compute distances between them using the <tt>Geocoder::Calculations.distance_between</tt> 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.
516
-
517
- 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 <tt>Geocoder::Calculations.distance_between</tt>.
518
-
519
- 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.
520
-
521
-
522
- == Tests
523
-
524
- Geocoder comes with a test suite (just run <tt>rake test</tt>) 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:
525
-
526
- http://github.com/alexreisner/geocoder_test
527
-
528
-
529
- == Error Handling
530
-
531
- By default Geocoder will rescue any exceptions raised by calls to the geocoding service and return an empty array (using warn() to inform you of the error). You can override this and implement custom error handling for certain exceptions by using the <tt>:always_raise</tt> option:
532
-
533
- Geocoder::Configuration.always_raise = [SocketError, TimeoutError]
534
-
535
- You can also do this to raise all exceptions:
536
-
537
- Geocoder::Configuration.always_raise = :all
538
-
539
- See <tt>lib/geocoder/exceptions.rb</tt> for a list of raise-able exceptions.
540
-
541
-
542
- == Known Issue
543
-
544
- 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). Instead, try using +joins+ and pass a <tt>:select</tt> option to the +near+ scope to get the columns you want. For example:
545
-
546
- # instead of City.near(...).includes(:venues)
547
- City.near("Omaha, NE", 20, :select => "cities.*, venues.*").joins(:venues)
548
-
549
- If anyone has a more elegant solution to this problem I am very interested in seeing it.
550
-
551
-
552
- Copyright (c) 2009-12 Alex Reisner, released under the MIT license