geokit-rails 2.5.0 → 2.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/ci.yml +80 -0
  3. data/.gitignore +44 -37
  4. data/CHANGELOG.md +106 -101
  5. data/CONFIG.markdown +67 -67
  6. data/Gemfile +3 -3
  7. data/MIT-LICENSE +19 -19
  8. data/README.markdown +726 -726
  9. data/Rakefile +17 -17
  10. data/gemfiles/rails7.1.gemfile +11 -0
  11. data/gemfiles/{rails5.gemfile → rails7.2.gemfile} +7 -7
  12. data/gemfiles/{rails6.0.gemfile → rails8.0.gemfile} +7 -8
  13. data/gemfiles/{rails6.1.gemfile → rails8.1.gemfile} +7 -8
  14. data/geokit-rails.gemspec +34 -34
  15. data/lib/generators/geokit_rails/install_generator.rb +13 -13
  16. data/lib/generators/templates/geokit_config.rb +100 -100
  17. data/lib/geokit-rails/acts_as_mappable/class_methods.rb +299 -297
  18. data/lib/geokit-rails/acts_as_mappable/glue.rb +54 -54
  19. data/lib/geokit-rails/acts_as_mappable.rb +78 -78
  20. data/lib/geokit-rails/adapters/abstract.rb +30 -30
  21. data/lib/geokit-rails/adapters/mysql.rb +21 -21
  22. data/lib/geokit-rails/adapters/mysql2.rb +8 -8
  23. data/lib/geokit-rails/adapters/mysql2spatial.rb +8 -8
  24. data/lib/geokit-rails/adapters/oracleenhanced.rb +32 -32
  25. data/lib/geokit-rails/adapters/postgresql.rb +21 -21
  26. data/lib/geokit-rails/adapters/sqlite.rb +53 -53
  27. data/lib/geokit-rails/adapters/sqlserver.rb +45 -45
  28. data/lib/geokit-rails/distance_collection.rb +8 -8
  29. data/lib/geokit-rails/geocoder_control.rb +19 -19
  30. data/lib/geokit-rails/ip_geocode_lookup.rb +44 -45
  31. data/lib/geokit-rails/railtie.rb +37 -37
  32. data/lib/geokit-rails/version.rb +3 -3
  33. data/lib/geokit-rails.rb +11 -11
  34. data/test/acts_as_mappable_test.rb +486 -478
  35. data/test/adapter_resolution_test.rb +46 -0
  36. data/test/boot.rb +40 -32
  37. data/test/database.yml +31 -28
  38. data/test/distance_collection_test.rb +41 -41
  39. data/test/dummy/Rakefile +6 -6
  40. data/test/dummy/app/assets/stylesheets/application.css +1 -1
  41. data/test/dummy/app/channels/application_cable/channel.rb +4 -4
  42. data/test/dummy/app/channels/application_cable/connection.rb +4 -4
  43. data/test/dummy/app/controllers/application_controller.rb +3 -3
  44. data/test/dummy/app/controllers/location_aware_controller.rb +42 -42
  45. data/test/dummy/app/helpers/application_helper.rb +2 -2
  46. data/test/dummy/app/jobs/application_job.rb +7 -7
  47. data/test/dummy/app/mailers/application_mailer.rb +4 -4
  48. data/test/dummy/app/models/application_record.rb +3 -3
  49. data/test/dummy/app/views/layouts/application.html.erb +15 -15
  50. data/test/dummy/app/views/layouts/mailer.html.erb +13 -13
  51. data/test/dummy/app/views/layouts/mailer.text.erb +1 -1
  52. data/test/dummy/bin/rails +4 -4
  53. data/test/dummy/bin/rake +4 -4
  54. data/test/dummy/bin/setup +33 -33
  55. data/test/dummy/config/application.rb +22 -22
  56. data/test/dummy/config/boot.rb +5 -5
  57. data/test/dummy/config/cable.yml +10 -10
  58. data/test/dummy/config/database.yml +25 -25
  59. data/test/dummy/config/environment.rb +5 -5
  60. data/test/dummy/config/environments/development.rb +68 -68
  61. data/test/dummy/config/environments/production.rb +87 -87
  62. data/test/dummy/config/environments/test.rb +60 -60
  63. data/test/dummy/config/initializers/content_security_policy.rb +25 -25
  64. data/test/dummy/config/initializers/filter_parameter_logging.rb +8 -8
  65. data/test/dummy/config/initializers/inflections.rb +16 -16
  66. data/test/dummy/config/initializers/permissions_policy.rb +11 -11
  67. data/test/dummy/config/locales/en.yml +33 -33
  68. data/test/dummy/config/puma.rb +43 -43
  69. data/test/dummy/config/routes.rb +6 -6
  70. data/test/dummy/config/storage.yml +34 -34
  71. data/test/dummy/config.ru +6 -6
  72. data/test/dummy/public/404.html +67 -67
  73. data/test/dummy/public/422.html +67 -67
  74. data/test/dummy/public/500.html +66 -66
  75. data/test/fixtures/companies.yml +9 -9
  76. data/test/fixtures/custom_locations.yml +61 -61
  77. data/test/fixtures/locations.yml +61 -61
  78. data/test/fixtures/mock_addresses.yml +16 -16
  79. data/test/fixtures/mock_families.yml +2 -2
  80. data/test/fixtures/mock_houses.yml +8 -8
  81. data/test/fixtures/mock_organizations.yml +4 -4
  82. data/test/fixtures/mock_people.yml +4 -4
  83. data/test/ip_geocode_lookup_test.rb +52 -48
  84. data/test/models/company.rb +2 -2
  85. data/test/models/custom_location.rb +11 -11
  86. data/test/models/location.rb +3 -3
  87. data/test/models/mock_address.rb +3 -3
  88. data/test/models/mock_family.rb +4 -4
  89. data/test/models/mock_house.rb +2 -2
  90. data/test/models/mock_organization.rb +5 -5
  91. data/test/models/mock_person.rb +6 -6
  92. data/test/models/store.rb +2 -2
  93. data/test/schema.rb +61 -61
  94. data/test/tasks.rake +37 -37
  95. data/test/test_helper.rb +83 -73
  96. metadata +13 -15
  97. data/.travis.yml +0 -55
  98. data/gemfiles/rails3.gemfile +0 -8
  99. data/gemfiles/rails4.gemfile +0 -8
