geocoder 0.9.8 → 0.9.9

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

Potentially problematic release.


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

data/.gitignore ADDED
@@ -0,0 +1,3 @@
1
+ pkg/*
2
+ *.gem
3
+ .bundle
data/CHANGELOG.rdoc CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  Per-release changes to Geocoder.
4
4
 
5
+ == 0.9.9 (2011 Mar 9)
6
+
7
+ * Add support for IP address geocoding via FreeGeoIp.net.
8
+ * Add support for Yahoo PlaceFinder geocoding API.
9
+ * Add support for custom geocoder data handling by passing a block to geocoded_by or reverse_geocoded_by.
10
+ * Add <tt>Rack::Request#location</tt> method for geocoding user's IP address.
11
+ * Change gem name to geocoder (no more rails-geocoder).
12
+ * Gem now works outside of Rails.
13
+ * DEPRECATION: +fetch_coordinates+ no longer takes an argument.
14
+ * DEPRECATION: +fetch_address+ no longer takes an argument.
15
+ * DEPRECATION: Geocoder.search now returns a single result instead of an array.
16
+ * DEPRECATION: <tt>fetch_coordinates!</tt> has been superceded by +geocode+ (then save your object manually).
17
+ * DEPRECATION: <tt>fetch_address!</tt> has been superceded by +reverse_geocode+ (then save your object manually).
18
+ * Fix: don't die when trying to get coordinates with a nil address (github.com/zmack).
19
+
5
20
  == 0.9.8 (2011 Feb 8)
6
21
 
7
22
  * Include geocode:all Rake task in gem (was missing!).
@@ -13,13 +28,13 @@ Per-release changes to Geocoder.
13
28
  == 0.9.7 (2011 Feb 1)
14
29
 
15
30
  * Add reverse geocoding (+reverse_geocoded_by+).
16
- * Prevent exception (uninitialized constant Geocoder::Net) when net/http not already required (sleepycat).
31
+ * Prevent exception (uninitialized constant Geocoder::Net) when net/http not already required (github.com/sleepycat).
17
32
  * Refactor: split monolithic Geocoder module into several smaller ones.
18
33
 
19
34
  == 0.9.6 (2011 Jan 19)
20
35
 
21
36
  * Fix incompatibility with will_paginate gem.
22
- * Include table names in GROUP BY clause of nearby scope to avoid ambiguity in joins (matchu).
37
+ * Include table names in GROUP BY clause of nearby scope to avoid ambiguity in joins (github.com/matchu).
23
38
 
24
39
  == 0.9.5 (2010 Oct 15)
25
40
 
@@ -40,7 +55,7 @@ Per-release changes to Geocoder.
40
55
 
41
56
  == 0.9.2 (2010 Jun 3)
42
57
 
43
- * Fix LIMIT clause bug in PostgreSQL (reported by kenzie).
58
+ * Fix LIMIT clause bug in PostgreSQL (reported by github.com/kenzie).
44
59
 
45
60
  == 0.9.1 (2010 May 4)
46
61
 
@@ -48,7 +63,7 @@ Per-release changes to Geocoder.
48
63
 
49
64
  == 0.9.0 (2010 Apr 2)
50
65
 
51
- * Fix bug in PostgreSQL support (caused "PGError: ERROR: column "distance" does not exist"), reported by developish.
66
+ * Fix bug in PostgreSQL support (caused "PGError: ERROR: column "distance" does not exist"), reported by github.com/developish.
52
67
 
53
68
  == 0.8.9 (2010 Feb 11)
54
69
 
data/README.rdoc CHANGED
@@ -1,19 +1,22 @@
1
1
  = Geocoder
2
2
 
3
- Geocoder adds object geocoding and database-agnostic distance calculations to Ruby on Rails. It's as simple as calling <tt>fetch_coordinates!</tt> on your objects, and then using a scope like <tt>Venue.near("Billings, MT")</tt>. Since it does not rely on proprietary database functions finding geocoded objects in a given area works with out-of-the-box MySQL or even SQLite.
3
+ Geocoder is a complete geocoding solution for Ruby. With Rails it adds object geocoding (by street or IP address), reverse geocoding (find street address based on given coordinates), and distance calculations to Ruby on Rails. It's as simple as calling +geocode+ on your objects, and then using a scope like <tt>Venue.near("Billings, MT")</tt>. Since it does not rely on proprietary database functions finding geocoded objects in a given area works with out-of-the-box PostgreSQL, MySQL, and even SQLite.
4
4
 
5
- Geocoder is compatible with Rails 2.x and 3.x. <b>This is the README for the 3.x branch.</b> Please see the 2.x branch for installation instructions, documentation, and issues.
6
5
 
6
+ == Compatibility
7
7
 
8
- == 1. Install
8
+ Geocoder is compatible with Rails 3. If you need to use it with Rails 2 please see the <tt>rails2</tt> branch (no longer maintained, limited feature set).
9
+
10
+
11
+ == Install
9
12
 
10
13
  === As a Gem
11
14
 
12
- Add this to your Gemfile:
15
+ Add to your Gemfile:
13
16
 
14
- gem "rails-geocoder", :require => "geocoder"
17
+ gem "geocoder"
15
18
 
16
- and run this at the command prompt:
19
+ and run at the command prompt:
17
20
 
18
21
  bundle install
19
22
 
@@ -24,39 +27,35 @@ At the command prompt:
24
27
  rails plugin install git://github.com/alexreisner/geocoder.git
25
28
 
26
29
 
27
- == 2. Configure
28
-
29
- A) Add +latitude+ and +longitude+ columns to your model:
30
-
31
- rails generate migration AddLatitudeAndLongitudeToYourModel latitude:float longitude:float
32
- rake db:migrate
30
+ == Configure Object Geocoding
33
31
 
34
- B) Tell geocoder where your model stores its address:
32
+ === Required Attributes
35
33
 
36
- geocoded_by :address
34
+ Your object must have two attributes (database columns) for storing latitude and longitude coordinates. By default they should be called +latitude+ and +longitude+ but this can be changed (see "More on Configuration" below):
37
35
 
38
- C) Optionally, auto-fetch coordinates every time your model is saved:
36
+ rails generate migration AddLatitudeAndLongitudeToModel latitude:float longitude:float
37
+ rake db:migrate
39
38
 
40
- after_validation :fetch_coordinates
39
+ For reverse geocoding your model must provide a method that returns an address. This can be a single attribute, but it can also be a method that returns a string assembled from different attributes (eg: +city+, +state+, and +country+).
41
40
 
42
- <i>Note that you are not stuck with the +latitude+ and +longitude+ column names, or the +address+ method. See "More On Configuration" below for details.</i>
41
+ === Model Behavior
43
42
 
43
+ In your model, tell Geocoder which method returns your object's full address:
44
44
 
45
- == 3. Use
45
+ geocoded_by :full_street_address # can also be an IP address
46
+ after_validation :geocode # auto-fetch coordinates
46
47
 
47
- Assuming +obj+ is an instance of a geocoded class, you can get its coordinates:
48
+ For reverse geocoding, tell Geocoder which methods return latitude and longitude:
48
49
 
49
- obj.fetch_coordinates # fetches and assigns coordinates
50
- obj.fetch_coordinates! # also saves lat, lon attributes
50
+ reverse_geocoded_by :lat, :lon
51
+ after_validation :reverse_geocode # auto-fetch address
51
52
 
52
- If you have a lot of objects you can use this Rake task to geocode them all:
53
+ If you have just added geocoding to a class and have a lot of existing objects you can use this Rake task to geocode them all:
53
54
 
54
55
  rake geocode:all CLASS=YourModel
55
56
 
56
- Once +obj+ is geocoded you can do things like this:
57
57
 
58
- obj.nearbys(30) # other objects within 30 miles
59
- obj.distance_to(40.714, -100.234) # distance to arbitrary point
58
+ == Location-Aware Database Queries
60
59
 
61
60
  To find objects by location, use the following scopes:
62
61
 
@@ -65,67 +64,121 @@ To find objects by location, use the following scopes:
65
64
  Venue.geocoded # venues with coordinates
66
65
  Venue.not_geocoded # venues without coordinates
67
66
 
68
- Some utility methods are also available:
67
+ With geocoded objects you can do things like this:
69
68
 
70
- # distance (in miles) between Eiffel Tower and Empire State Building
71
- Geocoder::Calculations.distance_between( 48.858205,2.294359, 40.748433,-73.985655 )
69
+ obj.nearbys(30) # other objects within 30 miles
70
+ obj.distance_to(40.714, -100.234) # distance from object to arbitrary point
71
+
72
+ Some utility methods are also available:
72
73
 
73
74
  # look up coordinates of some location (like searching Google Maps)
74
- Geocoder.fetch_coordinates("25 Main St, Cooperstown, NY")
75
+ Geocoder.coordinates("25 Main St, Cooperstown, NY")
76
+ => [42.700149, -74.922767]
77
+
78
+ # distance (in miles) between Eiffel Tower and Empire State Building
79
+ Geocoder::Calculations.distance_between( 47.858205,2.294359, 40.748433,-73.985655 )
80
+ => 3619.77359999382
75
81
 
76
82
  # find the geographic center (aka center of gravity) of objects or points
77
83
  Geocoder::Calculations.geographic_center([ city1, city2, city3, [40.22,-73.99], city4 ])
84
+ => [35.14968, -90.048929]
78
85
 
86
+ Please see the code for more methods and detailed information about arguments (eg, working with kilometers).
79
87
 
80
- == More On Configuration
88
+
89
+ == More on Configuration
81
90
 
82
91
  You are not stuck with using the +latitude+ and +longitude+ database column names for storing coordinates. For example, to use +lat+ and +lon+:
83
92
 
84
93
  geocoded_by :address, :latitude => :lat, :longitude => :lon
85
94
 
86
- The string to use for geocoding can be anything you'd use to search Google Maps. For example, any of the following are acceptable:
95
+ The +address+ method can return any string you'd use to search Google Maps. For example, any of the following are acceptable:
87
96
 
88
- 714 Green St, Big Town, MO
89
- Eiffel Tower, Paris, FR
90
- Paris, TX, US
97
+ * "714 Green St, Big Town, MO"
98
+ * "Eiffel Tower, Paris, FR"
99
+ * "Paris, TX, US"
91
100
 
92
- If your model has +address+, +city+, +state+, and +country+ attributes you might do something like this:
101
+ If your model has +street+, +city+, +state+, and +country+ attributes you might do something like this:
93
102
 
94
- geocoded_by :location
103
+ geocoded_by :address
95
104
 
96
- def location
97
- [address, city, state, country].compact.join(', ')
105
+ def address
106
+ [street, city, state, country].compact.join(', ')
98
107
  end
99
108
 
100
- Please see the code (<tt>lib/geocoder/active_record.rb</tt>) for more methods and detailed information about arguments (eg, working with kilometers).
109
+ For reverse geocoding you can also specify an alternate name attribute where the address will be stored, for example:
101
110
 
102
- You can also set the timeout used for connections to Google's geocoding service. The default is 3 seconds, but if you want to set it to 5 you could put the following in an initializer:
111
+ reverse_geocoded_by :lat, :lon, :address => :location
103
112
 
104
- Geocoder::Configuration.timeout = 5
105
113
 
114
+ == Advanced Geocoding
106
115
 
107
- == Reverse Geocoding
116
+ So far we have looked at shortcuts for assigning geocoding results to object attributes. However, if you need to do something fancy you can skip the auto-assignment by providing a block (takes the object to be geocoded and a <tt>Geocoder::Result</tt> object) in which you handle the parsed geocoding result any way you like, for example:
108
117
 
109
- If you need reverse geocoding (lat/long coordinates to address), do something like the following in your model:
118
+ reverse_geocoded_by :lat, :lon do |obj,geo|
119
+ obj.city = geo.city
120
+ obj.zipcode = geo.postal_code
121
+ obj.country = geo.country_code
122
+ end
123
+ after_validation :reverse_geocode
110
124
 
111
- reverse_geocoded_by :latitude, :longitude
112
- after_validation :fetch_address
125
+ Every <tt>Geocoder::Result</tt> object, +result+, provides the following data:
113
126
 
114
- and make sure it has +latitude+ and +longitude+ attributes, as well as an +address+ attribute. As with regular geocoding, you can specify alternate names for all of these attributes, for example:
127
+ * <tt>result.latitude # float</tt>
128
+ * <tt>result.longitude # float</tt>
129
+ * <tt>result.coordinates # array of the above two</tt>
130
+ * <tt>result.address # string</tt>
131
+ * <tt>result.city # string</tt>
132
+ * <tt>result.postal_code # string</tt>
133
+ * <tt>result.country_name # string</tt>
134
+ * <tt>result.country_code # string</tt>
115
135
 
116
- reverse_geocoded_by :lat, :lon, :address => :location
136
+ and if you're familiar with the results returned by the geocoding service you're using, you can access even more (see code comments for details: <tt>lib/geocoder/results/*</tt>).
137
+
138
+
139
+ == Geocoding Services
140
+
141
+ By default Geocoder uses Google's geocoding API to fetch coordinates and addresses. However if you wish to use Yahoo's geocoding API you can simply add this to an initializer:
142
+
143
+ # config/initializers/geocoder.rb
144
+ Geocoder::Configuration.lookup = :yahoo
145
+ Geocoder::Configuration.yahoo_appid = "..."
146
+
147
+ To obtain a Yahoo app id go to:
148
+
149
+ https://developer.apps.yahoo.com/wsregapp
150
+
151
+ Note that the result objects returned by different geocoding services all implement the methods listed above. Beyond that, however, you must be familiar with your particular subclass of <tt>Geocoder::Result</tt> and the geocoding service's result structure:
152
+
153
+ Google: http://code.google.com/apis/maps/documentation/geocoding/#JSON
154
+
155
+ Yahoo: http://developer.yahoo.com/geo/placefinder/guide/responses.html
156
+
157
+ FreeGeoIP: http://github.com/fiorix/freegeoip/blob/master/README.rst
158
+
159
+ === Timeouts
160
+
161
+ You can set the timeout used for connections to the geocoding service. The default is 3 seconds but if you want to set it to 5, for example, put the following in an initializer:
162
+
163
+ # config/initializers/geocoder.rb
164
+ Geocoder::Configuration.timeout = 5
117
165
 
118
166
 
119
167
  == Forward and Reverse Geocoding in the Same Model
120
168
 
121
- If you apply both forward and reverse geocoding functionality to the same model, you can provide different methods for storing the fetched address (reverse geocoding) and providing an address to use when fetching coordinates (forward geocoding), for example:
169
+ If you apply both forward and reverse geocoding functionality to the same model, you will provide two address methods:
170
+
171
+ * one for storing the fetched address (reverse geocoding)
172
+ * one for providing an address to use when fetching coordinates (forward geocoding)
173
+
174
+ For example:
122
175
 
123
176
  class Venue
124
177
 
125
178
  # build an address from street, city, and state attributes
126
179
  geocoded_by :address_from_components
127
180
 
128
- # store the Google-provided address in the full_address attribute
181
+ # store the fetched address in the full_address attribute
129
182
  reverse_geocoded_by :latitude, :longitude, :address => :full_address
130
183
  end
131
184
 
@@ -143,38 +196,26 @@ However, there can be only one set of latitude/longitude attributes, and whichev
143
196
  The reason for this is that we don't want ambiguity when doing distance calculations. We need a single, authoritative source for coordinates!
144
197
 
145
198
 
146
- == Getting More Information
199
+ == Request Geocoding by IP Address
200
+
201
+ Geocoder adds a +location+ method to the standard <tt>Rack::Request</tt> object so you can easily look up the location of any HTTP request by IP address. For example, in a Rails controller or a Sinatra app:
147
202
 
148
- Those familiar with Google's Geocoding API know that it returns much more information than just an address or set of coordinates. If you want access to the entire response you can use the <tt>Geocoder.search</tt> method:
203
+ # returns Geocoder::Result object
204
+ result = request.location
149
205
 
150
- results = Geocoder.search("McCarren Park, Brooklyn, NY")
151
- r = results.first
152
206
 
153
- +r+ is now a Geocoder::Result object which has methods like the following:
207
+ == Use Outside of Rails
154
208
 
155
- r.geometry
156
- => {
157
- "location"=>{"lng"=>-79.3801601, "lat"=>43.6619568},
158
- "location_type"=>"ROOFTOP",
159
- "viewport"=>{
160
- "northeast"=>{"lng"=>-79.3770125, "lat"=>43.6651044},
161
- "southwest"=>{"lng"=>-79.3833077, "lat"=>43.6588092}
162
- }
163
- }
209
+ You can use Geocoder outside of Rails by calling the <tt>Geocoder.search</tt> method:
164
210
 
165
- r.address_components_of_type(:neighborhood)
166
- => [{
167
- "long_name"=>"Greenpoint",
168
- "short_name"=>"Greenpoint",
169
- "types"=>["neighborhood", "political"]
170
- }]
211
+ result = Geocoder.search("McCarren Park, Brooklyn, NY")
171
212
 
172
- Please see the Geocoder::Result class for more information, as well as Google's API documentation (http://code.google.com/apis/maps/documentation/geocoding/#JSON).
213
+ This returns a <tt>Geocoder::Result</tt> object with all information provided by the geocoding service. Please see above and in the code for details.
173
214
 
174
215
 
175
- == SQLite
216
+ == Distance Queries in SQLite
176
217
 
177
- SQLite's lack of trigonometric functions requires an alternate implementation of the +near+ method (scope). When using SQLite, Geocoder will automatically use a less accurate algorithm for finding objects near a given point. Results of this algorithm should not be trusted too much as it will return objects that are outside the given radius.
218
+ SQLite's lack of trigonometric functions requires an alternate implementation of the +near+ scope. When using SQLite, Geocoder will automatically use a less accurate algorithm for finding objects near a given point. Results of this algorithm should not be trusted too much as it will return objects that are outside the given radius.
178
219
 
179
220
  It is also not possible to calculate distances between points without the trig functions so you cannot sort results by "nearness."
180
221
 
@@ -204,10 +245,8 @@ If anyone has a more elegant solution to this problem I am very interested in se
204
245
 
205
246
  == To-do List
206
247
 
207
- * support different ORMs (DataMapper, Mongoid, etc)
208
- * use completely separate "drivers" for different AR adapters?
209
- * seems reasonable since we're using very DB-specific features
210
- * also need to make sure 'mysql2' is supported
248
+ * add support for DataMapper
249
+ * add support for Mongoid
211
250
  * make 'near' scope work with AR associations
212
251
  * http://stackoverflow.com/questions/3266358/geocoder-rails-plugin-near-search-problem-with-activerecord
213
252
 
data/Rakefile CHANGED
@@ -1,21 +1,5 @@
1
- require 'rubygems'
2
- require 'rake'
3
-
4
- begin
5
- require 'jeweler'
6
- Jeweler::Tasks.new do |gem|
7
- gem.name = "rails-geocoder"
8
- gem.summary = %Q{Add geocoding functionality to Rails models.}
9
- gem.description = %Q{Geocoder adds object geocoding and database-agnostic distance calculations to Ruby on Rails. It does not rely on proprietary database functions so finding geocoded objects in a given area is easily done using out-of-the-box MySQL or even SQLite.}
10
- gem.email = "alex@alexreisner.com"
11
- gem.homepage = "http://github.com/alexreisner/geocoder"
12
- gem.authors = ["Alex Reisner"]
13
- # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
14
- end
15
- Jeweler::GemcutterTasks.new
16
- rescue LoadError
17
- puts "Jeweler (or a dependency) not available. Install it with: sudo gem install jeweler"
18
- end
1
+ require 'bundler'
2
+ Bundler::GemHelper.install_tasks
19
3
 
20
4
  require 'rake/testtask'
21
5
  Rake::TestTask.new(:test) do |test|
@@ -24,21 +8,6 @@ Rake::TestTask.new(:test) do |test|
24
8
  test.verbose = true
25
9
  end
26
10
 
27
- begin
28
- require 'rcov/rcovtask'
29
- Rcov::RcovTask.new do |test|
30
- test.libs << 'test'
31
- test.pattern = 'test/**/*_test.rb'
32
- test.verbose = true
33
- end
34
- rescue LoadError
35
- task :rcov do
36
- abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
37
- end
38
- end
39
-
40
- task :test => :check_dependencies
41
-
42
11
  task :default => :test
