geokit-rails 2.0.1 → 2.1.0

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

Potentially problematic release.


This version of geokit-rails might be problematic. Click here for more details.

checksums.yaml CHANGED
@@ -1,15 +1,7 @@
1
1
  ---
2
- !binary "U0hBMQ==":
3
- metadata.gz: !binary |-
4
- MjQ2ZjFiYzY3ZGE3M2Y3N2Q0YWVkM2Q2ZjdmMGZhNDllZWE1YzY4MA==
5
- data.tar.gz: !binary |-
6
- OGI2ZDcxN2QzMWMzNWM0YzIxMzYxYTlkYmYyNDU3MjE5MWM5MmY1Yg==
7
- !binary "U0hBNTEy":
8
- metadata.gz: !binary |-
9
- Yzk2Yjc2ODE2NzU3NmQ2OWRjMWIxOGQ5NmVkODUxZmY5MzlhNzkxMjM2MGFm
10
- Mjg0ODY3NzBiNDdjMWIxODZkM2E4NWYzZDliYmI1NmJlNzA1Y2ExNjM5ZmZl
11
- OWE3N2ZkN2ViYWNmYzU4NmU2NWQ4MjVjYzI1MjdiYzViZTNlNTY=
12
- data.tar.gz: !binary |-
13
- ZGI0ZTBmMTYyZGU0MDA0MTZmYmJmMzYyMjY2OTJjNjQzMmI5YmVmNWZkMTg4
14
- ZDQwODU5OWMzNGJkNWVlMWJiOWU2NDkwYmEwYTI1NmQ5YTQ2ZDQ0YmMxNGVh
15
- ODRhMDMxNDAyYzljNThkZWEzMmJlYjljNzc2ZjU5NWM5ODE0M2U=
2
+ SHA1:
3
+ metadata.gz: 344c3a01e104ef0d6b79be9cebe2ad8c1a2ca194
4
+ data.tar.gz: 96b07a5c6ca0940aef6b3c1f659aae5b1e0fc36b
5
+ SHA512:
6
+ metadata.gz: 2cdc20079f29590779baea71816ab3e64cd55f58bfb95bc930118a09a40aec9f8d7a12dc6e876f53bcbaf62241f0ea18868ef260a15e8a6cee8f5b9740c4e09d
7
+ data.tar.gz: db71e76adac5e6ff9269c02926d9f053603874ff61ca87a404df80b9aabf4617fc94b2a189d3c96b8379f2eb15510bbd95312709fbfecc5d6dfa896bd0b0f30d
@@ -0,0 +1,37 @@
1
+ # Bundler
2
+ # http://yehudakatz.com/2010/12/16/clarifying-the-roles-of-the-gemspec-and-gemfile/
3
+ Gemfile.lock
4
+
5
+ # Test log files
6
+ test/*-debug.log
7
+
8
+ # SQLite Test DB
9
+ test/test.sqlite3
10
+
11
+ # SVN
12
+ .svn
13
+
14
+ # RVM
15
+ .rvmrc
16
+
17
+ # TextMate
18
+ *.tmproj
19
+
20
+ # rcov generated
21
+ coverage
22
+
23
+ # rdoc generated
24
+ rdoc
25
+
26
+ # yard generated
27
+ doc
28
+ .yardoc
29
+
30
+ # bundler
31
+ .bundle
32
+
33
+ # builds
34
+ *.gem
35
+
36
+ # For MacOS:
37
+ .DS_Store
@@ -0,0 +1,19 @@
1
+ language: ruby
2
+ rvm:
3
+ - 1.9
4
+ - 2.0
5
+ - 2.1
6
+ - 2.2
7
+ gemfile:
8
+ - gemfiles/rails3.gemfile
9
+ - gemfiles/rails4.gemfile
10
+ matrix:
11
+ exclude:
12
+ - rvm: 1.9
13
+ gemfile: gemfiles/rails4.gemfile
14
+ - rvm: 2.2
15
+ gemfile: gemfiles/rails3.gemfile
16
+ script: "bundle exec rake coverage"
17
+ before_install:
18
+ - gem install bundler
19
+
@@ -0,0 +1,64 @@
1
+ ## 2.0.1
2
+
3
+ * Fix GeoKit naming compatibility
4
+
5
+ ## 2.0.0 / 2013-06-19
6
+
7
+ * Integrated geokit-rails3 into geokit-rails (use 1.x for rails2 support)
8
+
9
+ ## 1.2.0 / 2009-10-02
10
+
11
+ * Overhaul the test suite to be independent of a Rails project
12
+ * Added concept of database adapter. Ported mysql/postgresql conditional code to their own adapter.
13
+ * Added SQL Server support. THANKS http://github.com/brennandunn for all the improvements in this release
14
+
15
+ ## 1.1.3 / 2009-09-26
16
+
17
+ * documentation updates and updated to work with Geokit gem v1.5.0
18
+ * IMPORTANT: in the Geokit gem, Geokit::Geocoders::timeout became Geokit::Geocoders::request_timeout for jruby compatibility.
19
+ The plugin sets this in config/initializers/geokit_config.rb. So if you've upgraded the gem to 1.5.0, you need to
20
+ make the change manually from Geokit::Geocoders::timeout to Geokit::Geocoders::request_timeout in config/initializers/geokit_config.rb
21
+
22
+ ## 1.1.2 / 2009-06-08
23
+
24
+ * Added support for hashes in :through. So you can do: acts_as_mappable :through => { :state => :country } (Thanks José Valim).
25
+
26
+ ## 1.1.1 / 2009-05-22
27
+ * Support for multiple ip geocoders (Thanks dreamcat4)
28
+ * Now checks if either :origin OR :bounds is passed, and proceeds with geokit query if this is true (Thanks Glenn Powell)
29
+ * Raises a helpful error if someone uses through but the association does not exists or was not defined yet (Thanks José Valim)
30
+
31
+ ## 1.1.0 / 2009-04-11
32
+
33
+ * Fixed :through usages so that the through model is only included in the query if there
34
+ is an :origin passed in (Only if it is a geokit search) (Thanks Glenn Powell)
35
+ * Move library initialisation into lib/geokit-rails. init.rb uses lib/geokit-rails now (thanks Alban Peignier)
36
+ * Handle the case where a user passes a hash to the :conditions Finder option (thanks Adam Greene)
37
+ * Added ability to specify domain-specific API keys (Thanks Glenn Powell)
38
+
39
+ ## 2009-02-20
40
+
41
+ * More powerful assosciations in the Rails Plugin:You can now specify a model as mappable "through" an associated model.
42
+ In other words, that associated model is the actual mappable model with "lat" and "lng" attributes, but this "through" model
43
+ can still utilize all Geokit's "find by distance" finders. Also Rails 2.3 compatibility (thanks github/glennpow)
44
+
45
+ ## 2008-12-18
46
+
47
+ * Split Rails plugin from geocoder gem
48
+ * updated for Rails 2.2.2
49
+
50
+ ## 2008-08-20
51
+
52
+ * Further fix of distance calculation, this time in SQL. Now uses least() function, which is available in MySQL version 3.22.5+ and postgres versions 8.1+
53
+
54
+ ## 2008-01-16
55
+
56
+ * fixed the "zero-distance" bug (calculating between two points that are the same)
57
+
58
+ ## 2007-11-12
59
+
60
+ * fixed a small but with queries crossing meridian, and also fixed find(:closest)
61
+
62
+ ## 2007-10-11
63
+
64
+ * Fixed Rails2/Edge compatability
@@ -0,0 +1,67 @@
1
+ # You can configure Geokit in your environment files
2
+
3
+ These defaults are used in `Geokit::Mappable.distance_to` and in `acts_as_mappable`
4
+
5
+ config.geokit.default_units = :miles
6
+ config.geokit.default_formula = :sphere
7
+
8
+ This is the timeout value in seconds to be used for calls to the geocoder web services. For no timeout at all, comment out the setting. The timeout unit is in seconds.
9
+
10
+ config.geokit.geocoders.request_timeout = 3
11
+
12
+ These settings are used if web service calls must be routed through a proxy.
13
+ These setting can be `nil` if not needed, otherwise, addr and port must be filled in at a minimum. If the proxy requires authentication, the username and password can be provided as well.
14
+
15
+ config.geokit.geocoders.proxy_addr = nil
16
+ config.geokit.geocoders.proxy_port = nil
17
+ config.geokit.geocoders.proxy_user = nil
18
+ config.geokit.geocoders.proxy_pass = nil
19
+
20
+ This is your yahoo application key for the Yahoo Geocoder.
21
+
22
+ See [http://developer.yahoo.com/faq/index.html#appid](http://developer.yahoo.com/faq/index.html#appid)
23
+ and [http://developer.yahoo.com/maps/rest/V1/geocode.html](http://developer.yahoo.com/maps/rest/V1/geocode.html)
24
+
25
+ config.geokit.geocoders.yahoo = 'REPLACE_WITH_YOUR_YAHOO_KEY'
26
+
27
+ This is your Google Maps geocoder key.
28
+
29
+ See [http://www.google.com/apis/maps/signup.html](http://www.google.com/apis/maps/signup.html)
30
+ and [http://www.google.com/apis/maps/documentation/#Geocoding_Examples](http://www.google.com/apis/maps/documentation/#Geocoding_Examples)
31
+
32
+ config.geokit.geocoders.google = 'REPLACE_WITH_YOUR_GOOGLE_KEY'
33
+
34
+ This is your username and password for **geocoder.us**.
35
+ To use the free service, the value can be set to `nil` or `false`.
36
+ For usage tied to an account, the value should be set to `username:password`.
37
+
38
+ See [http://geocoder.us](http://geocoder.us)
39
+ and [http://geocoder.us/user/signup](http://geocoder.us/user/signup)
40
+
41
+ config.geokit.geocoders.geocoder_us = false
42
+
43
+ This is your authorization key for **geocoder.ca**.
44
+ To use the free service, the value can be set to `nil` or `false`. For usage tied to an account, set the value to the key obtained from
45
+ **Geocoder.ca**.
46
+
47
+ See [http://geocoder.ca](http://geocoder.ca)
48
+ and [http://geocoder.ca/?register=1](http://geocoder.ca/?register=1)
49
+
50
+ config.geokit.geocoders.geocoder_ca = false
51
+
52
+ Add this to use a username with the Geonames geocoder
53
+
54
+ config.geokit.geocoders.geonames="REPLACE_WITH_YOUR_GEONAMES_USERNAME"
55
+
56
+ This is the order in which the geocoders are called in a failover scenario.
57
+ If you only want to use a single geocoder, put a single symbol in the array.
58
+ Valid symbols are `:google`, `:yahoo`, `:us`, and `:ca`.
59
+ Be aware that there are **Terms of Use** restrictions on how you can use the various geocoders. Make sure you read up on relevant **Terms of Use** for each geocoder you are going to use.
60
+
61
+ config.geokit.geocoders.provider_order = [:google,:us]
62
+
63
+ The IP provider order. Valid symbols are `:ip`, `:geo_plugin`.
64
+ As before, make sure you read up on relevant **Terms of Use** for each
65
+
66
+ config.geokit.geocoders.ip_provider_order = [:geo_plugin,:ip]
67
+
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2013 Michael Noack, James Cox, Bill Eisenhauer & Andre Lewis
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,729 @@
1
+ Geokit Rails
2
+ ============
3
+
4
+ [![Gem Version](https://badge.fury.io/rb/geokit-rails.png)](http://badge.fury.io/rb/geokit-rails)
5
+ [![Build Status](https://travis-ci.org/geokit/geokit-rails.png?branch=master)](https://travis-ci.org/geokit/geokit-rails)
6
+ [![Coverage Status](https://coveralls.io/repos/geokit/geokit-rails/badge.png)](https://coveralls.io/r/geokit/geokit-rails)
7
+ [![Dependency Status](https://gemnasium.com/geokit/geokit-rails.png?travis)](https://gemnasium.com/geokit/geokit-rails)
8
+ [![Code Climate](https://codeclimate.com/github/geokit/geokit-rails.png)](https://codeclimate.com/github/geokit/geokit-rails)
9
+
10
+ ## COMMUNICATION
11
+
12
+ * If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/geokit). (Tag 'geokit' and we'll be alerted)
13
+ * If you **found a bug**, use GitHub issues.
14
+ * If you **have an idea**, use GitHub issues.
15
+ * If you'd like to **ask a general question**, use GitHub issues.
16
+ * If you **want to contribute**, submit a pull request.
17
+
18
+ ## INSTALLATION
19
+
20
+ 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)).
21
+
22
+ Make sure you use a version >= 3.0 of Rails.
23
+
24
+ You just have to add the 'geokit-rails' gem to your Gemfile
25
+
26
+ ```ruby
27
+ gem 'geokit-rails'
28
+ ```
29
+
30
+ Then tell bundler to update the gems :
31
+
32
+ ```sh
33
+ $ bundle install
34
+ ```
35
+
36
+ Last, consult the `important post-installation notes` section at the end of this document.
37
+
38
+ 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)).
39
+
40
+
41
+ ## FEATURE SUMMARY
42
+
43
+ Geokit provides key functionality for location-oriented Rails applications:
44
+
45
+ - Distance calculations, for both flat and spherical environments. For example,
46
+ given the location of two points on the earth, you can calculate the miles/Km
47
+ between them.
48
+ - ActiveRecord distance-based finders. For example, you can find all the points
49
+ in your database within a 50-mile radius.
50
+ - IP-based location lookup utilizing hostip.info. Provide an IP address, and get
51
+ city name and latitude/longitude in return
52
+ - A before_filter helper to geocoder the user's location based on IP address,
53
+ and retain the location in a cookie.
54
+ - Geocoding from multiple providers. It provides a fail-over mechanism, in case
55
+ your input fails to geocode in one service. Geocoding is provided by the Geokit
56
+ gem, which you must have installed
57
+
58
+ The goal of this plugin is to provide the common functionality for location-oriented
59
+ applications (geocoding, location lookup, distance calculation) in an easy-to-use
60
+ package.
61
+
62
+ ## A NOTE ON TERMINOLOGY
63
+
64
+ Throughout the code and API, _latitude_ and _longitude_ are referred to as _lat_
65
+ and _lng_. We've found over the long term the abbreviation saves lots of typing time.
66
+
67
+ ## LOCATION QUERIES
68
+
69
+ ### MAKING A MODEL MAPPABLE
70
+
71
+ To get started, just specify an ActiveRecord class as `acts_as_mappable`:
72
+
73
+ ```ruby
74
+ class Location < ActiveRecord::Base
75
+ acts_as_mappable
76
+ end
77
+ ```
78
+
79
+ There are some defaults you can override:
80
+
81
+ ```ruby
82
+ class Location < ActiveRecord::Base
83
+ acts_as_mappable :default_units => :miles,
84
+ :default_formula => :sphere,
85
+ :distance_field_name => :distance,
86
+ :lat_column_name => :lat,
87
+ :lng_column_name => :lng
88
+ end
89
+ ```
90
+
91
+ The optional parameters are `units`, `formula`, and `distance_field_name`.
92
+ Values for **units** can be `:miles`, `:kms` (kilometers), or `:nms` (nautical miles),
93
+ with `:miles` as the default.
94
+ Values for **formula** can be `:sphere` or `:flat` with `:sphere` as the default.
95
+ `:sphere` gives you Haversine calculations, while `:flat` gives the Pythagoreum Theory.
96
+ These defaults persist through out the gem.
97
+
98
+ The plug-in creates a calculated `distance` field on AR instances that have
99
+ been retrieved through a Geokit location query. By default, these fields are
100
+ known as "distance" but this can be changed through the `:distance_field_name` key.
101
+
102
+ You can also define alternative column names for latitude and longitude using
103
+ the `:lat_column_name` and `:lng_column_name` keys. The defaults are `lat` and
104
+ `lng` respectively.
105
+
106
+ ### NEW SCOPES TO USE
107
+
108
+ Once you've specified `acts_as_mappable`, a few scopes are available :
109
+
110
+ * `within` and `beyond` find records within or beyond a certain distance from the origin point.
111
+ * `in_range` finds records within a certain distance range from the origin point.
112
+ * `in_bounds` finds records within a rectangle on the map
113
+ * `closest` and `farthest` find the closest or farthest record from the origin point
114
+ * `by_distance` finds records ordered by distance from the origin point
115
+
116
+ All these scopes are the porcelain for a lower level scope named `geo_scope` that take a hash of options.
117
+ Their first parameter is simply one of the possible options, without the name
118
+
119
+ A few examples :
120
+
121
+ ```ruby
122
+ Location.within(5, :origin => @somewhere)
123
+ # is the same as
124
+ Location.geo_scope(:within => 5, :origin => @somewhere)
125
+ ```
126
+
127
+ ```ruby
128
+ Location.in_range(2..5, :origin => @somewhere)
129
+ # is the same as
130
+ Location.geo_scope(:range => 2..5, :origin => @somewhere)
131
+ ```
132
+
133
+ ```ruby
134
+ Location.in_bounds([@south_west_point, @north_east_point], :origin => @somewhere)
135
+ # is the same as
136
+ Location.geo_scope(: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.geo_scope(:origin => [37.792,-122.393])
145
+ ```
146
+
147
+ `:origin` as a geocodeable string:
148
+
149
+ ```ruby
150
+ Location.geo_scope(: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.geo_scope(: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.geo_scope(: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.geo_scope(: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
+ geo_scope(options).order("#{distance_column_name} asc").limit(1)
230
+ end
231
+ def farthest(options = {})
232
+ geo_scope(options).order("#{distance_column_name} desc").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.geo_scope(: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
+ 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.
267
+
268
+ If you need to calculate the bounding box from a point and radius, you can do that:
269
+
270
+ ```ruby
271
+ bounds = Geokit::Bounds.from_point_and_radius(home,5)
272
+ Store.in_bounds(bounds).all
273
+ ```
274
+
275
+ ----
276
+
277
+ # What is following is from the previous _geokit-rails_ plugin.
278
+
279
+ > **It has not been tested with Rails 3 nor with this version of the gem.**
280
+ **Most of it should work, but it is not sure**
281
+
282
+
283
+ ## USING INCLUDES
284
+
285
+ You can use includes along with your distance finders:
286
+
287
+ ```ruby
288
+ stores = Store.within(5, :origin=>home).includes([:reviews,:cities]).order('distance asc').all
289
+ ```
290
+
291
+ *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:
292
+
293
+ ```ruby
294
+ stores.sort_by{|s| s.distance_to(home)}
295
+ ```
296
+
297
+ 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):
298
+
299
+ ```ruby
300
+ bounds=Geokit::Bounds.from_point_and_radius(home,5)
301
+ stores=Store.includes([:reviews,:cities]).in_bounds(bounds)
302
+ stores.sort_by{|s| s.distance_to(home)}
303
+ ```
304
+
305
+ ## USING :through
306
+
307
+ 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.
308
+
309
+ ```ruby
310
+ class Location < ActiveRecord::Base
311
+ belongs_to :locatable, :polymorphic => true
312
+ acts_as_mappable
313
+ end
314
+ ```
315
+
316
+ ```ruby
317
+ class Company < ActiveRecord::Base
318
+ has_one :location, :as => :locatable # also works for belongs_to associations
319
+ acts_as_mappable :through => :location
320
+ end
321
+ ```
322
+
323
+ Then you can still call:
324
+
325
+ ```ruby
326
+ Company.within(distance, :origin => @somewhere)
327
+ ```
328
+
329
+ You can also give :through a hash if your location is nested deep. For example, given:
330
+
331
+ ```ruby
332
+ class House
333
+ acts_as_mappable
334
+ end
335
+ ```
336
+
337
+ ```ruby
338
+ class Family
339
+ belongs_to :house
340
+ end
341
+ ```
342
+
343
+ ```ruby
344
+ class Person
345
+ belongs_to :family
346
+ acts_as_mappable :through => { :family => :house }
347
+ end
348
+ ```
349
+
350
+ Remember that the notes above about USING INCLUDES apply to the results from
351
+ this find, since an include is automatically used.
352
+
353
+ ## IP GEOCODING
354
+
355
+ You can obtain the location for an IP at any time using the geocoder
356
+ as in the following example:
357
+
358
+ ```ruby
359
+ location = IpGeocoder.geocode('12.215.42.19')
360
+ ```
361
+
362
+ where Location is a GeoLoc instance containing the latitude,
363
+ longitude, city, state, and country code. Also, the success
364
+ value is true.
365
+
366
+ If the IP cannot be geocoded, a GeoLoc instance is returned with a
367
+ success value of false.
368
+
369
+ It should be noted that the IP address needs to be visible to the
370
+ Rails application. In other words, you need to ensure that the
371
+ requesting IP address is forwarded by any front-end servers that
372
+ are out in front of the Rails app. Otherwise, the IP will always
373
+ be that of the front-end server.
374
+
375
+ The Multi-Geocoder will also geocode IP addresses and provide
376
+ failover among multiple IP geocoders. Just pass in an IP address for the
377
+ parameter instead of a street address. Eg:
378
+
379
+ ```ruby
380
+ location = Geocoders::MultiGeocoder.geocode('12.215.42.19')
381
+ ```
382
+
383
+ The MultiGeocoder class requires 2 configuration setting for the provider order.
384
+ Ordering is done through `Geokit::Geocoders::provider_order` and
385
+ `Geokit::Geocoders::ip_provider_order`, found in
386
+ `config/initializers/geokit_config.rb`. If you don't already have a
387
+ `geokit_config.rb` file, the plugin creates one when it is first installed.
388
+
389
+
390
+ ## IP GEOCODING HELPER
391
+
392
+ A class method called geocode_ip_address has been mixed into the
393
+ ActionController::Base. This enables before_filter style lookup of
394
+ the IP address. Since it is a filter, it can accept any of the
395
+ available filter options.
396
+
397
+ Usage is as below:
398
+
399
+ ```ruby
400
+ class LocationAwareController < ActionController::Base
401
+ geocode_ip_address
402
+ end
403
+ ```
404
+
405
+ A first-time lookup will result in the GeoLoc class being stored
406
+ in the session as `:geo_location` as well as in a cookie called
407
+ `:geo_session`. Subsequent lookups will use the session value if it
408
+ exists or the cookie value if it doesn't exist. The last resort is
409
+ to make a call to the web service. Clients are free to manage the
410
+ cookie as they wish.
411
+
412
+ The intent of this feature is to be able to provide a good guess as
413
+ to a new visitor's location.
414
+
415
+ ## INTEGRATED FIND AND GEOCODING
416
+
417
+ Geocoding has been integrated with the finders enabling you to pass
418
+ a physical address or an IP address. This would look the following:
419
+
420
+ ```ruby
421
+ Location.farthest(:origin => '217.15.10.9')
422
+ Location.farthest(:origin => 'Irving, TX')
423
+ ```
424
+
425
+ where the IP or physical address would be geocoded to a location and
426
+ then the resulting latitude and longitude coordinates would be used
427
+ in the find. This is not expected to be common usage, but it can be
428
+ done nevertheless.
429
+
430
+ ## ADDRESS GEOCODING
431
+
432
+ Geocoding is provided by the Geokit gem, which is required for this plugin.
433
+ See the top of this file for instructions on installing the Geokit gem.
434
+
435
+ Geokit can geocode addresses using multiple geocodeing web services.
436
+ Geokit supports services like Google, Yahoo, and Geocoder.us, and more --
437
+ see the Geokit gem API for a complete list.
438
+
439
+ These geocoder services are made available through the following classes:
440
+ GoogleGeocoder, YahooGeocoder, UsGeocoder, CaGeocoder, and GeonamesGeocoder.
441
+ Further, an additional geocoder class called MultiGeocoder incorporates an ordered failover
442
+ sequence to increase the probability of successful geocoding.
443
+
444
+ All classes are called using the following signature:
445
+
446
+ ```ruby
447
+ include Geokit::Geocoders
448
+ location = XxxGeocoder.geocode(address)
449
+ ```
450
+
451
+ where you replace Xxx Geocoder with the appropriate class. A GeoLoc
452
+ instance is the result of the call. This class has a "success"
453
+ attribute which will be true if a successful geocoding occurred.
454
+ If successful, the lat and lng properties will be populated.
455
+
456
+ Geocoders are named with the convention NameGeocoder. This
457
+ naming convention enables Geocoder to auto-detect its sub-classes
458
+ in order to create methods called `name_geocoder(address)` so that
459
+ all geocoders can be called through the base class. This is done
460
+ purely for convenience; the individual geocoder classes are expected
461
+ to be used independently.
462
+
463
+ The MultiGeocoder class requires the configuration of a provider
464
+ order which dictates what order to use the various geocoders. Ordering
465
+ is done through `Geokit::Geocoders::provider_order`, found in
466
+ `config/initializers/geokit_config.rb`.
467
+
468
+ If you don't already have a `geokit_config.rb` file, the plugin creates one
469
+ when it is first installed.
470
+
471
+ Make sure your failover configuration matches the usage characteristics
472
+ of your application -- for example, if you routinely get bogus input to
473
+ geocode, your code will be much slower if you have to failover among
474
+ multiple geocoders before determining that the input was in fact bogus.
475
+
476
+ The Geocoder.geocode method returns a GeoLoc object. Basic usage:
477
+
478
+ ```ruby
479
+ loc=Geocoder.geocode('100 Spear St, San Francisco, CA')
480
+ if loc.success
481
+ puts loc.lat
482
+ puts loc.lng
483
+ puts loc.full_address
484
+ end
485
+ ```
486
+
487
+ ## REVERSE GEOCODING
488
+
489
+ Currently, only the Google Geocoder supports reverse geocoding.
490
+ Pass the lat/lng as a string, array or LatLng instance:
491
+
492
+ ```ruby
493
+ res=Geokit::Geocoders::GoogleGeocoder.reverse_geocode "37.791821,-122.394679"
494
+ => #<Geokit::GeoLoc:0x558ed0 ...
495
+ res.full_address "101-115 Main St, San Francisco, CA 94105, USA"
496
+ ```
497
+
498
+ The address will usually appear as a range, as it does in the above example.
499
+
500
+
501
+ ## INTEGRATED FIND WITH ADDRESS GEOCODING
502
+
503
+ Just has you can pass an IP address directly into an ActiveRecord finder
504
+ as the origin, you can also pass a physical address as the origin:
505
+
506
+ ```ruby
507
+ Location.find_closest(:origin => '100 Spear st, San Francisco, CA')
508
+ ```
509
+
510
+ where the physical address would be geocoded to a location and then the
511
+ resulting latitude and longitude coordinates would be used in the
512
+ find.
513
+
514
+ Note that if the address fails to geocode, the find method will raise an
515
+ ActiveRecord::GeocodeError you must be prepared to catch. Alternatively,
516
+ You can geocoder the address beforehand, and pass the resulting lat/lng
517
+ into the finder if successful.
518
+
519
+ ## Auto Geocoding
520
+
521
+ If your geocoding needs are simple, you can tell your model to automatically
522
+ geocode itself on create:
523
+
524
+ ```ruby
525
+ class Store < ActiveRecord::Base
526
+ acts_as_mappable :auto_geocode=>true
527
+ end
528
+ ```
529
+
530
+ It takes two optional params:
531
+
532
+ ```ruby
533
+ class Store < ActiveRecord::Base
534
+ acts_as_mappable :auto_geocode=>{:field=>:address, :error_message=>'Could not geocode address'}
535
+ end
536
+ ```
537
+
538
+ . . . which is equivalent to:
539
+
540
+ ```ruby
541
+ class Store << ActiveRecord::Base
542
+ acts_as_mappable
543
+ before_validation :geocode_address, :on => :create
544
+
545
+ private
546
+ def geocode_address
547
+ geo=Geokit::Geocoders::MultiGeocoder.geocode (address)
548
+ errors.add(:address, "Could not Geocode address") if !geo.success
549
+ self.lat, self.lng = geo.lat,geo.lng if geo.success
550
+ end
551
+ end
552
+ ```
553
+
554
+ If you need any more complicated geocoding behavior for your model, you should roll your own
555
+ `before_validate` callback.
556
+
557
+
558
+ ## Distances, headings, endpoints, and midpoints
559
+
560
+ ```ruby
561
+ distance = home.distance_from(work, :units=>:miles)
562
+ heading = home.heading_to(work) # result is in degrees, 0 is north
563
+ endpoint = home.endpoint(90,2) # two miles due east
564
+ midpoint = home.midpoint_to(work)
565
+ ```
566
+
567
+ ## Cool stuff you can do with bounds
568
+
569
+ ```ruby
570
+ bounds = Bounds.new(sw_point,ne_point)
571
+ bounds.contains?(home)
572
+ puts bounds.center
573
+ ```
574
+
575
+ HOW TO . . .
576
+ =================================================================================
577
+
578
+ A few quick examples to get you started ....
579
+
580
+ ## How to install the Geokit Rails plugin
581
+ (See the very top of this file)
582
+
583
+ ## How to find all stores within a 10-mile radius of a given lat/lng
584
+ 1. ensure your stores table has lat and lng columns with numeric or float
585
+ datatypes to store your latitude/longitude
586
+
587
+ 2. use `acts_as_mappable` on your store model:
588
+ 3.
589
+ ```ruby
590
+ class Store < ActiveRecord::Base
591
+ acts_as_mappable
592
+ ...
593
+ end
594
+ ```
595
+
596
+ 3. finders now have extra capabilities:
597
+
598
+ ```ruby
599
+ Store.find(:all, :origin =>[32.951613,-96.958444], :within=>10)
600
+ ```
601
+
602
+ ## How to geocode an address
603
+
604
+ 1. configure your geocoder key(s) in `config/initializers/geokit_config.rb`
605
+
606
+ 2. also in `geokit_config.rb`, make sure that `Geokit::Geocoders::provider_order` reflects the
607
+ geocoder(s). If you only want to use one geocoder, there should
608
+ be only one symbol in the array. For example:
609
+
610
+ ```ruby
611
+ Geokit::Geocoders::provider_order=[:google]
612
+ ```
613
+
614
+ 3. Test it out in script/console
615
+
616
+ ```ruby
617
+ include Geokit::Geocoders
618
+ res = MultiGeocoder.geocode('100 Spear St, San Francisco, CA')
619
+ puts res.lat
620
+ puts res.lng
621
+ puts res.full_address
622
+ ```
623
+
624
+ ... etc. The return type is GeoLoc, see the API for
625
+ all the methods you can call on it.
626
+
627
+ ## How to find all stores within 10 miles of a given address
628
+
629
+ 1. as above, ensure your table has the lat/lng columns, and you've
630
+ applied `acts_as_mappable` to the Store model.
631
+
632
+ 2. configure and test out your geocoder, as above
633
+
634
+ 3. pass the address in under the :origin key
635
+
636
+ ```ruby
637
+ Store.find(:all, :origin=>'100 Spear st, San Francisco, CA', :within=>10)
638
+ ```
639
+
640
+ 4. you can also use a zipcode, or anything else that's geocodable:
641
+
642
+ ```ruby
643
+ Store.find(:all, :origin=>'94117', :conditions=>'distance<10')
644
+ ```
645
+
646
+ ## How to sort a query by distance from an origin
647
+
648
+ You now have access to a 'distance' column, and you can use it
649
+ as you would any other column. For example:
650
+
651
+ ```ruby
652
+ Store.find(:all, :origin=>'94117', :order=>'distance')
653
+ ```
654
+
655
+ ## How to sort elements of an array according to distance from a common point
656
+
657
+ Usually, you can do your sorting in the database as part of your find call.
658
+ If you need to sort things post-query, you can do so:
659
+
660
+ ```ruby
661
+ stores = Store.all
662
+ stores.sort_by{|s| s.distance_to(home)}
663
+ ```
664
+
665
+ Obviously, each of the items in the array must have a latitude/longitude so
666
+ they can be sorted by distance.
667
+
668
+ ## Database indexes
669
+
670
+ MySQL can't create indexes on a calculated field such as those Geokit uses to
671
+ calculate distance based on latitude/longitude values for a record. However,
672
+ indexing the lat and lng columns does improve Geokit distance calculation
673
+ performance since the lat and lng columns are used in a straight comparison
674
+ for distance calculation. Assuming a Page model that is incorporating the
675
+ Geokit plugin the migration would be as follows.
676
+
677
+ ```ruby
678
+ class AddIndexToPageLatAndLng < ActiveRecord::Migration
679
+
680
+ def self.up
681
+ add_index :pages, [:lat, :lng]
682
+ end
683
+
684
+ def self.down
685
+ remove_index :pages, [:lat, :lng]
686
+ end
687
+ end
688
+ ```
689
+
690
+ ## Database Compatability
691
+
692
+ * Geokit works with MySQL (tested with version 5.0.41), PostgreSQL (tested with version 8.2.6) and Microsoft SQL Server (tested with 2000).
693
+ * Geokit is known to *not* work with Postgres versions under 8.1 -- it uses the least() funciton.
694
+
695
+
696
+ ## HIGH-LEVEL NOTES ON WHAT'S WHERE
697
+
698
+ `acts_as_mappable.rb`, as you'd expect, contains the ActsAsMappable
699
+ module which gets mixed into your models to provide the
700
+ location-based finder goodness.
701
+
702
+ `ip_geocode_lookup.rb` contains the before_filter helper method which
703
+ enables auto lookup of the requesting IP address.
704
+
705
+ ### The Geokit gem provides the building blocks of distance-based operations:
706
+
707
+ The Mappable module, which provides basic
708
+ distance calculation methods, i.e., calculating the distance
709
+ between two points.
710
+
711
+ The LatLng class is a simple container for latitude and longitude, but
712
+ it's made more powerful by mixing in the above-mentioned Mappable
713
+ module -- therefore, you can calculate easily the distance between two
714
+ LatLng objects with `distance = first.distance_to(other)`
715
+
716
+ GeoLoc represents an address or location which
717
+ has been geocoded. You can get the city, zipcode, street address, etc.
718
+ from a GeoLoc object. GeoLoc extends LatLng, so you also get lat/lng
719
+ AND the Mappable module goodness for free.
720
+
721
+ ## IMPORTANT POST-INSTALLATION NOTES:
722
+
723
+ *1. The configuration file*: Geokit for Rails uses a configuration file in config/initializers.
724
+ You *must* add your own keys for the various geocoding services if you want to use geocoding.
725
+ If you need to refer to the original template again, see the `assets/api_keys_template` file.
726
+
727
+ *2. The gem dependency*: Geokit for Rails depends on the Geokit gem. Tell Rails about this
728
+ dependency in `config/environment.rb`, within the initializer block:
729
+ config.gem "geokit"