data/README.markdown CHANGED
@@ -1,726 +1,726 @@
1
- Geokit Rails
2
- ============
3
-
4
- [![Gem Version](https://badge.fury.io/rb/geokit-rails.svg)](http://badge.fury.io/rb/geokit-rails)
5
- [![Build Status](https://travis-ci.org/geokit/geokit-rails.svg?branch=master)](https://travis-ci.org/geokit/geokit-rails)
6
- [![Coverage Status](https://coveralls.io/repos/geokit/geokit-rails/badge.svg?branch=master)](https://coveralls.io/r/geokit/geokit-rails)
7
- [![Code Climate](https://codeclimate.com/github/geokit/geokit-rails.svg)](https://codeclimate.com/github/geokit/geokit-rails)
8
-
9
- ## COMMUNICATION
10
-
11
- * If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/geokit). (Tag 'geokit' and we'll be alerted)
12
- * If you **found a bug**, use GitHub issues.
13
- * If you **have an idea**, use GitHub issues.
14
- * If you'd like to **ask a general question**, use GitHub issues.
15
- * If you **want to contribute**, submit a pull request.
16
-
17
- ## INSTALLATION
18
-
19
- Geokit for Rails consists of a generic Gem ([geokit](https://github.com/geokit/geokit)) and a Rails plugin ([geokit-rails](https://github.com/geokit/geokit-rails)).
20
-
21
- Make sure you use a version >= 3.0 of Rails.
22
-
23
- You just have to add the 'geokit-rails' gem to your Gemfile
24
-
25
- ```ruby
26
- gem 'geokit-rails'
27
- ```
28
-
29
- Then tell bundler to update the gems :
30
-
31
- ```sh
32
- $ bundle install
33
- ```
34
- Generate the configuration initializer:
35
-
36
- ```sh
37
- $ rails g geokit_rails:install
38
- ```
39
-
40
- Now, if you wish to use the various geocoding services, you can add your keys to the new initializer.
41
-
42
-
43
-
44
- If you want to use geokit-rails in a Rails 2 application, just use the good old plugin ([geokit-rails](https://github.com/andre/geokit-rails)).
45
-
46
-
47
- ## FEATURE SUMMARY
48
-
49
- Geokit provides key functionality for location-oriented Rails applications:
50
-
51
- - Distance calculations, for both flat and spherical environments. For example,
52
- given the location of two points on the earth, you can calculate the miles/Km
53
- between them.
54
- - ActiveRecord distance-based finders. For example, you can find all the points
55
- in your database within a 50-mile radius.
56
- - IP-based location lookup utilizing hostip.info. Provide an IP address, and get
57
- city name and latitude/longitude in return
58
- - A before_action helper to geocoder the user's location based on IP address,
59
- and retain the location in a cookie.
60
- - Geocoding from multiple providers. It provides a fail-over mechanism, in case
61
- your input fails to geocode in one service. Geocoding is provided by the Geokit
62
- gem, which you must have installed
63
-
64
- The goal of this plugin is to provide the common functionality for location-oriented
65
- applications (geocoding, location lookup, distance calculation) in an easy-to-use
66
- package.
67
-
68
- ## A NOTE ON TERMINOLOGY
69
-
70
- Throughout the code and API, _latitude_ and _longitude_ are referred to as _lat_
71
- and _lng_. We've found over the long term the abbreviation saves lots of typing time.
72
-
73
- ## LOCATION QUERIES
74
-
75
- ### MAKING A MODEL MAPPABLE
76
-
77
- To get started, just specify an ActiveRecord class as `acts_as_mappable`:
78
-
79
- ```ruby
80
- class Location < ActiveRecord::Base
81
- acts_as_mappable
82
- end
83
- ```
84
-
85
- There are some defaults you can override:
86
-
87
- ```ruby
88
- class Location < ActiveRecord::Base
89
- acts_as_mappable :default_units => :miles,
90
- :default_formula => :sphere,
91
- :distance_field_name => :distance,
92
- :lat_column_name => :lat,
93
- :lng_column_name => :lng
94
- end
95
- ```
96
-
97
- The optional parameters are `units`, `formula`, and `distance_field_name`.
98
- Values for **units** can be `:miles`, `:kms` (kilometers), or `:nms` (nautical miles),
99
- with `:miles` as the default.
100
- Values for **formula** can be `:sphere` or `:flat` with `:sphere` as the default.
101
- `:sphere` gives you Haversine calculations, while `:flat` gives the Pythagoreum Theory.
102
- These defaults persist through out the gem.
103
-
104
- The plug-in creates a calculated `distance` field on AR instances that have
105
- been retrieved through a Geokit location query. By default, these fields are
106
- known as "distance" but this can be changed through the `:distance_field_name` key.
107
-
108
- You can also define alternative column names for latitude and longitude using
109
- the `:lat_column_name` and `:lng_column_name` keys. The defaults are `lat` and
110
- `lng` respectively.
111
-
112
- ### NEW SCOPES TO USE
113
-
114
- Once you've specified `acts_as_mappable`, a few scopes are available :
115
-
116
- * `within` and `beyond` find records within or beyond a certain distance from the origin point.
117
- * `in_range` finds records within a certain distance range from the origin point.
118
- * `in_bounds` finds records within a rectangle on the map
119
- * `closest` and `farthest` find the closest or farthest record from the origin point
120
- * `by_distance` finds records ordered by distance from the origin point
121
-
122
- All of these scopes take a hash of options where the first parameter is simply
123
- one of the possible options, without the name.
124
-
125
- A few examples :
126
-
127
- ```ruby
128
- Location.within(5, :origin => @somewhere)
129
- ```
130
-
131
- ```ruby
132
- Location.in_range(2..5, :origin => @somewhere)
133
- ```
134
-
135
- ```ruby
136
- Location.in_bounds([@south_west_point, @north_east_point], :origin => @somewhere)
137
- ```
138
-
139
- The options can be :
140
-
141
- `:origin` as a two-element array of latitude/longitude:
142
-
143
- ```ruby
144
- Location.by_distance(:origin => [37.792,-122.393])
145
- ```
146
-
147
- `:origin` as a geocodeable string:
148
-
149
- ```ruby
150
- Location.by_distance(:origin => '100 Spear st, San Francisco, CA')
151
- ```
152
-
153
- `:origin` as an object which responds to `lat` and `lng` methods,
154
- or `latitude` and `longitude` methods, or whatever methods you have
155
- specified for `lng_column_name` and `lat_column_name`:
156
-
157
- ```ruby
158
- Location.geo_scope(:origin => my_store)
159
- # my_store.lat and my_store.lng methods exist
160
- ```
161
-
162
- `:units` or `:formula` can be used to override the default values in a specific query
163
-
164
- ```ruby
165
- Location.within(5, :units => :kms, :origin => @somewhere)
166
- # it will get the records within 5 kilometers instead of 5 miles
167
- ```
168
-
169
- `:range` as a native Ruby range
170
-
171
- `:bounds` as an array of two elements : the south/west point and the north/east point.
172
-
173
- ```ruby
174
- @sw = Geokit::LatLng.new(32.91663,-96.982841)
175
- @ne = Geokit::LatLng.new(32.96302,-96.919495)
176
- @somewhere = Location.find(123456)
177
- Location.within(:bounds => [@sw, @ne], :origin => @somewhere)
178
- ```
179
-
180
- `:bounds` as a Geokit::Bounds object
181
-
182
- ```ruby
183
- @bounds = Geokit::Bounds.new([32.91663,-96.982841], [32.96302,-96.919495])
184
- @somewhere = Location.find(123456)
185
- Location.within(:bounds => [@sw, @ne], :origin => @somewhere)
186
- ```
187
-
188
- When using a point of reference or bounds, you leverage the power of Geokit
189
- to build this objects. Basically, if Geokit can make a Geokit::Point
190
- or a Geokit::Bounds with what you give to it, you're good to go.
191
-
192
- ### FIND BY SQL
193
-
194
- Finally, if all that is desired is the raw SQL for distance
195
- calculations, you can use the following:
196
-
197
- ```ruby
198
- Location.distance_sql(origin, units = default_units, formula = default_formula)
199
- ```
200
-
201
- Thereafter, you are free to use it in `find_by_sql` as you wish.
202
-
203
- ### CHAINABILITY
204
-
205
- You can then chain these scope with any other or use a "calling" method like `first`, `all`, `count`, …
206
-
207
- ```ruby
208
- Location.within(5, :origin => @somewhere).all
209
- Location.within(5, :origin => @somewhere).count
210
- Location.by_distance(:origin => [37.792,-122.393]).first
211
- ```
212
-
213
- You can add `order` clauses in the chain as for any ActiveRecord query
214
-
215
- ```ruby
216
- Location.within(5, :origin => @somewhere).order('nbr_seats ASC')
217
- ```
218
-
219
- You can even sort by distance (use the same name as specified in the model class)
220
-
221
- ```ruby
222
- Location.within(5, :origin => @somewhere).order('distance DESC, nbr_seats ASC')
223
- ```
224
-
225
- Idem for the `limit` clause. In fact, `closest` and `farthest` are defined like this :
226
-
227
- ```ruby
228
- def closest(options = {})
229
- by_distance(options).limit(1)
230
- end
231
- def farthest(options = {})
232
- by_distance({:reverse => true}.merge(options)).limit(1)
233
- end
234
- ```
235
-
236
- #### Important caveat
237
-
238
- In the current version of geokit-rails, it is not possible to add a `where` clause
239
- using the _distance_ column. I've tried many different ways to do this and didn't get it working.
240
-
241
- One would expect to build a query like this :
242
-
243
- ```ruby
244
- scoped = Location.by_distance(:origin => @somewhere)
245
- scoped = scoped.where('distance <= 5')
246
- results = scoped.all
247
- ```
248
-
249
- This is not possible right now, it must be done in a single step like this :
250
-
251
- ```ruby
252
- scoped = Location.within(5, :origin => @somewhere)
253
- results = scoped.all
254
- ```
255
-
256
- Every good idea that would help achieve this is very much welcome.
257
-
258
- ### FINDING WITHIN A BOUNDING BOX
259
-
260
- If you are displaying points on a map, you probably need to query for whatever falls within the rectangular bounds of the map:
261
-
262
- ```ruby
263
- Store.in_bounds([sw_point,ne_point]).all
264
- ```
265
-
266
- If you want the query to return things that are located on the rectangular bounds, specify the `inclusive` option set to true:
267
-
268
- ```ruby
269
- Store.in_bounds([sw_point,ne_point], :inclusive => true).all
270
- ```
271
-
272
- The input to `bounds` can be an array with the two points or a Bounds object. However you provide them, the order should always be the southwest corner, northeast corner of the rectangle. Typically, you will be getting the sw\_point and ne\_point from a map that is displayed on a web page.
273
-
274
- If you need to calculate the bounding box from a point and radius, you can do that:
275
-
276
- ```ruby
277
- bounds = Geokit::Bounds.from_point_and_radius(home,5)
278
- Store.in_bounds(bounds).all
279
- ```
280
-
281
- ----
282
-
283
- # What is following is from the previous _geokit-rails_ plugin.
284
-
285
- > **It has not been tested with Rails 3 nor with this version of the gem.**
286
- **Most of it should work, but it is not sure**
287
-
288
-
289
- ## USING INCLUDES
290
-
291
- You can use includes along with your distance finders:
292
-
293
- ```ruby
294
- stores = Store.within(5, :origin=>home).includes([:reviews,:cities]).order('distance asc').all
295
- ```
296
-
297
- *However*, ActiveRecord drops the calculated distance column when you use include. So, if you need to use the distance column, you'll have to re-calculate it post-query in Ruby:
298
-
299
- ```ruby
300
- stores.sort_by{|s| s.distance_to(home)}
301
- ```
302
-
303
- In this case, you may want to just use the bounding box condition alone in your SQL (there's no use calculating the distance twice):
304
-
305
- ```ruby
306
- bounds=Geokit::Bounds.from_point_and_radius(home,5)
307
- stores=Store.includes([:reviews,:cities]).in_bounds(bounds)
308
- stores.sort_by{|s| s.distance_to(home)}
309
- ```
310
-
311
- ## USING :through
312
-
313
- You can also specify a model as mappable "through" another associated model. In other words, that associated model is the actual mappable model with "lat" and "lng" attributes, but this "through" model can still utilize all of the above find methods to search for records.
314
-
315
- ```ruby
316
- class Location < ActiveRecord::Base
317
- belongs_to :locatable, :polymorphic => true
318
- acts_as_mappable
319
- end
320
- ```
321
-
322
- ```ruby
323
- class Company < ActiveRecord::Base
324
- has_one :location, :as => :locatable # also works for belongs_to associations
325
- acts_as_mappable :through => :location
326
- end
327
- ```
328
-
329
- Then you can still call:
330
-
331
- ```ruby
332
- Company.within(distance, :origin => @somewhere)
333
- ```
334
-
335
- You can also give :through a hash if your location is nested deep. For example, given:
336
-
337
- ```ruby
338
- class House
339
- acts_as_mappable
340
- end
341
- ```
342
-
343
- ```ruby
344
- class Family
345
- belongs_to :house
346
- end
347
- ```
348
-
349
- ```ruby
350
- class Person
351
- belongs_to :family
352
- acts_as_mappable :through => { :family => :house }
353
- end
354
- ```
355
-
356
- Remember that the notes above about USING INCLUDES apply to the results from
357
- this find, since an include is automatically used.
358
-
359
- ## IP GEOCODING
360
-
361
- You can obtain the location for an IP at any time using the geocoder
362
- as in the following example:
363
-
364
- ```ruby
365
- location = IpGeocoder.geocode('12.215.42.19')
366
- ```
367
-
368
- where Location is a GeoLoc instance containing the latitude,
369
- longitude, city, state, and country code. Also, the success
370
- value is true.
371
-
372
- If the IP cannot be geocoded, a GeoLoc instance is returned with a
373
- success value of false.
374
-
375
- It should be noted that the IP address needs to be visible to the
376
- Rails application. In other words, you need to ensure that the
377
- requesting IP address is forwarded by any front-end servers that
378
- are out in front of the Rails app. Otherwise, the IP will always
379
- be that of the front-end server.
380
-
381
- The Multi-Geocoder will also geocode IP addresses and provide
382
- failover among multiple IP geocoders. Just pass in an IP address for the
383
- parameter instead of a street address. Eg:
384
-
385
- ```ruby
386
- location = Geocoders::MultiGeocoder.geocode('12.215.42.19')
387
- ```
388
-
389
- The MultiGeocoder class requires 2 configuration setting for the provider order.
390
- Ordering is done through `Geokit::Geocoders::provider_order` and
391
- `Geokit::Geocoders::ip_provider_order`, found in
392
- `config/initializers/geokit_config.rb`. If you don't already have a
393
- `geokit_config.rb` file, the plugin creates one when it is first installed.
394
-
395
-
396
- ## IP GEOCODING HELPER
397
-
398
- A class method called geocode_ip_address has been mixed into the
399
- ActionController::Base. This enables before_action style lookup of
400
- the IP address. Since it is a filter, it can accept any of the
401
- available filter options.
402
-
403
- Usage is as below:
404
-
405
- ```ruby
406
- class LocationAwareController < ActionController::Base
407
- geocode_ip_address
408
- end
409
- ```
410
-
411
- A first-time lookup will result in the GeoLoc class being stored
412
- in the session as `:geo_location` as well as in a cookie called
413
- `:geo_session`. Subsequent lookups will use the session value if it
414
- exists or the cookie value if it doesn't exist. The last resort is
415
- to make a call to the web service. Clients are free to manage the
416
- cookie as they wish.
417
-
418
- The intent of this feature is to be able to provide a good guess as
419
- to a new visitor's location.
420
-
421
- ## INTEGRATED FIND AND GEOCODING
422
-
423
- Geocoding has been integrated with the finders enabling you to pass
424
- a physical address or an IP address. This would look the following:
425
-
426
- ```ruby
427
- Location.farthest(:origin => '217.15.10.9')
428
- Location.farthest(:origin => 'Irving, TX')
429
- ```
430
-
431
- where the IP or physical address would be geocoded to a location and
432
- then the resulting latitude and longitude coordinates would be used
433
- in the find. This is not expected to be common usage, but it can be
434
- done nevertheless.
435
-
436
- ## ADDRESS GEOCODING
437
-
438
- Geocoding is provided by the Geokit gem, which is required for this plugin.
439
- See the top of this file for instructions on installing the Geokit gem.
440
-
441
- Geokit can geocode addresses using multiple geocodeing web services.
442
- Geokit supports services like Google, Yahoo, and Geocoder.us, and more --
443
- see the Geokit gem API for a complete list.
444
-
445
- These geocoder services are made available through the following classes:
446
- GoogleGeocoder, YahooGeocoder, UsGeocoder, CaGeocoder, and GeonamesGeocoder.
447
- Further, an additional geocoder class called MultiGeocoder incorporates an ordered failover
448
- sequence to increase the probability of successful geocoding.
449
-
450
- All classes are called using the following signature:
451
-
452
- ```ruby
453
- include Geokit::Geocoders
454
- location = XxxGeocoder.geocode(address)
455
- ```
456
-
457
- where you replace Xxx Geocoder with the appropriate class. A GeoLoc
458
- instance is the result of the call. This class has a "success"
459
- attribute which will be true if a successful geocoding occurred.
460
- If successful, the lat and lng properties will be populated.
461
-
462
- Geocoders are named with the convention NameGeocoder. This
463
- naming convention enables Geocoder to auto-detect its sub-classes
464
- in order to create methods called `name_geocoder(address)` so that
465
- all geocoders can be called through the base class. This is done
466
- purely for convenience; the individual geocoder classes are expected
467
- to be used independently.
468
-
469
- The MultiGeocoder class requires the configuration of a provider
470
- order which dictates what order to use the various geocoders. Ordering
471
- is done through `Geokit::Geocoders::provider_order`, found in
472
- `config/initializers/geokit_config.rb`.
473
-
474
- If you don't already have a `geokit_config.rb` file, the plugin creates one
475
- when it is first installed.
476
-
477
- Make sure your failover configuration matches the usage characteristics
478
- of your application -- for example, if you routinely get bogus input to
479
- geocode, your code will be much slower if you have to failover among
480
- multiple geocoders before determining that the input was in fact bogus.
481
-
482
- The Geocoder.geocode method returns a GeoLoc object. Basic usage:
483
-
484
- ```ruby
485
- loc=Geocoder.geocode('100 Spear St, San Francisco, CA')
486
- if loc.success
487
- puts loc.lat
488
- puts loc.lng
489
- puts loc.full_address
490
- end
491
- ```
492
-
493
- ## REVERSE GEOCODING
494
-
495
- Currently, only the Google Geocoder supports reverse geocoding.
496
- Pass the lat/lng as a string, array or LatLng instance:
497
-
498
- ```ruby
499
- res=Geokit::Geocoders::GoogleGeocoder.reverse_geocode "37.791821,-122.394679"
500
- # => #<Geokit::GeoLoc:0x558ed0 ...
501
- res.full_address
502
- # => "101-115 Main St, San Francisco, CA 94105, USA"
503
- ```
504
-
505
- The address will usually appear as a range, as it does in the above example.
506
-
507
-
508
- ## INTEGRATED FIND WITH ADDRESS GEOCODING
509
-
510
- Just has you can pass an IP address directly into an ActiveRecord finder
511
- as the origin, you can also pass a physical address as the origin:
512
-
513
- ```ruby
514
- Location.find_closest(:origin => '100 Spear st, San Francisco, CA')
515
- ```
516
-
517
- where the physical address would be geocoded to a location and then the
518
- resulting latitude and longitude coordinates would be used in the
519
- find.
520
-
521
- Note that if the address fails to geocode, the find method will raise an
522
- ActiveRecord::GeocodeError you must be prepared to catch. Alternatively,
523
- You can geocoder the address beforehand, and pass the resulting lat/lng
524
- into the finder if successful.
525
-
526
- ## Auto Geocoding
527
-
528
- If your geocoding needs are simple, you can tell your model to automatically
529
- geocode itself on create:
530
-
531
- ```ruby
532
- class Store < ActiveRecord::Base
533
- acts_as_mappable :auto_geocode=>true
534
- end
535
- ```
536
-
537
- It takes two optional params:
538
-
539
- ```ruby
540
- class Store < ActiveRecord::Base
541
- acts_as_mappable :auto_geocode=>{:field=>:address, :error_message=>'Could not geocode address'}
542
- end
543
- ```
544
-
545
- . . . which is equivalent to:
546
-
547
- ```ruby
548
- class Store << ActiveRecord::Base
549
- acts_as_mappable
550
- before_validation :geocode_address, :on => :create
551
-
552
- private
553
- def geocode_address
554
- geo=Geokit::Geocoders::MultiGeocoder.geocode (address)
555
- errors.add(:address, "Could not Geocode address") if !geo.success
556
- self.lat, self.lng = geo.lat,geo.lng if geo.success
557
- end
558
- end
559
- ```
560
-
561
- If you need any more complicated geocoding behavior for your model, you should roll your own
562
- `before_validate` callback.
563
-
564
-
565
- ## Distances, headings, endpoints, and midpoints
566
-
567
- ```ruby
568
- distance = home.distance_from(work, :units=>:miles)
569
- heading = home.heading_to(work) # result is in degrees, 0 is north
570
- endpoint = home.endpoint(90,2) # two miles due east
571
- midpoint = home.midpoint_to(work)
572
- ```
573
-
574
- ## Cool stuff you can do with bounds
575
-
576
- ```ruby
577
- bounds = Bounds.new(sw_point,ne_point)
578
- bounds.contains?(home)
579
- puts bounds.center
580
- ```
581
-
582
- HOW TO . . .
583
- =================================================================================
584
-
585
- A few quick examples to get you started ....
586
-
587
- ## How to install the Geokit Rails plugin
588
- (See the very top of this file)
589
-
590
- ## How to find all stores within a 10-mile radius of a given lat/lng
591
- 1. ensure your stores table has lat and lng columns with numeric or float
592
- datatypes to store your latitude/longitude
593
-
594
- 2. use `acts_as_mappable` on your store model:
595
- 3.
596
- ```ruby
597
- class Store < ActiveRecord::Base
598
- acts_as_mappable
599
- ...
600
- end
601
- ```
602
-
603
- 3. finders now have extra capabilities:
604
-
605
- ```ruby
606
- Store.find(:all, :origin =>[32.951613,-96.958444], :within=>10)
607
- ```
608
-
609
- ## How to geocode an address
610
-
611
- 1. configure your geocoder key(s) in `config/initializers/geokit_config.rb`
612
-
613
- 2. also in `geokit_config.rb`, make sure that `Geokit::Geocoders::provider_order` reflects the
614
- geocoder(s). If you only want to use one geocoder, there should
615
- be only one symbol in the array. For example:
616
-
617
- ```ruby
618
- Geokit::Geocoders::provider_order=[:google]
619
- ```
620
-
621
- 3. Test it out in script/console
622
-
623
- ```ruby
624
- include Geokit::Geocoders
625
- res = MultiGeocoder.geocode('100 Spear St, San Francisco, CA')
626
- puts res.lat
627
- puts res.lng
628
- puts res.full_address
629
- ```
630
-
631
- ... etc. The return type is GeoLoc, see the API for
632
- all the methods you can call on it.
633
-
634
- ## How to find all stores within 10 miles of a given address
635
-
636
- 1. as above, ensure your table has the lat/lng columns, and you've
637
- applied `acts_as_mappable` to the Store model.
638
-
639
- 2. configure and test out your geocoder, as above
640
-
641
- 3. pass the address in under the :origin key
642
-
643
- ```ruby
644
- Store.find(:all, :origin=>'100 Spear st, San Francisco, CA', :within=>10)
645
- ```
646
-
647
- 4. you can also use a zipcode, or anything else that's geocodable:
648
-
649
- ```ruby
650
- Store.find(:all, :origin=>'94117', :conditions=>'distance<10')
651
- ```
652
-
653
- ## How to sort a query by distance from an origin
654
-
655
- You now have access to a 'distance' column, and you can use it
656
- as you would any other column. For example:
657
-
658
- ```ruby
659
- Store.find(:all, :origin=>'94117', :order=>'distance')
660
- ```
661
-
662
- ## How to sort elements of an array according to distance from a common point
663
-
664
- Usually, you can do your sorting in the database as part of your find call.
665
- If you need to sort things post-query, you can do so:
666
-
667
- ```ruby
668
- stores = Store.all
669
- stores.sort_by{|s| s.distance_to(home)}
670
- ```
671
-
672
- Obviously, each of the items in the array must have a latitude/longitude so
673
- they can be sorted by distance.
674
-
675
- ## Database indexes
676
-
677
- MySQL can't create indexes on a calculated field such as those Geokit uses to
678
- calculate distance based on latitude/longitude values for a record. However,
679
- indexing the lat and lng columns does improve Geokit distance calculation
680
- performance since the lat and lng columns are used in a straight comparison
681
- for distance calculation. Assuming a Page model that is incorporating the
682
- Geokit plugin the migration would be as follows.
683
-
684
- ```ruby
685
- class AddIndexToPageLatAndLng < ActiveRecord::Migration
686
-
687
- def self.up
688
- add_index :pages, [:lat, :lng]
689
- end
690
-
691
- def self.down
692
- remove_index :pages, [:lat, :lng]
693
- end
694
- end
695
- ```
696
-
697
- ## Database Compatability
698
-
699
- * Geokit works with MySQL (tested with version 5.0.41), PostgreSQL (tested with version 8.2.6) and Microsoft SQL Server (tested with 2000).
700
- * Geokit is known to *not* work with Postgres versions under 8.1 -- it uses the least() function.
701
-
702
-
703
- ## HIGH-LEVEL NOTES ON WHAT'S WHERE
704
-
705
- `acts_as_mappable.rb`, as you'd expect, contains the ActsAsMappable
706
- module which gets mixed into your models to provide the
707
- location-based finder goodness.
708
-
709
- `ip_geocode_lookup.rb` contains the before_action helper method which
710
- enables auto lookup of the requesting IP address.
711
-
712
- ### The Geokit gem provides the building blocks of distance-based operations:
713
-
714
- The Mappable module, which provides basic
715
- distance calculation methods, i.e., calculating the distance
716
- between two points.
717
-
718
- The LatLng class is a simple container for latitude and longitude, but
719
- it's made more powerful by mixing in the above-mentioned Mappable
720
- module -- therefore, you can calculate easily the distance between two
721
- LatLng objects with `distance = first.distance_to(other)`
722
-
723
- GeoLoc represents an address or location which
724
- has been geocoded. You can get the city, zipcode, street address, etc.
725
- from a GeoLoc object. GeoLoc extends LatLng, so you also get lat/lng
726
- AND the Mappable module goodness for free.
1
+ Geokit Rails
2
+ ============
3
+
4
+ [![Gem Version](https://badge.fury.io/rb/geokit-rails.svg)](http://badge.fury.io/rb/geokit-rails)
5
+ [![CI](https://github.com/geokit/geokit-rails/actions/workflows/ci.yml/badge.svg)](https://github.com/geokit/geokit-rails/actions/workflows/ci.yml)
6
+ [![Coverage Status](https://coveralls.io/repos/geokit/geokit-rails/badge.svg?branch=master)](https://coveralls.io/r/geokit/geokit-rails)
7
+ [![Code Climate](https://codeclimate.com/github/geokit/geokit-rails.svg)](https://codeclimate.com/github/geokit/geokit-rails)
8
+
9
+ ## COMMUNICATION
10
+
11
+ * If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/geokit). (Tag 'geokit' and we'll be alerted)
12
+ * If you **found a bug**, use GitHub issues.
13
+ * If you **have an idea**, use GitHub issues.
14
+ * If you'd like to **ask a general question**, use GitHub issues.
15
+ * If you **want to contribute**, submit a pull request.
16
+
17
+ ## INSTALLATION
18
+
19
+ Geokit for Rails consists of a generic Gem ([geokit](https://github.com/geokit/geokit)) and a Rails plugin ([geokit-rails](https://github.com/geokit/geokit-rails)).
20
+
21
+ Make sure you use a version >= 3.0 of Rails.
22
+
23
+ You just have to add the 'geokit-rails' gem to your Gemfile
24
+
25
+ ```ruby
26
+ gem 'geokit-rails'
27
+ ```
28
+
29
+ Then tell bundler to update the gems :
30
+
31
+ ```sh
32
+ $ bundle install
33
+ ```
34
+ Generate the configuration initializer:
35
+
36
+ ```sh
37
+ $ rails g geokit_rails:install
38
+ ```
39
+
40
+ Now, if you wish to use the various geocoding services, you can add your keys to the new initializer.
41
+
42
+
43
+
44
+ If you want to use geokit-rails in a Rails 2 application, just use the good old plugin ([geokit-rails](https://github.com/andre/geokit-rails)).
45
+
46
+
47
+ ## FEATURE SUMMARY
48
+
49
+ Geokit provides key functionality for location-oriented Rails applications:
50
+
51
+ - Distance calculations, for both flat and spherical environments. For example,
52
+ given the location of two points on the earth, you can calculate the miles/Km
53
+ between them.
54
+ - ActiveRecord distance-based finders. For example, you can find all the points
55
+ in your database within a 50-mile radius.
56
+ - IP-based location lookup utilizing hostip.info. Provide an IP address, and get
57
+ city name and latitude/longitude in return
58
+ - A before_action helper to geocoder the user's location based on IP address,
59
+ and retain the location in a cookie.
60
+ - Geocoding from multiple providers. It provides a fail-over mechanism, in case
61
+ your input fails to geocode in one service. Geocoding is provided by the Geokit
62
+ gem, which you must have installed
63
+
64
+ The goal of this plugin is to provide the common functionality for location-oriented
65
+ applications (geocoding, location lookup, distance calculation) in an easy-to-use
66
+ package.
67
+
68
+ ## A NOTE ON TERMINOLOGY
69
+
70
+ Throughout the code and API, _latitude_ and _longitude_ are referred to as _lat_
71
+ and _lng_. We've found over the long term the abbreviation saves lots of typing time.
72
+
73
+ ## LOCATION QUERIES
74
+
75
+ ### MAKING A MODEL MAPPABLE
76
+
77
+ To get started, just specify an ActiveRecord class as `acts_as_mappable`:
78
+
79
+ ```ruby
80
+ class Location < ActiveRecord::Base
81
+ acts_as_mappable
82
+ end
83
+ ```
84
+
85
+ There are some defaults you can override:
86
+
87
+ ```ruby
88
+ class Location < ActiveRecord::Base
89
+ acts_as_mappable :default_units => :miles,
90
+ :default_formula => :sphere,
91
+ :distance_field_name => :distance,
92
+ :lat_column_name => :lat,
93
+ :lng_column_name => :lng
94
+ end
95
+ ```
96
+
97
+ The optional parameters are `units`, `formula`, and `distance_field_name`.
98
+ Values for **units** can be `:miles`, `:kms` (kilometers), or `:nms` (nautical miles),
99
+ with `:miles` as the default.
100
+ Values for **formula** can be `:sphere` or `:flat` with `:sphere` as the default.
101
+ `:sphere` gives you Haversine calculations, while `:flat` gives the Pythagoreum Theory.
102
+ These defaults persist through out the gem.
103
+
104
+ The plug-in creates a calculated `distance` field on AR instances that have
105
+ been retrieved through a Geokit location query. By default, these fields are
106
+ known as "distance" but this can be changed through the `:distance_field_name` key.
107
+
108
+ You can also define alternative column names for latitude and longitude using
109
+ the `:lat_column_name` and `:lng_column_name` keys. The defaults are `lat` and
110
+ `lng` respectively.
111
+
112
+ ### NEW SCOPES TO USE
113
+
114
+ Once you've specified `acts_as_mappable`, a few scopes are available :
115
+
116
+ * `within` and `beyond` find records within or beyond a certain distance from the origin point.
117
+ * `in_range` finds records within a certain distance range from the origin point.
118
+ * `in_bounds` finds records within a rectangle on the map
119
+ * `closest` and `farthest` find the closest or farthest record from the origin point
120
+ * `by_distance` finds records ordered by distance from the origin point
121
+
122
+ All of these scopes take a hash of options where the first parameter is simply
123
+ one of the possible options, without the name.
124
+
125
+ A few examples :
126
+
127
+ ```ruby
128
+ Location.within(5, :origin => @somewhere)
129
+ ```
130
+
131
+ ```ruby
132
+ Location.in_range(2..5, :origin => @somewhere)
133
+ ```
134
+
135
+ ```ruby
136
+ Location.in_bounds([@south_west_point, @north_east_point], :origin => @somewhere)
137
+ ```
138
+
139
+ The options can be :
140
+
141
+ `:origin` as a two-element array of latitude/longitude:
142
+
143
+ ```ruby
144
+ Location.by_distance(:origin => [37.792,-122.393])
145
+ ```
146
+
147
+ `:origin` as a geocodeable string:
148
+
149
+ ```ruby
150
+ Location.by_distance(:origin => '100 Spear st, San Francisco, CA')
151
+ ```
152
+
153
+ `:origin` as an object which responds to `lat` and `lng` methods,
154
+ or `latitude` and `longitude` methods, or whatever methods you have
155
+ specified for `lng_column_name` and `lat_column_name`:
156
+
157
+ ```ruby
158
+ Location.geo_scope(:origin => my_store)
159
+ # my_store.lat and my_store.lng methods exist
160
+ ```
161
+
162
+ `:units` or `:formula` can be used to override the default values in a specific query
163
+
164
+ ```ruby
165
+ Location.within(5, :units => :kms, :origin => @somewhere)
166
+ # it will get the records within 5 kilometers instead of 5 miles
167
+ ```
168
+
169
+ `:range` as a native Ruby range
170
+
171
+ `:bounds` as an array of two elements : the south/west point and the north/east point.
172
+
173
+ ```ruby
174
+ @sw = Geokit::LatLng.new(32.91663,-96.982841)
175
+ @ne = Geokit::LatLng.new(32.96302,-96.919495)
176
+ @somewhere = Location.find(123456)
177
+ Location.within(:bounds => [@sw, @ne], :origin => @somewhere)
178
+ ```
179
+
180
+ `:bounds` as a Geokit::Bounds object
181
+
182
+ ```ruby
183
+ @bounds = Geokit::Bounds.new([32.91663,-96.982841], [32.96302,-96.919495])
184
+ @somewhere = Location.find(123456)
185
+ Location.within(:bounds => [@sw, @ne], :origin => @somewhere)
186
+ ```
187
+
188
+ When using a point of reference or bounds, you leverage the power of Geokit
189
+ to build this objects. Basically, if Geokit can make a Geokit::Point
190
+ or a Geokit::Bounds with what you give to it, you're good to go.
191
+
192
+ ### FIND BY SQL
193
+
194
+ Finally, if all that is desired is the raw SQL for distance
195
+ calculations, you can use the following:
196
+
197
+ ```ruby
198
+ Location.distance_sql(origin, units = default_units, formula = default_formula)
199
+ ```
200
+
201
+ Thereafter, you are free to use it in `find_by_sql` as you wish.
202
+
203
+ ### CHAINABILITY
204
+
205
+ You can then chain these scope with any other or use a "calling" method like `first`, `all`, `count`, …
206
+
207
+ ```ruby
208
+ Location.within(5, :origin => @somewhere).all
209
+ Location.within(5, :origin => @somewhere).count
210
+ Location.by_distance(:origin => [37.792,-122.393]).first
211
+ ```
212
+
213
+ You can add `order` clauses in the chain as for any ActiveRecord query
214
+
215
+ ```ruby
216
+ Location.within(5, :origin => @somewhere).order('nbr_seats ASC')
217
+ ```
218
+
219
+ You can even sort by distance (use the same name as specified in the model class)
220
+
221
+ ```ruby
222
+ Location.within(5, :origin => @somewhere).order('distance DESC, nbr_seats ASC')
223
+ ```
224
+
225
+ Idem for the `limit` clause. In fact, `closest` and `farthest` are defined like this :
226
+
227
+ ```ruby
228
+ def closest(options = {})
229
+ by_distance(options).limit(1)
230
+ end
231
+ def farthest(options = {})
232
+ by_distance({:reverse => true}.merge(options)).limit(1)
233
+ end
234
+ ```
235
+
236
+ #### Important caveat
237
+
238
+ In the current version of geokit-rails, it is not possible to add a `where` clause
239
+ using the _distance_ column. I've tried many different ways to do this and didn't get it working.
240
+
241
+ One would expect to build a query like this :
242
+
243
+ ```ruby
244
+ scoped = Location.by_distance(:origin => @somewhere)
245
+ scoped = scoped.where('distance <= 5')
246
+ results = scoped.all
247
+ ```
248
+
249
+ This is not possible right now, it must be done in a single step like this :
250
+
251
+ ```ruby
252
+ scoped = Location.within(5, :origin => @somewhere)
253
+ results = scoped.all
254
+ ```
255
+
256
+ Every good idea that would help achieve this is very much welcome.
257
+
258
+ ### FINDING WITHIN A BOUNDING BOX
259
+
260
+ If you are displaying points on a map, you probably need to query for whatever falls within the rectangular bounds of the map:
261
+
262
+ ```ruby
263
+ Store.in_bounds([sw_point,ne_point]).all
264
+ ```
265
+
266
+ If you want the query to return things that are located on the rectangular bounds, specify the `inclusive` option set to true:
267
+
268
+ ```ruby
269
+ Store.in_bounds([sw_point,ne_point], :inclusive => true).all
270
+ ```
271
+
272
+ The input to `bounds` can be an array with the two points or a Bounds object. However you provide them, the order should always be the southwest corner, northeast corner of the rectangle. Typically, you will be getting the sw\_point and ne\_point from a map that is displayed on a web page.
273
+
274
+ If you need to calculate the bounding box from a point and radius, you can do that:
275
+
276
+ ```ruby
277
+ bounds = Geokit::Bounds.from_point_and_radius(home,5)
278
+ Store.in_bounds(bounds).all
279
+ ```
280
+
281
+ ----
282
+
283
+ # What is following is from the previous _geokit-rails_ plugin.
284
+
285
+ > **It has not been tested with Rails 3 nor with this version of the gem.**
286
+ **Most of it should work, but it is not sure**
287
+
288
+
289
+ ## USING INCLUDES
290
+
291
+ You can use includes along with your distance finders:
292
+
293
+ ```ruby
294
+ stores = Store.within(5, :origin=>home).includes([:reviews,:cities]).order('distance asc').all
295
+ ```
296
+
297
+ *However*, ActiveRecord drops the calculated distance column when you use include. So, if you need to use the distance column, you'll have to re-calculate it post-query in Ruby:
298
+
299
+ ```ruby
300
+ stores.sort_by{|s| s.distance_to(home)}
301
+ ```
302
+
303
+ In this case, you may want to just use the bounding box condition alone in your SQL (there's no use calculating the distance twice):
304
+
305
+ ```ruby
306
+ bounds=Geokit::Bounds.from_point_and_radius(home,5)
307
+ stores=Store.includes([:reviews,:cities]).in_bounds(bounds)
308
+ stores.sort_by{|s| s.distance_to(home)}
309
+ ```
310
+
311
+ ## USING :through
312
+
313
+ You can also specify a model as mappable "through" another associated model. In other words, that associated model is the actual mappable model with "lat" and "lng" attributes, but this "through" model can still utilize all of the above find methods to search for records.
314
+
315
+ ```ruby
316
+ class Location < ActiveRecord::Base
317
+ belongs_to :locatable, :polymorphic => true
318
+ acts_as_mappable
319
+ end
320
+ ```
321
+
322
+ ```ruby
323
+ class Company < ActiveRecord::Base
324
+ has_one :location, :as => :locatable # also works for belongs_to associations
325
+ acts_as_mappable :through => :location
326
+ end
327
+ ```
328
+
329
+ Then you can still call:
330
+
331
+ ```ruby
332
+ Company.within(distance, :origin => @somewhere)
333
+ ```
334
+
335
+ You can also give :through a hash if your location is nested deep. For example, given:
336
+
337
+ ```ruby
338
+ class House
339
+ acts_as_mappable
340
+ end
341
+ ```
342
+
343
+ ```ruby
344
+ class Family
345
+ belongs_to :house
346
+ end
347
+ ```
348
+
349
+ ```ruby
350
+ class Person
351
+ belongs_to :family
352
+ acts_as_mappable :through => { :family => :house }
353
+ end
354
+ ```
355
+
356
+ Remember that the notes above about USING INCLUDES apply to the results from
357
+ this find, since an include is automatically used.
358
+
359
+ ## IP GEOCODING
360
+
361
+ You can obtain the location for an IP at any time using the geocoder
362
+ as in the following example:
363
+
364
+ ```ruby
365
+ location = IpGeocoder.geocode('12.215.42.19')
366
+ ```
367
+
368
+ where Location is a GeoLoc instance containing the latitude,
369
+ longitude, city, state, and country code. Also, the success
370
+ value is true.
371
+
372
+ If the IP cannot be geocoded, a GeoLoc instance is returned with a
373
+ success value of false.
374
+
375
+ It should be noted that the IP address needs to be visible to the
376
+ Rails application. In other words, you need to ensure that the
377
+ requesting IP address is forwarded by any front-end servers that
378
+ are out in front of the Rails app. Otherwise, the IP will always
379
+ be that of the front-end server.
380
+
381
+ The Multi-Geocoder will also geocode IP addresses and provide
382
+ failover among multiple IP geocoders. Just pass in an IP address for the
383
+ parameter instead of a street address. Eg:
384
+
385
+ ```ruby
386
+ location = Geocoders::MultiGeocoder.geocode('12.215.42.19')
387
+ ```
388
+
389
+ The MultiGeocoder class requires 2 configuration setting for the provider order.
390
+ Ordering is done through `Geokit::Geocoders::provider_order` and
391
+ `Geokit::Geocoders::ip_provider_order`, found in
392
+ `config/initializers/geokit_config.rb`. If you don't already have a
393
+ `geokit_config.rb` file, the plugin creates one when it is first installed.
394
+
395
+
396
+ ## IP GEOCODING HELPER
397
+
398
+ A class method called geocode_ip_address has been mixed into the
399
+ ActionController::Base. This enables before_action style lookup of
400
+ the IP address. Since it is a filter, it can accept any of the
401
+ available filter options.
402
+
403
+ Usage is as below:
404
+
405
+ ```ruby
406
+ class LocationAwareController < ActionController::Base
407
+ geocode_ip_address
408
+ end
409
+ ```
410
+
411
+ A first-time lookup will result in the GeoLoc class being stored
412
+ in the session as `:geo_location` as well as in a cookie called
413
+ `:geo_session`. Subsequent lookups will use the session value if it
414
+ exists or the cookie value if it doesn't exist. The last resort is
415
+ to make a call to the web service. Clients are free to manage the
416
+ cookie as they wish.
417
+
418
+ The intent of this feature is to be able to provide a good guess as
419
+ to a new visitor's location.
420
+
421
+ ## INTEGRATED FIND AND GEOCODING
422
+
423
+ Geocoding has been integrated with the finders enabling you to pass
424
+ a physical address or an IP address. This would look the following:
425
+
426
+ ```ruby
427
+ Location.farthest(:origin => '217.15.10.9')
428
+ Location.farthest(:origin => 'Irving, TX')
429
+ ```
430
+
431
+ where the IP or physical address would be geocoded to a location and
432
+ then the resulting latitude and longitude coordinates would be used
433
+ in the find. This is not expected to be common usage, but it can be
434
+ done nevertheless.
435
+
436
+ ## ADDRESS GEOCODING
437
+
438
+ Geocoding is provided by the Geokit gem, which is required for this plugin.
439
+ See the top of this file for instructions on installing the Geokit gem.
440
+
441
+ Geokit can geocode addresses using multiple geocodeing web services.
442
+ Geokit supports services like Google, Yahoo, and Geocoder.us, and more --
443
+ see the Geokit gem API for a complete list.
444
+
445
+ These geocoder services are made available through the following classes:
446
+ GoogleGeocoder, YahooGeocoder, UsGeocoder, CaGeocoder, and GeonamesGeocoder.
447
+ Further, an additional geocoder class called MultiGeocoder incorporates an ordered failover
448
+ sequence to increase the probability of successful geocoding.
449
+
450
+ All classes are called using the following signature:
451
+
452
+ ```ruby
453
+ include Geokit::Geocoders
454
+ location = XxxGeocoder.geocode(address)
455
+ ```
456
+
457
+ where you replace Xxx Geocoder with the appropriate class. A GeoLoc
458
+ instance is the result of the call. This class has a "success"
459
+ attribute which will be true if a successful geocoding occurred.
460
+ If successful, the lat and lng properties will be populated.
461
+
462
+ Geocoders are named with the convention NameGeocoder. This
463
+ naming convention enables Geocoder to auto-detect its sub-classes
464
+ in order to create methods called `name_geocoder(address)` so that
465
+ all geocoders can be called through the base class. This is done
466
+ purely for convenience; the individual geocoder classes are expected
467
+ to be used independently.
468
+
469
+ The MultiGeocoder class requires the configuration of a provider
470
+ order which dictates what order to use the various geocoders. Ordering
471
+ is done through `Geokit::Geocoders::provider_order`, found in
472
+ `config/initializers/geokit_config.rb`.
473
+
474
+ If you don't already have a `geokit_config.rb` file, the plugin creates one
475
+ when it is first installed.
476
+
477
+ Make sure your failover configuration matches the usage characteristics
478
+ of your application -- for example, if you routinely get bogus input to
479
+ geocode, your code will be much slower if you have to failover among
480
+ multiple geocoders before determining that the input was in fact bogus.
481
+
482
+ The Geocoder.geocode method returns a GeoLoc object. Basic usage:
483
+
484
+ ```ruby
485
+ loc=Geocoder.geocode('100 Spear St, San Francisco, CA')
486
+ if loc.success
487
+ puts loc.lat
488
+ puts loc.lng
489
+ puts loc.full_address
490
+ end
491
+ ```
492
+
493
+ ## REVERSE GEOCODING
494
+
495
+ Currently, only the Google Geocoder supports reverse geocoding.
496
+ Pass the lat/lng as a string, array or LatLng instance:
497
+
498
+ ```ruby
499
+ res=Geokit::Geocoders::GoogleGeocoder.reverse_geocode "37.791821,-122.394679"
500
+ # => #<Geokit::GeoLoc:0x558ed0 ...
501
+ res.full_address
502
+ # => "101-115 Main St, San Francisco, CA 94105, USA"
503
+ ```
504
+
505
+ The address will usually appear as a range, as it does in the above example.
506
+
507
+
508
+ ## INTEGRATED FIND WITH ADDRESS GEOCODING
509
+
510
+ Just has you can pass an IP address directly into an ActiveRecord finder
511
+ as the origin, you can also pass a physical address as the origin:
512
+
513
+ ```ruby
514
+ Location.closest(:origin => '100 Spear st, San Francisco, CA')
515
+ ```
516
+
517
+ where the physical address would be geocoded to a location and then the
518
+ resulting latitude and longitude coordinates would be used in the
519
+ find.
520
+
521
+ Note that if the address fails to geocode, the find method will raise an
522
+ ActiveRecord::GeocodeError you must be prepared to catch. Alternatively,
523
+ You can geocoder the address beforehand, and pass the resulting lat/lng
524
+ into the finder if successful.
525
+
526
+ ## Auto Geocoding
527
+
528
+ If your geocoding needs are simple, you can tell your model to automatically
529
+ geocode itself on create:
530
+
531
+ ```ruby
532
+ class Store < ActiveRecord::Base
533
+ acts_as_mappable :auto_geocode=>true
534
+ end
535
+ ```
536
+
537
+ It takes two optional params:
538
+
539
+ ```ruby
540
+ class Store < ActiveRecord::Base
541
+ acts_as_mappable :auto_geocode=>{:field=>:address, :error_message=>'Could not geocode address'}
542
+ end
543
+ ```
544
+
545
+ . . . which is equivalent to:
546
+
547
+ ```ruby
548
+ class Store << ActiveRecord::Base
549
+ acts_as_mappable
550
+ before_validation :geocode_address, :on => :create
551
+
552
+ private
553
+ def geocode_address
554
+ geo=Geokit::Geocoders::MultiGeocoder.geocode (address)
555
+ errors.add(:address, "Could not Geocode address") if !geo.success
556
+ self.lat, self.lng = geo.lat,geo.lng if geo.success
557
+ end
558
+ end
559
+ ```
560
+
561
+ If you need any more complicated geocoding behavior for your model, you should roll your own
562
+ `before_validate` callback.
563
+
564
+
565
+ ## Distances, headings, endpoints, and midpoints
566
+
567
+ ```ruby
568
+ distance = home.distance_from(work, :units=>:miles)
569
+ heading = home.heading_to(work) # result is in degrees, 0 is north
570
+ endpoint = home.endpoint(90,2) # two miles due east
571
+ midpoint = home.midpoint_to(work)
572
+ ```
573
+
574
+ ## Cool stuff you can do with bounds
575
+
576
+ ```ruby
577
+ bounds = Bounds.new(sw_point,ne_point)
578
+ bounds.contains?(home)
579
+ puts bounds.center
580
+ ```
581
+
582
+ HOW TO . . .
583
+ =================================================================================
584
+
585
+ A few quick examples to get you started ....
586
+
587
+ ## How to install the Geokit Rails plugin
588
+ (See the very top of this file)
589
+
590
+ ## How to find all stores within a 10-mile radius of a given lat/lng
591
+ 1. ensure your stores table has lat and lng columns with numeric or float
592
+ datatypes to store your latitude/longitude
593
+
594
+ 2. use `acts_as_mappable` on your store model:
595
+ 3.
596
+ ```ruby
597
+ class Store < ActiveRecord::Base
598
+ acts_as_mappable
599
+ ...
600
+ end
601
+ ```
602
+
603
+ 3. finders now have extra capabilities:
604
+
605
+ ```ruby
606
+ Store.find(:all, :origin =>[32.951613,-96.958444], :within=>10)
607
+ ```
608
+
609
+ ## How to geocode an address
610
+
611
+ 1. configure your geocoder key(s) in `config/initializers/geokit_config.rb`
612
+
613
+ 2. also in `geokit_config.rb`, make sure that `Geokit::Geocoders::provider_order` reflects the
614
+ geocoder(s). If you only want to use one geocoder, there should
615
+ be only one symbol in the array. For example:
616
+
617
+ ```ruby
618
+ Geokit::Geocoders::provider_order=[:google]
619
+ ```
620
+
621
+ 3. Test it out in script/console
622
+
623
+ ```ruby
624
+ include Geokit::Geocoders
625
+ res = MultiGeocoder.geocode('100 Spear St, San Francisco, CA')
626
+ puts res.lat
627
+ puts res.lng
628
+ puts res.full_address
629
+ ```
630
+
631
+ ... etc. The return type is GeoLoc, see the API for
632
+ all the methods you can call on it.
633
+
634
+ ## How to find all stores within 10 miles of a given address
635
+
636
+ 1. as above, ensure your table has the lat/lng columns, and you've
637
+ applied `acts_as_mappable` to the Store model.
638
+
639
+ 2. configure and test out your geocoder, as above
640
+
641
+ 3. pass the address in under the :origin key
642
+
643
+ ```ruby
644
+ Store.find(:all, :origin=>'100 Spear st, San Francisco, CA', :within=>10)
645
+ ```
646
+
647
+ 4. you can also use a zipcode, or anything else that's geocodable:
648
+
649
+ ```ruby
650
+ Store.find(:all, :origin=>'94117', :conditions=>'distance<10')
651
+ ```
652
+
653
+ ## How to sort a query by distance from an origin
654
+
655
+ You now have access to a 'distance' column, and you can use it
656
+ as you would any other column. For example:
657
+
658
+ ```ruby
659
+ Store.find(:all, :origin=>'94117', :order=>'distance')
660
+ ```
661
+
662
+ ## How to sort elements of an array according to distance from a common point
663
+
664
+ Usually, you can do your sorting in the database as part of your find call.
665
+ If you need to sort things post-query, you can do so:
666
+
667
+ ```ruby
668
+ stores = Store.all
669
+ stores.sort_by{|s| s.distance_to(home)}
670
+ ```
671
+
672
+ Obviously, each of the items in the array must have a latitude/longitude so
673
+ they can be sorted by distance.
674
+
675
+ ## Database indexes
676
+
677
+ MySQL can't create indexes on a calculated field such as those Geokit uses to
678
+ calculate distance based on latitude/longitude values for a record. However,
679
+ indexing the lat and lng columns does improve Geokit distance calculation
680
+ performance since the lat and lng columns are used in a straight comparison
681
+ for distance calculation. Assuming a Page model that is incorporating the
682
+ Geokit plugin the migration would be as follows.
683
+
684
+ ```ruby
685
+ class AddIndexToPageLatAndLng < ActiveRecord::Migration
686
+
687
+ def self.up
688
+ add_index :pages, [:lat, :lng]
689
+ end
690
+
691
+ def self.down
692
+ remove_index :pages, [:lat, :lng]
693
+ end
694
+ end
695
+ ```
696
+
697
+ ## Database Compatability
698
+
699
+ * Geokit works with MySQL, PostgreSQL, SQLite and Microsoft SQL Server. The test suite runs against SQLite and MySQL 8.4.
700
+ * Geokit is known to *not* work with Postgres versions under 8.1 -- it uses the least() function.
701
+
702
+
703
+ ## HIGH-LEVEL NOTES ON WHAT'S WHERE
704
+
705
+ `acts_as_mappable.rb`, as you'd expect, contains the ActsAsMappable
706
+ module which gets mixed into your models to provide the
707
+ location-based finder goodness.
708
+
709
+ `ip_geocode_lookup.rb` contains the before_action helper method which
710
+ enables auto lookup of the requesting IP address.
711
+
712
+ ### The Geokit gem provides the building blocks of distance-based operations:
713
+
714
+ The Mappable module, which provides basic
715
+ distance calculation methods, i.e., calculating the distance
716
+ between two points.
717
+
718
+ The LatLng class is a simple container for latitude and longitude, but
719
+ it's made more powerful by mixing in the above-mentioned Mappable
720
+ module -- therefore, you can calculate easily the distance between two
721
+ LatLng objects with `distance = first.distance_to(other)`
722
+
723
+ GeoLoc represents an address or location which
724
+ has been geocoded. You can get the city, zipcode, street address, etc.
725
+ from a GeoLoc object. GeoLoc extends LatLng, so you also get lat/lng
726
+ AND the Mappable module goodness for free.