43
12
 
44
13
  require 'rake/rdoctask'
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.9.9
data/lib/geocoder.rb CHANGED
@@ -1,23 +1,96 @@
1
1
  require "geocoder/configuration"
2
2
  require "geocoder/calculations"
3
- require "geocoder/lookup"
4
- require "geocoder/result"
5
- require "geocoder/active_record"
6
3
  require "geocoder/railtie"
4
+ require "geocoder/request"
7
5
 
8
6
  module Geocoder
9
7
  extend self
10
8
 
11
9
  ##
12
- # Alias for Geocoder::Lookup.search.
10
+ # Search for information about an address or a set of coordinates.
13
11
  #
14
12
  def search(*args)
15
- Lookup.search(*args)
13
+ return nil if blank_query?(args[0])
14
+ ip = (args.size == 1 and ip_address?(args.first))
15
+ lookup(ip).search(*args)
16
16
  end
17
17
 
18
+ ##
19
+ # Look up the coordinates of the given street or IP address.
20
+ #
21
+ def coordinates(address)
22
+ if result = search(address)
23
+ result.coordinates
24
+ end
25
+ end
26
+
27
+ ##
28
+ # Look up the address of the given coordinates.
29
+ #
30
+ def address(latitude, longitude)
31
+ if result = search(latitude, longitude)
32
+ result.address
33
+ end
34
+ end
35
+
36
+
18
37
  # exception classes
19
38
  class Error < StandardError; end
20
39
  class ConfigurationError < Error; end
40
+
41
+
42
+ private # -----------------------------------------------------------------
43
+
44
+ ##
45
+ # Get the lookup object (which communicates with the remote geocoding API).
46
+ # Returns an IP address lookup if +ip+ parameter true.
47
+ #
48
+ def lookup(ip = false)
49
+ if ip
50
+ get_lookup :freegeoip
51
+ else
52
+ get_lookup Geocoder::Configuration.lookup || :google
53
+ end
54
+ end
55
+
56
+ def get_lookup(name)
57
+ unless defined?(@lookups)
58
+ @lookups = {}
59
+ end
60
+ unless @lookups.include?(name)
61
+ @lookups[name] = spawn_lookup(name)
62
+ end
63
+ @lookups[name]
64
+ end
65
+
66
+ def spawn_lookup(name)
67
+ if valid_lookups.include?(name)
68
+ name = name.to_s
69
+ require "geocoder/lookups/#{name}"
70
+ eval("Geocoder::Lookup::#{name[0...1].upcase + name[1..-1]}.new")
71
+ end
72
+ end
73
+
74
+ def valid_lookups
75
+ [:google, :yahoo, :freegeoip]
76
+ end
77
+
78
+ ##
79
+ # Does the given value look like an IP address?
80
+ #
81
+ # Does not check for actual validity, just the appearance of four
82
+ # dot-delimited 8-bit numbers.
83
+ #
84
+ def ip_address?(value)
85
+ !!value.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)
86
+ end
87
+
88
+ ##
89
+ # Is the given search query blank? (ie, should we not bother searching?)
90
+ #
91
+ def blank_query?(value)
92
+ !value.to_s.match(/[A-z0-9]/)
93
+ end
21
94
  end
22
95
 
23
96
  Geocoder::Railtie.insert