diff --git a/vendor/plugins/geokit/MIT-LICENSE b/vendor/plugins/geokit/MIT-LICENSE new file mode 100644 index 0000000..97d81c8 --- /dev/null +++ b/vendor/plugins/geokit/MIT-LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2007 Bill Eisenhauer & Andre Lewis + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/plugins/geokit/README b/vendor/plugins/geokit/README new file mode 100644 index 0000000..02079fb --- /dev/null +++ b/vendor/plugins/geokit/README @@ -0,0 +1,451 @@ +## FEATURE SUMMARY + +This plugin provides key functionality for location-oriented Rails applications: + +- Distance calculations, for both flat and spherical environments. For example, + given the location of two points on the earth, you can calculate the miles/KM + between them. +- ActiveRecord distance-based finders. For example, you can find all the points + in your database within a 50-mile radius. +- Geocoding from multiple providers. It currently supports Google, Yahoo, + Geocoder.us, and Geocoder.ca geocoders, and it provides a uniform response + structure from all of them. It also provides a fail-over mechanism, in case + your input fails to geocode in one service. +- IP-based location lookup utilizing hostip.info. Provide an IP address, and get + city name and latitude/longitude in return +- A before_filter helper to geocoder the user's location based on IP address, + and retain the location in a cookie. + +The goal of this plugin is to provide the common functionality for location-oriented +applications (geocoding, location lookup, distance calculation) in an easy-to-use +package. + +## A NOTE ON TERMINOLOGY + +Throughout the code and API of this, latitude and longitude are referred to as lat +and lng. We've found over the long term the abbreviation saves lots of typing time. + +## DISTANCE CALCULATIONS AND QUERIES + +If you want only distance calculation services, you need only mix in the Mappable +module like so: + + class Location + include GeoKit::Mappable + end + +After doing so, you can do things like: + + Location.distance_between(from, to) + +with optional parameters :units and :formula. Values for :units can be :miles or +:kms with :miles as the default. Values for :formula can be :sphere or :flat with +:sphere as the default. :sphere gives you Haversine calculations, while :flat +gives the Pythagoreum Theory. These defaults persist through out the plug-in. + +You can also do: + + location.distance_to(other) + +The real power and utility of the plug-in is in its query support. This is +achieved through mixing into an ActiveRecord model object: + + class Location < ActiveRecord::Base + acts_as_mappable + end + +The plug-in uses the above-mentioned defaults, but can be modified to use +different units and a different formulae. This is done through the :default_units +and :default_formula keys which accept the same values as mentioned above. + +The plug-in creates a calculated column and potentially a calculated condition. +By default, these are known as "distance" but this can be changed through the +:distance_field_name key. + +So, an alternative invocation would look as below: + + class Location < ActiveRecord::Base + acts_as_mappable :default_units => :kms, + :default_formula => :flat, + :distance_field_name => :distance + end + +You can also define alternative column names for latitude and longitude using +the :lat_column_name and :lng_column_name keys. The defaults are 'lat' and +'lng' respectively. + +Thereafter, a set of finder methods are made available. Below are the +different combinations: + +Origin as a two-element array of latititude/longitude: + + find(:all, :origin => [37.792,-122.393]) + +Origin as a geocodeable string: + + find(:all, :origin => '100 Spear st, San Francisco, CA') + +Origin as an object which responds to lat and lng methods, +or latitude and longitude methods, or whatever methods you have +specified for lng_column_name and lat_column_name: + + find(:all, :origin=>my_store) # my_store.lat and my_store.lng methods exist + +Often you will need to find within a certain distance. The prefered syntax is: + + find(:all, :origin => @somewhere, :within => 5) + +. . . however these syntaxes will also work: + + find_within(5, :origin => @somewhere) + find(:all, :origin => @somewhere, :conditions => "distance < 5") + +Note however that the third form should be avoided. With either of the first two, +GeoKit automatically adds a bounding box to speed up the radial query in the database. +With the third form, it does not. + +If you need to combine distance conditions with other conditions, you should do +so like this: + + find(:all, :origin => @somewhere, :within => 5, :conditions=>['state=?',state]) + +If :origin is not provided in the finder call, the find method +works as normal. Further, the key is removed +from the :options hash prior to invoking the superclass behavior. + +Other convenience methods work intuitively and are as follows: + + find_within(distance, :origin => @somewhere) + find_beyond(distance, :origin => @somewhere) + find_closest(:origin => @somewhere) + find_farthest(:origin => @somewhere) + +where the options respect the defaults, but can be overridden if +desired. + +Lastly, if all that is desired is the raw SQL for distance +calculations, you can use the following: + + distance_sql(origin, units=default_units, formula=default_formula) + +Thereafter, you are free to use it in find_by_sql as you wish. + +There are methods available to enable you to get the count based upon +the find condition that you have provided. These all work similarly to +the finders. So for instance: + + count(:origin, :conditions => "distance < 5") + count_within(distance, :origin => @somewhere) + count_beyond(distance, :origin => @somewhere) + +## FINDING WITHIN A BOUNDING BOX + +If you are displaying points on a map, you probably need to query for whatever falls within the rectangular bounds of the map: + + Store.find :all, :bounds=>[sw_point,ne_point] + +The input to :bounds can be 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. + +If you need to calculate the bounding box from a point and radius, you can do that: + + bounds=Bounds.from_point_and_radius(home,5) + Store.find :all, :bounds=>bounds + +## USING INCLUDES + +You can use includes along with your distance finders: + + stores=Store.find :all, :origin=>home, :include=>[:reviews,:cities] :within=>5, :order=>'distance' + +*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: + + stores.sort_by_distance_from(home) + +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): + + bounds=Bounds.from_point_and_radius(home,5) + stores=Store.find :all, :include=>[:reviews,:cities] :bounds=>bounds + stores.sort_by_distance_from(home) + +## IP GEOCODING + +You can obtain the location for an IP at any time using the geocoder +as in the following example: + + location = IpGeocoder.geocode('12.215.42.19') + +where Location is a GeoLoc instance containing the latitude, +longitude, city, state, and country code. Also, the success +value is true. + +If the IP cannot be geocoded, a GeoLoc instance is returned with a +success value of false. + +It should be noted that the IP address needs to be visible to the +Rails application. In other words, you need to ensure that the +requesting IP address is forwarded by any front-end servers that +are out in front of the Rails app. Otherwise, the IP will always +be that of the front-end server. + +## IP GEOCODING HELPER + +A class method called geocode_ip_address has been mixed into the +ActionController::Base. This enables before_filter style lookup of +the IP address. Since it is a filter, it can accept any of the +available filter options. + +Usage is as below: + + class LocationAwareController < ActionController::Base + geocode_ip_address + end + +A first-time lookup will result in the GeoLoc class being stored +in the session as :geo_location as well as in a cookie called +:geo_session. Subsequent lookups will use the session value if it +exists or the cookie value if it doesn't exist. The last resort is +to make a call to the web service. Clients are free to manage the +cookie as they wish. + +The intent of this feature is to be able to provide a good guess as +to a new visitor's location. + +## INTEGRATED FIND AND GEOCODING + +Geocoding has been integrated with the finders enabling you to pass +a physical address or an IP address. This would look the following: + + Location.find_farthest(:origin => '217.15.10.9') + Location.find_farthest(:origin => 'Irving, TX') + +where the IP or physical address would be geocoded to a location and +then the resulting latitude and longitude coordinates would be used +in the find. This is not expected to be common usage, but it can be +done nevertheless. + +## ADDRESS GEOCODING + +GeoKit can geocode addresses using multiple geocodeing web services. +Currently, GeoKit supports Google, Yahoo, and Geocoder.us geocoding +services. + +These geocoder services are made available through three classes: +GoogleGeocoder, YahooGeocoder, and UsGeocoder. Further, an additional +geocoder class called MultiGeocoder incorporates an ordered failover +sequence to increase the probability of successful geocoding. + +All classes are called using the following signature: + + include GeoKit::Geocoders + location = XxxGeocoder.geocode(address) + +where you replace Xxx Geocoder with the appropriate class. A GeoLoc +instance is the result of the call. This class has a "success" +attribute which will be true if a successful geocoding occurred. +If successful, the lat and lng properties will be populated. + +Geocoders are named with the naming convention NameGeocoder. This +naming convention enables Geocoder to auto-detect its sub-classes +in order to create methods called name_geocoder(address) so that +all geocoders are called through the base class. This is done +purely for convenience; the individual geocoder classes are expected +to be used independently. + +The MultiGeocoder class requires the configuration of a provider +order which dictates what order to use the various geocoders. Ordering +is done through the PROVIDER_ORDER constant found in environment.rb. + +On installation, this plugin appends a template for your API keys to +your environment.rb. + +Make sure your failover configuration matches the usage characteristics +of your application -- for example, if you routinely get bogus input to +geocode, your code will be much slower if you have to failover among +multiple geocoders before determining that the input was in fact bogus. + +The Geocoder.geocode method returns a GeoLoc object. Basic usage: + + loc=Geocoder.geocode('100 Spear St, San Francisco, CA') + if loc.success + puts loc.lat + puts loc.lng + puts loc.full_address + end + +## INTEGRATED FIND WITH ADDRESS GEOCODING + +Just has you can pass an IP address directly into an ActiveRecord finder +as the origin, you can also pass a physical address as the origin: + + Location.find_closest(:origin => '100 Spear st, San Francisco, CA') + +where the physical address would be geocoded to a location and then the +resulting latitude and longitude coordinates would be used in the +find. + +Note that if the address fails to geocode, the find method will raise an +ActiveRecord::GeocodeError you must be prepared to catch. Alternatively, +You can geocoder the address beforehand, and pass the resulting lat/lng +into the finder if successful. + +## Auto Geocoding + +If your geocoding needs are simple, you can tell your model to automatically +geocode itself on create: + + class Store < ActiveRecord::Base + acts_as_mappable :auto_geocode=>true + end + +It takes two optional params: + + class Store < ActiveRecord::Base + acts_as_mappable :auto_geocode=>{:field=>:address, :error_message=>'Could not geocode address'} + end + +. . . which is equivilent to: + + class Store << ActiveRecord::Base + acts_as_mappable + before_validation_on_create :geocode_address + + private + def geocode_address + geo=GeoKit::Geocoders::MultiGeocoder.geocode (address) + errors.add(:address, "Could not Geocode address") if !geo.success + self.lat, self.lng = geo.lat,geo.lng if geo.success + end + end + +If you need any more complicated geocoding behavior for your model, you should roll your own +before_validate callback. + + +## Distances, headings, endpoints, and midpoints + + distance=home.distance_from(work, :units=>:miles) + heading=home.heading_to(work) # result is in degrees, 0 is north + endpoint=home.endpoint(90,2) # two miles due east + midpoing=home.midpoint_to(work) + +## Cool stuff you can do with bounds + + bounds=Bounds.new(sw_point,ne_point) + bounds.contains?(home) + puts bounds.center + + +HOW TO . . . +================================================================================= + +## How to install the GeoKit plugin + cd [APP_ROOT] + ruby script/plugin install svn://rubyforge.org/var/svn/geokit/trunk + or, to install as an external (your project must be version controlled): + ruby script/plugin install -x svn://rubyforge.org/var/svn/geokit/trunk + +## How to find all stores within a 10-mile radius of a given lat/lng +1. ensure your stores table has lat and lng columns with numeric or float + datatypes to store your latitude/longitude + +3. use acts_as_mappable on your store model: + class Store < ActiveRecord::Base + acts_as_mappable + ... + end +3. finders now have extra capabilities: + Store.find(:all, :origin =>[32.951613,-96.958444], :within=>10) + +## How to geocode an address + +1. configure your geocoder key(s) in environment.rb + +2. also in environment.rb, make sure that PROVIDER_ORDER reflects the + geocoder(s). If you only want to use one geocoder, there should + be only one symbol in the array. For example: + PROVIDER_ORDER=[:google] + +3. Test it out in script/console + include GeoKit::Geocoders + res = MultiGeocoder.geocode('100 Spear St, San Francisco, CA') + puts res.lat + puts res.lng + puts res.full_address + ... etc. The return type is GeoLoc, see the API for + all the methods you can call on it. + +## How to find all stores within 10 miles of a given address + +1. as above, ensure your table has the lat/lng columns, and you've + applied acts_as_mappable to the Store model. + +2. configure and test out your geocoder, as above + +3. pass the address in under the :origin key + Store.find(:all, :origin=>'100 Spear st, San Francisco, CA', + :within=>10) + +4. you can also use a zipcode, or anything else that's geocodable: + Store.find(:all, :origin=>'94117', + :conditions=>'distance<10') + +## How to sort a query by distance from an origin + +You now have access to a 'distance' column, and you can use it +as you would any other column. For example: + Store.find(:all, :origin=>'94117', :order=>'distance') + +## How to elements of an array according to distance from a common point + +Usually, you can do your sorting in the database as part of your find call. +If you need to sort things post-query, you can do so: + + stores=Store.find :all + stores.sort_by_distance_from(home) + puts stores.first.distance + +Obviously, each of the items in the array must have a latitude/longitude so +they can be sorted by distance. + +Database Compatability +================================================================================= +GeoKit does *not* work with SQLite, as it lacks the necessary geometry functions. +GeoKit works with MySQL (tested with version 5.0.41) or PostgreSQL (tested with version 8.2.6) +GeoKit is known to *not* work with Postgres <8.1 -- it uses the least() funciton. + + +HIGH-LEVEL NOTES ON WHAT'S WHERE +================================================================================= + +acts_as_mappable.rb, as you'd expect, contains the ActsAsMappable +module which gets mixed into your models to provide the +location-based finder goodness. + +mappable.rb contains the Mappable module, which provides basic +distance calculation methods, i.e., calculating the distance +between two points. + +mappable.rb also contains LatLng, GeoLoc, and Bounds. +LatLng is a simple container for latitude and longitude, but +it's made more powerful by mixing in the above-mentioned Mappable +module -- therefore, you can calculate easily the distance between two +LatLng ojbects with distance = first.distance_to(other) + +GeoLoc (also in mappable.rb) represents an address or location which +has been geocoded. You can get the city, zipcode, street address, etc. +from a GeoLoc object. GeoLoc extends LatLng, so you also get lat/lng +AND the Mappable modeule goodness for free. + +geocoders.rb contains the geocoder classes. + +ip_geocode_lookup.rb contains the before_filter helper method which +enables auto lookup of the requesting IP address. + +## IMPORTANT NOTE: We have appended to your environment.rb file + +Installation of this plugin has appended an API key template +to your environment.rb file. You *must* add your own keys for the various +geocoding services if you want to use geocoding. If you need to refer to the original +template again, see the api_keys_template file in the root of the plugin. diff --git a/vendor/plugins/geokit/Rakefile b/vendor/plugins/geokit/Rakefile new file mode 100644 index 0000000..82e289e --- /dev/null +++ b/vendor/plugins/geokit/Rakefile @@ -0,0 +1,22 @@ +require 'rake' +require 'rake/testtask' +require 'rake/rdoctask' + +desc 'Default: run unit tests.' +task :default => :test + +desc 'Test the GeoKit plugin.' +Rake::TestTask.new(:test) do |t| + t.libs << 'lib' + t.pattern = 'test/**/*_test.rb' + t.verbose = true +end + +desc 'Generate documentation for the GeoKit plugin.' +Rake::RDocTask.new(:rdoc) do |rdoc| + rdoc.rdoc_dir = 'rdoc' + rdoc.title = 'GeoKit' + rdoc.options << '--line-numbers' << '--inline-source' + rdoc.rdoc_files.include('README') + rdoc.rdoc_files.include('lib/**/*.rb') +end \ No newline at end of file diff --git a/vendor/plugins/geokit/VERSION_HISTORY.txt b/vendor/plugins/geokit/VERSION_HISTORY.txt new file mode 100644 index 0000000..8805383 --- /dev/null +++ b/vendor/plugins/geokit/VERSION_HISTORY.txt @@ -0,0 +1,4 @@ +01/20/08 Version 1.0.1. 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+ +01/16/08 fixed the "zero-distance" bug (calculating between two points that are the same) +12/11/07 fixed a small but with queries crossing meridian, and also fixed find(:closest) +10/11/07 Fixed Rails2/Edge compatability \ No newline at end of file diff --git a/vendor/plugins/geokit/about.yml b/vendor/plugins/geokit/about.yml new file mode 100644 index 0000000..43a5675 --- /dev/null +++ b/vendor/plugins/geokit/about.yml @@ -0,0 +1,9 @@ +author: + name_1: Bill Eisenhauer + homepage_1: http://blog.billeisenhauer.com + name_2: Andre Lewis + homepage_2: http://www.earthcode.com +summary: Geo distance calculations, distance calculation query support, geocoding for physical and ip addresses. +version: 1.0.1 +rails_version: 1.0+ +license: MIT \ No newline at end of file diff --git a/vendor/plugins/geokit/assets/api_keys_template b/vendor/plugins/geokit/assets/api_keys_template new file mode 100644 index 0000000..6367a1a --- /dev/null +++ b/vendor/plugins/geokit/assets/api_keys_template @@ -0,0 +1,50 @@ +# These defaults are used in GeoKit::Mappable.distance_to and in acts_as_mappable +GeoKit::default_units = :miles +GeoKit::default_formula = :sphere + +# 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. +GeoKit::Geocoders::timeout = 3 + +# These settings are used if web service calls must be routed through a proxy. +# 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. +GeoKit::Geocoders::proxy_addr = nil +GeoKit::Geocoders::proxy_port = nil +GeoKit::Geocoders::proxy_user = nil +GeoKit::Geocoders::proxy_pass = nil + +# This is your yahoo application key for the Yahoo Geocoder. +# See http://developer.yahoo.com/faq/index.html#appid +# and http://developer.yahoo.com/maps/rest/V1/geocode.html +GeoKit::Geocoders::yahoo = 'REPLACE_WITH_YOUR_YAHOO_KEY' + +# This is your Google Maps geocoder key. +# See http://www.google.com/apis/maps/signup.html +# and http://www.google.com/apis/maps/documentation/#Geocoding_Examples +GeoKit::Geocoders::google = 'REPLACE_WITH_YOUR_GOOGLE_KEY' + +# This is your username and password for geocoder.us. +# To use the free service, the value can be set to nil or false. For +# usage tied to an account, the value should be set to username:password. +# See http://geocoder.us +# and http://geocoder.us/user/signup +GeoKit::Geocoders::geocoder_us = false + +# This is your authorization key for geocoder.ca. +# 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 +# Geocoder.ca. +# See http://geocoder.ca +# and http://geocoder.ca/?register=1 +GeoKit::Geocoders::geocoder_ca = false + +# This is the order in which the geocoders are called in a failover scenario +# If you only want to use a single geocoder, put a single symbol in the array. +# Valid symbols are :google, :yahoo, :us, and :ca. +# 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. +GeoKit::Geocoders::provider_order = [:google,:us] \ No newline at end of file diff --git a/vendor/plugins/geokit/init.rb b/vendor/plugins/geokit/init.rb new file mode 100644 index 0000000..d36503e --- /dev/null +++ b/vendor/plugins/geokit/init.rb @@ -0,0 +1,13 @@ +# Load modules and classes needed to automatically mix in ActiveRecord and +# ActionController helpers. All other functionality must be explicitly +# required. +require 'geo_kit/defaults' +require 'geo_kit/mappable' +require 'geo_kit/acts_as_mappable' +require 'geo_kit/ip_geocode_lookup' + +# Automatically mix in distance finder support into ActiveRecord classes. +ActiveRecord::Base.send :include, GeoKit::ActsAsMappable + +# Automatically mix in ip geocoding helpers into ActionController classes. +ActionController::Base.send :include, GeoKit::IpGeocodeLookup diff --git a/vendor/plugins/geokit/install.rb b/vendor/plugins/geokit/install.rb new file mode 100644 index 0000000..8263e22 --- /dev/null +++ b/vendor/plugins/geokit/install.rb @@ -0,0 +1,7 @@ +# Display to the console the contents of the README file. +puts IO.read(File.join(File.dirname(__FILE__), 'README')) + +# Append the contents of api_keys_template to the application's environment.rb file +environment_rb = File.open(File.expand_path(File.join(File.dirname(__FILE__), '../../../config/environment.rb')), "a") +environment_rb.puts IO.read(File.join(File.dirname(__FILE__), '/assets/api_keys_template')) +environment_rb.close diff --git a/vendor/plugins/geokit/lib/geo_kit/acts_as_mappable.rb b/vendor/plugins/geokit/lib/geo_kit/acts_as_mappable.rb new file mode 100644 index 0000000..a29f2be --- /dev/null +++ b/vendor/plugins/geokit/lib/geo_kit/acts_as_mappable.rb @@ -0,0 +1,436 @@ +module GeoKit + # Contains the class method acts_as_mappable targeted to be mixed into ActiveRecord. + # When mixed in, augments find services such that they provide distance calculation + # query services. The find method accepts additional options: + # + # * :origin - can be + # 1. a two-element array of latititude/longitude -- :origin=>[37.792,-122.393] + # 2. a geocodeable string -- :origin=>'100 Spear st, San Francisco, CA' + # 3. an object which responds to lat and lng methods, or latitude and longitude methods, + # or whatever methods you have specified for lng_column_name and lat_column_name + # + # Other finder methods are provided for specific queries. These are: + # + # * find_within (alias: find_inside) + # * find_beyond (alias: find_outside) + # * find_closest (alias: find_nearest) + # * find_farthest + # + # Counter methods are available and work similarly to finders. + # + # If raw SQL is desired, the distance_sql method can be used to obtain SQL appropriate + # to use in a find_by_sql call. + module ActsAsMappable + # Mix below class methods into ActiveRecord. + def self.included(base) # :nodoc: + base.extend ClassMethods + end + + # Class method to mix into active record. + module ClassMethods # :nodoc: + # Class method to bring distance query support into ActiveRecord models. By default + # uses :miles for distance units and performs calculations based upon the Haversine + # (sphere) formula. These can be changed by setting GeoKit::default_units and + # GeoKit::default_formula. Also, by default, uses lat, lng, and distance for respective + # column names. All of these can be overridden using the :default_units, :default_formula, + # :lat_column_name, :lng_column_name, and :distance_column_name hash keys. + # + # Can also use to auto-geocode a specific column on create. Syntax; + # + # acts_as_mappable :auto_geocode=>true + # + # By default, it tries to geocode the "address" field. Or, for more customized behavior: + # + # acts_as_mappable :auto_geocode=>{:field=>:address,:error_message=>'bad address'} + # + # In both cases, it creates a before_validation_on_create callback to geocode the given column. + # For anything more customized, we recommend you forgo the auto_geocode option + # and create your own AR callback to handle geocoding. + def acts_as_mappable(options = {}) + # Mix in the module, but ensure to do so just once. + return if self.included_modules.include?(GeoKit::ActsAsMappable::InstanceMethods) + send :include, GeoKit::ActsAsMappable::InstanceMethods + # include the Mappable module. + send :include, Mappable + + # Handle class variables. + cattr_accessor :distance_column_name, :default_units, :default_formula, :lat_column_name, :lng_column_name, :qualified_lat_column_name, :qualified_lng_column_name + self.distance_column_name = options[:distance_column_name] || 'distance' + self.default_units = options[:default_units] || GeoKit::default_units + self.default_formula = options[:default_formula] || GeoKit::default_formula + self.lat_column_name = options[:lat_column_name] || 'lat' + self.lng_column_name = options[:lng_column_name] || 'lng' + self.qualified_lat_column_name = "#{table_name}.#{lat_column_name}" + self.qualified_lng_column_name = "#{table_name}.#{lng_column_name}" + if options.include?(:auto_geocode) && options[:auto_geocode] + # if the form auto_geocode=>true is used, let the defaults take over by suppling an empty hash + options[:auto_geocode] = {} if options[:auto_geocode] == true + cattr_accessor :auto_geocode_field, :auto_geocode_error_message + self.auto_geocode_field = options[:auto_geocode][:field] || 'address' + self.auto_geocode_error_message = options[:auto_geocode][:error_message] || 'could not locate address' + + # set the actual callback here + before_validation_on_create :auto_geocode_address + end + end + end + + # this is the callback for auto_geocoding + def auto_geocode_address + address=self.send(auto_geocode_field) + geo=GeoKit::Geocoders::MultiGeocoder.geocode(address) + + if geo.success + self.send("#{lat_column_name}=", geo.lat) + self.send("#{lng_column_name}=", geo.lng) + else + errors.add(auto_geocode_field, auto_geocode_error_message) + end + + geo.success + end + + # Instance methods to mix into ActiveRecord. + module InstanceMethods #:nodoc: + # Mix class methods into module. + def self.included(base) # :nodoc: + base.extend SingletonMethods + end + + # Class singleton methods to mix into ActiveRecord. + module SingletonMethods # :nodoc: + # Extends the existing find method in potentially two ways: + # - If a mappable instance exists in the options, adds a distance column. + # - If a mappable instance exists in the options and the distance column exists in the + # conditions, substitutes the distance sql for the distance column -- this saves + # having to write the gory SQL. + def find(*args) + prepare_for_find_or_count(:find, args) + super(*args) + end + + # Extends the existing count method by: + # - If a mappable instance exists in the options and the distance column exists in the + # conditions, substitutes the distance sql for the distance column -- this saves + # having to write the gory SQL. + def count(*args) + prepare_for_find_or_count(:count, args) + super(*args) + end + + # Finds within a distance radius. + def find_within(distance, options={}) + options[:within] = distance + find(:all, options) + end + alias find_inside find_within + + # Finds beyond a distance radius. + def find_beyond(distance, options={}) + options[:beyond] = distance + find(:all, options) + end + alias find_outside find_beyond + + # Finds according to a range. Accepts inclusive or exclusive ranges. + def find_by_range(range, options={}) + options[:range] = range + find(:all, options) + end + + # Finds the closest to the origin. + def find_closest(options={}) + find(:nearest, options) + end + alias find_nearest find_closest + + # Finds the farthest from the origin. + def find_farthest(options={}) + find(:farthest, options) + end + + # Finds within rectangular bounds (sw,ne). + def find_within_bounds(bounds, options={}) + options[:bounds] = bounds + find(:all, options) + end + + # counts within a distance radius. + def count_within(distance, options={}) + options[:within] = distance + count(options) + end + alias count_inside count_within + + # Counts beyond a distance radius. + def count_beyond(distance, options={}) + options[:beyond] = distance + count(options) + end + alias count_outside count_beyond + + # Counts according to a range. Accepts inclusive or exclusive ranges. + def count_by_range(range, options={}) + options[:range] = range + count(options) + end + + # Finds within rectangular bounds (sw,ne). + def count_within_bounds(bounds, options={}) + options[:bounds] = bounds + count(options) + end + + # Returns the distance calculation to be used as a display column or a condition. This + # is provide for anyone wanting access to the raw SQL. + def distance_sql(origin, units=default_units, formula=default_formula) + case formula + when :sphere + sql = sphere_distance_sql(origin, units) + when :flat + sql = flat_distance_sql(origin, units) + end + sql + end + + private + + # Prepares either a find or a count action by parsing through the options and + # conditionally adding to the select clause for finders. + def prepare_for_find_or_count(action, args) + options = defined?(args.extract_options!) ? args.extract_options! : extract_options_from_args!(args) + # Obtain items affecting distance condition. + origin = extract_origin_from_options(options) + units = extract_units_from_options(options) + formula = extract_formula_from_options(options) + bounds = extract_bounds_from_options(options) + # if no explicit bounds were given, try formulating them from the point and distance given + bounds = formulate_bounds_from_distance(options, origin, units) unless bounds + # Apply select adjustments based upon action. + add_distance_to_select(options, origin, units, formula) if origin && action == :find + # Apply the conditions for a bounding rectangle if applicable + apply_bounds_conditions(options,bounds) if bounds + # Apply distance scoping and perform substitutions. + apply_distance_scope(options) + substitute_distance_in_conditions(options, origin, units, formula) if origin && options.has_key?(:conditions) + # Order by scoping for find action. + apply_find_scope(args, options) if action == :find + # Unfortunatley, we need to do extra work if you use an :include. See the method for more info. + handle_order_with_include(options,origin,units,formula) if options.include?(:include) && options.include?(:order) && origin + # Restore options minus the extra options that we used for the + # GeoKit API. + args.push(options) + end + + # If we're here, it means that 1) an origin argument, 2) an :include, 3) an :order clause were supplied. + # Now we have to sub some SQL into the :order clause. The reason is that when you do an :include, + # ActiveRecord drops the psuedo-column (specificically, distance) which we supplied for :select. + # So, the 'distance' column isn't available for the :order clause to reference when we use :include. + def handle_order_with_include(options, origin, units, formula) + # replace the distance_column_name with the distance sql in order clause + options[:order].sub!(distance_column_name, distance_sql(origin, units, formula)) + end + + # Looks for mapping-specific tokens and makes appropriate translations so that the + # original finder has its expected arguments. Resets the the scope argument to + # :first and ensures the limit is set to one. + def apply_find_scope(args, options) + case args.first + when :nearest, :closest + args[0] = :first + options[:limit] = 1 + options[:order] = "#{distance_column_name} ASC" + when :farthest + args[0] = :first + options[:limit] = 1 + options[:order] = "#{distance_column_name} DESC" + end + end + + # If it's a :within query, add a bounding box to improve performance. + # This only gets called if a :bounds argument is not otherwise supplied. + def formulate_bounds_from_distance(options, origin, units) + distance = options[:within] if options.has_key?(:within) + distance = options[:range].last-(options[:range].exclude_end?? 1 : 0) if options.has_key?(:range) + if distance + res=GeoKit::Bounds.from_point_and_radius(origin,distance,:units=>units) + else + nil + end + end + + # Replace :within, :beyond and :range distance tokens with the appropriate distance + # where clauses. Removes these tokens from the options hash. + def apply_distance_scope(options) + distance_condition = "#{distance_column_name} <= #{options[:within]}" if options.has_key?(:within) + distance_condition = "#{distance_column_name} > #{options[:beyond]}" if options.has_key?(:beyond) + distance_condition = "#{distance_column_name} >= #{options[:range].first} AND #{distance_column_name} <#{'=' unless options[:range].exclude_end?} #{options[:range].last}" if options.has_key?(:range) + [:within, :beyond, :range].each { |option| options.delete(option) } if distance_condition + + options[:conditions]=augment_conditions(options[:conditions],distance_condition) if distance_condition + end + + # This method lets you transparently add a new condition to a query without + # worrying about whether it currently has conditions, or what kind of conditions they are + # (string or array). + # + # Takes the current conditions (which can be an array or a string, or can be nil/false), + # and a SQL string. It inserts the sql into the existing conditions, and returns new conditions + # (which can be a string or an array + def augment_conditions(current_conditions,sql) + if current_conditions && current_conditions.is_a?(String) + res="#{current_conditions} AND #{sql}" + elsif current_conditions && current_conditions.is_a?(Array) + current_conditions[0]="#{current_conditions[0]} AND #{sql}" + res=current_conditions + else + res=sql + end + res + end + + # Alters the conditions to include rectangular bounds conditions. + def apply_bounds_conditions(options,bounds) + sw,ne=bounds.sw,bounds.ne + lng_sql= bounds.crosses_meridian? ? "(#{qualified_lng_column_name}<#{sw.lng} OR #{qualified_lng_column_name}>#{ne.lng})" : "#{qualified_lng_column_name}>#{sw.lng} AND #{qualified_lng_column_name}<#{ne.lng}" + bounds_sql="#{qualified_lat_column_name}>#{sw.lat} AND #{qualified_lat_column_name}<#{ne.lat} AND #{lng_sql}" + options[:conditions]=augment_conditions(options[:conditions],bounds_sql) + end + + # Extracts the origin instance out of the options if it exists and returns + # it. If there is no origin, looks for latitude and longitude values to + # create an origin. The side-effect of the method is to remove these + # option keys from the hash. + def extract_origin_from_options(options) + origin = options.delete(:origin) + res = normalize_point_to_lat_lng(origin) if origin + res + end + + # Extract the units out of the options if it exists and returns it. If + # there is no :units key, it uses the default. The side effect of the + # method is to remove the :units key from the options hash. + def extract_units_from_options(options) + units = options[:units] || default_units + options.delete(:units) + units + end + + # Extract the formula out of the options if it exists and returns it. If + # there is no :formula key, it uses the default. The side effect of the + # method is to remove the :formula key from the options hash. + def extract_formula_from_options(options) + formula = options[:formula] || default_formula + options.delete(:formula) + formula + end + + def extract_bounds_from_options(options) + bounds = options.delete(:bounds) + bounds = GeoKit::Bounds.normalize(bounds) if bounds + end + + # Geocode IP address. + def geocode_ip_address(origin) + geo_location = GeoKit::Geocoders::IpGeocoder.geocode(origin) + return geo_location if geo_location.success + raise GeoKit::Geocoders::GeocodeError + end + + + # Given a point in a variety of (an address to geocode, + # an array of [lat,lng], or an object with appropriate lat/lng methods, an IP addres) + # this method will normalize it into a GeoKit::LatLng instance. The only thing this + # method adds on top of LatLng#normalize is handling of IP addresses + def normalize_point_to_lat_lng(point) + res = geocode_ip_address(point) if point.is_a?(String) && /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})?$/.match(point) + res = GeoKit::LatLng.normalize(point) unless res + res + end + + # Augments the select with the distance SQL. + def add_distance_to_select(options, origin, units=default_units, formula=default_formula) + if origin + distance_selector = distance_sql(origin, units, formula) + " AS #{distance_column_name}" + selector = options.has_key?(:select) && options[:select] ? options[:select] : "*" + options[:select] = "#{selector}, #{distance_selector}" + end + end + + # Looks for the distance column and replaces it with the distance sql. If an origin was not + # passed in and the distance column exists, we leave it to be flagged as bad SQL by the database. + # Conditions are either a string or an array. In the case of an array, the first entry contains + # the condition. + def substitute_distance_in_conditions(options, origin, units=default_units, formula=default_formula) + original_conditions = options[:conditions] + condition = original_conditions.is_a?(String) ? original_conditions : original_conditions.first + pattern = Regexp.new("\s*#{distance_column_name}(\s<>=)*") + condition = condition.gsub(pattern, distance_sql(origin, units, formula)) + original_conditions = condition if original_conditions.is_a?(String) + original_conditions[0] = condition if original_conditions.is_a?(Array) + options[:conditions] = original_conditions + end + + # Returns the distance SQL using the spherical world formula (Haversine). The SQL is tuned + # to the database in use. + def sphere_distance_sql(origin, units) + lat = deg2rad(origin.lat) + lng = deg2rad(origin.lng) + multiplier = units_sphere_multiplier(units) + case connection.adapter_name.downcase + when "mysql" + sql=<<-SQL_END + (ACOS(least(1,COS(#{lat})*COS(#{lng})*COS(RADIANS(#{qualified_lat_column_name}))*COS(RADIANS(#{qualified_lng_column_name}))+ + COS(#{lat})*SIN(#{lng})*COS(RADIANS(#{qualified_lat_column_name}))*SIN(RADIANS(#{qualified_lng_column_name}))+ + SIN(#{lat})*SIN(RADIANS(#{qualified_lat_column_name}))))*#{multiplier}) + SQL_END + when "postgresql" + sql=<<-SQL_END + (ACOS(least(1,COS(#{lat})*COS(#{lng})*COS(RADIANS(#{qualified_lat_column_name}))*COS(RADIANS(#{qualified_lng_column_name}))+ + COS(#{lat})*SIN(#{lng})*COS(RADIANS(#{qualified_lat_column_name}))*SIN(RADIANS(#{qualified_lng_column_name}))+ + SIN(#{lat})*SIN(RADIANS(#{qualified_lat_column_name}))))*#{multiplier}) + SQL_END + else + sql = "unhandled #{connection.adapter_name.downcase} adapter" + end + end + + # Returns the distance SQL using the flat-world formula (Phythagorean Theory). The SQL is tuned + # to the database in use. + def flat_distance_sql(origin, units) + lat_degree_units = units_per_latitude_degree(units) + lng_degree_units = units_per_longitude_degree(origin.lat, units) + case connection.adapter_name.downcase + when "mysql" + sql=<<-SQL_END + SQRT(POW(#{lat_degree_units}*(#{origin.lat}-#{qualified_lat_column_name}),2)+ + POW(#{lng_degree_units}*(#{origin.lng}-#{qualified_lng_column_name}),2)) + SQL_END + when "postgresql" + sql=<<-SQL_END + SQRT(POW(#{lat_degree_units}*(#{origin.lat}-#{qualified_lat_column_name}),2)+ + POW(#{lng_degree_units}*(#{origin.lng}-#{qualified_lng_column_name}),2)) + SQL_END + else + sql = "unhandled #{connection.adapter_name.downcase} adapter" + end + end + end + end + end +end + +# Extend Array with a sort_by_distance method. +# This method creates a "distance" attribute on each object, +# calculates the distance from the passed origin, +# and finally sorts the array by the resulting distance. +class Array + def sort_by_distance_from(origin, opts={}) + distance_attribute_name = opts.delete(:distance_attribute_name) || 'distance' + self.each do |e| + e.class.send(:attr_accessor, distance_attribute_name) if !e.respond_to? "#{distance_attribute_name}=" + e.send("#{distance_attribute_name}=", origin.distance_to(e,opts)) + end + self.sort!{|a,b|a.send(distance_attribute_name) <=> b.send(distance_attribute_name)} + end +end \ No newline at end of file diff --git a/vendor/plugins/geokit/lib/geo_kit/defaults.rb b/vendor/plugins/geokit/lib/geo_kit/defaults.rb new file mode 100644 index 0000000..e9832c1 --- /dev/null +++ b/vendor/plugins/geokit/lib/geo_kit/defaults.rb @@ -0,0 +1,21 @@ +module GeoKit + # These defaults are used in GeoKit::Mappable.distance_to and in acts_as_mappable + @@default_units = :miles + @@default_formula = :sphere + + [:default_units, :default_formula].each do |sym| + class_eval <<-EOS, __FILE__, __LINE__ + def self.#{sym} + if defined?(#{sym.to_s.upcase}) + #{sym.to_s.upcase} + else + @@#{sym} + end + end + + def self.#{sym}=(obj) + @@#{sym} = obj + end + EOS + end +end diff --git a/vendor/plugins/geokit/lib/geo_kit/geocoders.rb b/vendor/plugins/geokit/lib/geo_kit/geocoders.rb new file mode 100644 index 0000000..54520b1 --- /dev/null +++ b/vendor/plugins/geokit/lib/geo_kit/geocoders.rb @@ -0,0 +1,348 @@ +require 'net/http' +require 'rexml/document' +require 'yaml' +require 'timeout' + +module GeoKit + # Contains a set of geocoders which can be used independently if desired. The list contains: + # + # * Google Geocoder - requires an API key. + # * Yahoo Geocoder - requires an API key. + # * Geocoder.us - may require authentication if performing more than the free request limit. + # * Geocoder.ca - for Canada; may require authentication as well. + # * IP Geocoder - geocodes an IP address using hostip.info's web service. + # * Multi Geocoder - provides failover for the physical location geocoders. + # + # Some configuration is required for these geocoders and can be located in the environment + # configuration files. + module Geocoders + @@proxy_addr = nil + @@proxy_port = nil + @@proxy_user = nil + @@proxy_pass = nil + @@timeout = nil + @@yahoo = 'REPLACE_WITH_YOUR_YAHOO_KEY' + @@google = 'REPLACE_WITH_YOUR_GOOGLE_KEY' + @@geocoder_us = false + @@geocoder_ca = false + @@provider_order = [:google,:us] + + [:yahoo, :google, :geocoder_us, :geocoder_ca, :provider_order, :timeout, + :proxy_addr, :proxy_port, :proxy_user, :proxy_pass].each do |sym| + class_eval <<-EOS, __FILE__, __LINE__ + def self.#{sym} + if defined?(#{sym.to_s.upcase}) + #{sym.to_s.upcase} + else + @@#{sym} + end + end + + def self.#{sym}=(obj) + @@#{sym} = obj + end + EOS + end + + # Error which is thrown in the event a geocoding error occurs. + class GeocodeError < StandardError; end + + # The Geocoder base class which defines the interface to be used by all + # other geocoders. + class Geocoder + # Main method which calls the do_geocode template method which subclasses + # are responsible for implementing. Returns a populated GeoLoc or an + # empty one with a failed success code. + def self.geocode(address) + res = do_geocode(address) + return res.success ? res : GeoLoc.new + end + + # Call the geocoder service using the timeout if configured. + def self.call_geocoder_service(url) + timeout(GeoKit::Geocoders::timeout) { return self.do_get(url) } if GeoKit::Geocoders::timeout + return self.do_get(url) + rescue TimeoutError + return nil + end + + protected + + def self.logger() RAILS_DEFAULT_LOGGER; end + + private + + # Wraps the geocoder call around a proxy if necessary. + def self.do_get(url) + return Net::HTTP::Proxy(GeoKit::Geocoders::proxy_addr, GeoKit::Geocoders::proxy_port, + GeoKit::Geocoders::proxy_user, GeoKit::Geocoders::proxy_pass).get_response(URI.parse(url)) + end + + # Adds subclass' geocode method making it conveniently available through + # the base class. + def self.inherited(clazz) + class_name = clazz.name.split('::').last + src = <<-END_SRC + def self.#{class_name.underscore}(address) + #{class_name}.geocode(address) + end + END_SRC + class_eval(src) + end + end + + # Geocoder CA geocoder implementation. Requires the GeoKit::Geocoders::GEOCODER_CA variable to + # contain true or false based upon whether authentication is to occur. Conforms to the + # interface set by the Geocoder class. + # + # Returns a response like: + # + # + # 49.243086 + # -123.153684 + # + class CaGeocoder < Geocoder + + private + + # Template method which does the geocode lookup. + def self.do_geocode(address) + raise ArgumentError('Geocoder.ca requires a GeoLoc argument') unless address.is_a?(GeoLoc) + url = construct_request(address) + res = self.call_geocoder_service(url) + return GeoLoc.new if !res.is_a?(Net::HTTPSuccess) + xml = res.body + logger.debug "Geocoder.ca geocoding. Address: #{address}. Result: #{xml}" + # Parse the document. + doc = REXML::Document.new(xml) + address.lat = doc.elements['//latt'].text + address.lng = doc.elements['//longt'].text + address.success = true + return address + rescue + logger.error "Caught an error during Geocoder.ca geocoding call: "+$! + return GeoLoc.new + end + + # Formats the request in the format acceptable by the CA geocoder. + def self.construct_request(location) + url = "" + url += add_ampersand(url) + "stno=#{location.street_number}" if location.street_address + url += add_ampersand(url) + "addresst=#{CGI.escape(location.street_name)}" if location.street_address + url += add_ampersand(url) + "city=#{CGI.escape(location.city)}" if location.city + url += add_ampersand(url) + "prov=#{location.state}" if location.state + url += add_ampersand(url) + "postal=#{location.zip}" if location.zip + url += add_ampersand(url) + "auth=#{GeoKit::Geocoders::geocoder_ca}" if GeoKit::Geocoders::geocoder_ca + url += add_ampersand(url) + "geoit=xml" + 'http://geocoder.ca/?' + url + end + + def self.add_ampersand(url) + url && url.length > 0 ? "&" : "" + end + end + + # Google geocoder implementation. Requires the GeoKit::Geocoders::GOOGLE variable to + # contain a Google API key. Conforms to the interface set by the Geocoder class. + class GoogleGeocoder < Geocoder + + private + + # Template method which does the geocode lookup. + def self.do_geocode(address) + address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address + res = self.call_geocoder_service("http://maps.google.com/maps/geo?q=#{CGI.escape(address_str)}&output=xml&key=#{GeoKit::Geocoders::google}&oe=utf-8") +# res = Net::HTTP.get_response(URI.parse("http://maps.google.com/maps/geo?q=#{CGI.escape(address_str)}&output=xml&key=#{GeoKit::Geocoders::google}&oe=utf-8")) + return GeoLoc.new if !res.is_a?(Net::HTTPSuccess) + xml=res.body + logger.debug "Google geocoding. Address: #{address}. Result: #{xml}" + doc=REXML::Document.new(xml) + + if doc.elements['//kml/Response/Status/code'].text == '200' + res = GeoLoc.new + coordinates=doc.elements['//coordinates'].text.to_s.split(',') + + #basics + res.lat=coordinates[1] + res.lng=coordinates[0] + res.country_code=doc.elements['//CountryNameCode'].text + res.provider='google' + + #extended -- false if not not available + res.city = doc.elements['//LocalityName'].text if doc.elements['//LocalityName'] + res.state = doc.elements['//AdministrativeAreaName'].text if doc.elements['//AdministrativeAreaName'] + res.full_address = doc.elements['//address'].text if doc.elements['//address'] # google provides it + res.zip = doc.elements['//PostalCodeNumber'].text if doc.elements['//PostalCodeNumber'] + res.street_address = doc.elements['//ThoroughfareName'].text if doc.elements['//ThoroughfareName'] + # Translate accuracy into Yahoo-style token address, street, zip, zip+4, city, state, country + # For Google, 1=low accuracy, 8=high accuracy + # old way -- address_details=doc.elements['//AddressDetails','urn:oasis:names:tc:ciq:xsdschema:xAL:2.0'] + address_details=doc.elements['//*[local-name() = "AddressDetails"]'] + accuracy = address_details ? address_details.attributes['Accuracy'].to_i : 0 + res.precision=%w{unknown country state state city zip zip+4 street address}[accuracy] + res.success=true + + return res + else + logger.info "Google was unable to geocode address: "+address + return GeoLoc.new + end + + rescue + logger.error "Caught an error during Google geocoding call: "+$! + return GeoLoc.new + end + end + + # Provides geocoding based upon an IP address. The underlying web service is a hostip.info + # which sources their data through a combination of publicly available information as well + # as community contributions. + class IpGeocoder < Geocoder + + private + + # Given an IP address, returns a GeoLoc instance which contains latitude, + # longitude, city, and country code. Sets the success attribute to false if the ip + # parameter does not match an ip address. + def self.do_geocode(ip) + return GeoLoc.new unless /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})?$/.match(ip) + url = "http://api.hostip.info/get_html.php?ip=#{ip}&position=true" + response = self.call_geocoder_service(url) + response.is_a?(Net::HTTPSuccess) ? parse_body(response.body) : GeoLoc.new + rescue + logger.error "Caught an error during HostIp geocoding call: "+$! + return GeoLoc.new + end + + # Converts the body to YAML since its in the form of: + # + # Country: UNITED STATES (US) + # City: Sugar Grove, IL + # Latitude: 41.7696 + # Longitude: -88.4588 + # + # then instantiates a GeoLoc instance to populate with location data. + def self.parse_body(body) # :nodoc: + yaml = YAML.load(body) + res = GeoLoc.new + res.provider = 'hostip' + res.city, res.state = yaml['City'].split(', ') + country, res.country_code = yaml['Country'].split(' (') + res.lat = yaml['Latitude'] + res.lng = yaml['Longitude'] + res.country_code.chop! + res.success = res.city != "(Private Address)" + res + end + end + + # Geocoder Us geocoder implementation. Requires the GeoKit::Geocoders::GEOCODER_US variable to + # contain true or false based upon whether authentication is to occur. Conforms to the + # interface set by the Geocoder class. + class UsGeocoder < Geocoder + + private + + # For now, the geocoder_method will only geocode full addresses -- not zips or cities in isolation + def self.do_geocode(address) + address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address + url = "http://"+(GeoKit::Geocoders::geocoder_us || '')+"geocoder.us/service/csv/geocode?address=#{CGI.escape(address_str)}" + res = self.call_geocoder_service(url) + return GeoLoc.new if !res.is_a?(Net::HTTPSuccess) + data = res.body + logger.debug "Geocoder.us geocoding. Address: #{address}. Result: #{data}" + array = data.chomp.split(',') + + if array.length == 6 + res=GeoLoc.new + res.lat,res.lng,res.street_address,res.city,res.state,res.zip=array + res.country_code='US' + res.success=true + return res + else + logger.info "geocoder.us was unable to geocode address: "+address + return GeoLoc.new + end + rescue + logger.error "Caught an error during geocoder.us geocoding call: "+$! + return GeoLoc.new + end + end + + # Yahoo geocoder implementation. Requires the GeoKit::Geocoders::YAHOO variable to + # contain a Yahoo API key. Conforms to the interface set by the Geocoder class. + class YahooGeocoder < Geocoder + + private + + # Template method which does the geocode lookup. + def self.do_geocode(address) + address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address + url="http://api.local.yahoo.com/MapsService/V1/geocode?appid=#{GeoKit::Geocoders::yahoo}&location=#{CGI.escape(address_str)}" + res = self.call_geocoder_service(url) + return GeoLoc.new if !res.is_a?(Net::HTTPSuccess) + xml = res.body + doc = REXML::Document.new(xml) + logger.debug "Yahoo geocoding. Address: #{address}. Result: #{xml}" + + if doc.elements['//ResultSet'] + res=GeoLoc.new + + #basic + res.lat=doc.elements['//Latitude'].text + res.lng=doc.elements['//Longitude'].text + res.country_code=doc.elements['//Country'].text + res.provider='yahoo' + + #extended - false if not available + res.city=doc.elements['//City'].text if doc.elements['//City'] && doc.elements['//City'].text != nil + res.state=doc.elements['//State'].text if doc.elements['//State'] && doc.elements['//State'].text != nil + res.zip=doc.elements['//Zip'].text if doc.elements['//Zip'] && doc.elements['//Zip'].text != nil + res.street_address=doc.elements['//Address'].text if doc.elements['//Address'] && doc.elements['//Address'].text != nil + res.precision=doc.elements['//Result'].attributes['precision'] if doc.elements['//Result'] + res.success=true + return res + else + logger.info "Yahoo was unable to geocode address: "+address + return GeoLoc.new + end + + rescue + logger.info "Caught an error during Yahoo geocoding call: "+$! + return GeoLoc.new + end + end + + # Provides methods to geocode with a variety of geocoding service providers, plus failover + # among providers in the order you configure. + # + # Goal: + # - homogenize the results of multiple geocoders + # + # Limitations: + # - currently only provides the first result. Sometimes geocoders will return multiple results. + # - currently discards the "accuracy" component of the geocoding calls + class MultiGeocoder < Geocoder + private + + # This method will call one or more geocoders in the order specified in the + # configuration until one of the geocoders work. + # + # The failover approach is crucial for production-grade apps, but is rarely used. + # 98% of your geocoding calls will be successful with the first call + def self.do_geocode(address) + GeoKit::Geocoders::provider_order.each do |provider| + begin + klass = GeoKit::Geocoders.const_get "#{provider.to_s.capitalize}Geocoder" + res = klass.send :geocode, address + return res if res.success + rescue + logger.error("Something has gone very wrong during geocoding, OR you have configured an invalid class name in GeoKit::Geocoders::provider_order. Address: #{address}. Provider: #{provider}") + end + end + # If we get here, we failed completely. + GeoLoc.new + end + end + end +end \ No newline at end of file diff --git a/vendor/plugins/geokit/lib/geo_kit/ip_geocode_lookup.rb b/vendor/plugins/geokit/lib/geo_kit/ip_geocode_lookup.rb new file mode 100644 index 0000000..3d630ea --- /dev/null +++ b/vendor/plugins/geokit/lib/geo_kit/ip_geocode_lookup.rb @@ -0,0 +1,46 @@ +require 'yaml' + +module GeoKit + # Contains a class method geocode_ip_address which can be used to enable automatic geocoding + # for request IP addresses. The geocoded information is stored in a cookie and in the + # session to minimize web service calls. The point of the helper is to enable location-based + # websites to have a best-guess for new visitors. + module IpGeocodeLookup + # Mix below class methods into ActionController. + def self.included(base) # :nodoc: + base.extend ClassMethods + end + + # Class method to mix into active record. + module ClassMethods # :nodoc: + def geocode_ip_address(filter_options = {}) + before_filter :store_ip_location, filter_options + end + end + + private + + # Places the IP address' geocode location into the session if it + # can be found. Otherwise, looks for a geo location cookie and + # uses that value. The last resort is to call the web service to + # get the value. + def store_ip_location + session[:geo_location] ||= retrieve_location_from_cookie_or_service + cookies[:geo_location] = { :value => session[:geo_location].to_yaml, :expires => 30.days.from_now } if session[:geo_location] + end + + # Uses the stored location value from the cookie if it exists. If + # no cookie exists, calls out to the web service to get the location. + def retrieve_location_from_cookie_or_service + return YAML.load(cookies[:geo_location]) if cookies[:geo_location] + location = Geocoders::IpGeocoder.geocode(get_ip_address) + return location.success ? location : nil + end + + # Returns the real ip address, though this could be the localhost ip + # address. No special handling here anymore. + def get_ip_address + request.remote_ip + end + end +end \ No newline at end of file diff --git a/vendor/plugins/geokit/lib/geo_kit/mappable.rb b/vendor/plugins/geokit/lib/geo_kit/mappable.rb new file mode 100644 index 0000000..b6434c8 --- /dev/null +++ b/vendor/plugins/geokit/lib/geo_kit/mappable.rb @@ -0,0 +1,432 @@ +require 'geo_kit/defaults' + +module GeoKit + # Contains class and instance methods providing distance calcuation services. This + # module is meant to be mixed into classes containing lat and lng attributes where + # distance calculation is desired. + # + # At present, two forms of distance calculations are provided: + # + # * Pythagorean Theory (flat Earth) - which assumes the world is flat and loses accuracy over long distances. + # * Haversine (sphere) - which is fairly accurate, but at a performance cost. + # + # Distance units supported are :miles and :kms. + module Mappable + PI_DIV_RAD = 0.0174 + KMS_PER_MILE = 1.609 + EARTH_RADIUS_IN_MILES = 3963.19 + EARTH_RADIUS_IN_KMS = EARTH_RADIUS_IN_MILES * KMS_PER_MILE + MILES_PER_LATITUDE_DEGREE = 69.1 + KMS_PER_LATITUDE_DEGREE = MILES_PER_LATITUDE_DEGREE * KMS_PER_MILE + LATITUDE_DEGREES = EARTH_RADIUS_IN_MILES / MILES_PER_LATITUDE_DEGREE + + # Mix below class methods into the includer. + def self.included(receiver) # :nodoc: + receiver.extend ClassMethods + end + + module ClassMethods #:nodoc: + # Returns the distance between two points. The from and to parameters are + # required to have lat and lng attributes. Valid options are: + # :units - valid values are :miles or :kms (GeoKit::default_units is the default) + # :formula - valid values are :flat or :sphere (GeoKit::default_formula is the default) + def distance_between(from, to, options={}) + from=GeoKit::LatLng.normalize(from) + to=GeoKit::LatLng.normalize(to) + return 0.0 if from == to # fixes a "zero-distance" bug + units = options[:units] || GeoKit::default_units + formula = options[:formula] || GeoKit::default_formula + case formula + when :sphere + units_sphere_multiplier(units) * + Math.acos( Math.sin(deg2rad(from.lat)) * Math.sin(deg2rad(to.lat)) + + Math.cos(deg2rad(from.lat)) * Math.cos(deg2rad(to.lat)) * + Math.cos(deg2rad(to.lng) - deg2rad(from.lng))) + when :flat + Math.sqrt((units_per_latitude_degree(units)*(from.lat-to.lat))**2 + + (units_per_longitude_degree(from.lat, units)*(from.lng-to.lng))**2) + end + end + + # Returns heading in degrees (0 is north, 90 is east, 180 is south, etc) + # from the first point to the second point. Typicaly, the instance methods will be used + # instead of this method. + def heading_between(from,to) + from=GeoKit::LatLng.normalize(from) + to=GeoKit::LatLng.normalize(to) + + d_lng=deg2rad(to.lng-from.lng) + from_lat=deg2rad(from.lat) + to_lat=deg2rad(to.lat) + y=Math.sin(d_lng) * Math.cos(to_lat) + x=Math.cos(from_lat)*Math.sin(to_lat)-Math.sin(from_lat)*Math.cos(to_lat)*Math.cos(d_lng) + heading=to_heading(Math.atan2(y,x)) + end + + # Given a start point, distance, and heading (in degrees), provides + # an endpoint. Returns a LatLng instance. Typically, the instance method + # will be used instead of this method. + def endpoint(start,heading, distance, options={}) + units = options[:units] || GeoKit::default_units + radius = units == :miles ? EARTH_RADIUS_IN_MILES : EARTH_RADIUS_IN_KMS + start=GeoKit::LatLng.normalize(start) + lat=deg2rad(start.lat) + lng=deg2rad(start.lng) + heading=deg2rad(heading) + distance=distance.to_f + + end_lat=Math.asin(Math.sin(lat)*Math.cos(distance/radius) + + Math.cos(lat)*Math.sin(distance/radius)*Math.cos(heading)) + + end_lng=lng+Math.atan2(Math.sin(heading)*Math.sin(distance/radius)*Math.cos(lat), + Math.cos(distance/radius)-Math.sin(lat)*Math.sin(end_lat)) + + LatLng.new(rad2deg(end_lat),rad2deg(end_lng)) + end + + # Returns the midpoint, given two points. Returns a LatLng. + # Typically, the instance method will be used instead of this method. + # Valid option: + # :units - valid values are :miles or :kms (:miles is the default) + def midpoint_between(from,to,options={}) + from=GeoKit::LatLng.normalize(from) + + units = options[:units] || GeoKit::default_units + + heading=from.heading_to(to) + distance=from.distance_to(to,options) + midpoint=from.endpoint(heading,distance/2,options) + end + + # Geocodes a location using the multi geocoder. + def geocode(location) + res = Geocoders::MultiGeocoder.geocode(location) + return res if res.success + raise GeoKit::Geocoders::GeocodeError + end + + protected + + def deg2rad(degrees) + degrees.to_f / 180.0 * Math::PI + end + + def rad2deg(rad) + rad.to_f * 180.0 / Math::PI + end + + def to_heading(rad) + (rad2deg(rad)+360)%360 + end + + # Returns the multiplier used to obtain the correct distance units. + def units_sphere_multiplier(units) + units == :miles ? EARTH_RADIUS_IN_MILES : EARTH_RADIUS_IN_KMS + end + + # Returns the number of units per latitude degree. + def units_per_latitude_degree(units) + units == :miles ? MILES_PER_LATITUDE_DEGREE : KMS_PER_LATITUDE_DEGREE + end + + # Returns the number units per longitude degree. + def units_per_longitude_degree(lat, units) + miles_per_longitude_degree = (LATITUDE_DEGREES * Math.cos(lat * PI_DIV_RAD)).abs + units == :miles ? miles_per_longitude_degree : miles_per_longitude_degree * KMS_PER_MILE + end + end + + # ----------------------------------------------------------------------------------------------- + # Instance methods below here + # ----------------------------------------------------------------------------------------------- + + # Extracts a LatLng instance. Use with models that are acts_as_mappable + def to_lat_lng + return self if instance_of?(GeoKit::LatLng) || instance_of?(GeoKit::GeoLoc) + return LatLng.new(send(self.class.lat_column_name),send(self.class.lng_column_name)) if self.class.respond_to?(:acts_as_mappable) + return nil + end + + # Returns the distance from another point. The other point parameter is + # required to have lat and lng attributes. Valid options are: + # :units - valid values are :miles or :kms (:miles is the default) + # :formula - valid values are :flat or :sphere (:sphere is the default) + def distance_to(other, options={}) + self.class.distance_between(self, other, options) + end + alias distance_from distance_to + + # Returns heading in degrees (0 is north, 90 is east, 180 is south, etc) + # to the given point. The given point can be a LatLng or a string to be Geocoded + def heading_to(other) + self.class.heading_between(self,other) + end + + # Returns heading in degrees (0 is north, 90 is east, 180 is south, etc) + # FROM the given point. The given point can be a LatLng or a string to be Geocoded + def heading_from(other) + self.class.heading_between(other,self) + end + + # Returns the endpoint, given a heading (in degrees) and distance. + # Valid option: + # :units - valid values are :miles or :kms (:miles is the default) + def endpoint(heading,distance,options={}) + self.class.endpoint(self,heading,distance,options) + end + + # Returns the midpoint, given another point on the map. + # Valid option: + # :units - valid values are :miles or :kms (:miles is the default) + def midpoint_to(other, options={}) + self.class.midpoint_between(self,other,options) + end + + end + + class LatLng + include Mappable + + attr_accessor :lat, :lng + + # Accepts latitude and longitude or instantiates an empty instance + # if lat and lng are not provided. Converted to floats if provided + def initialize(lat=nil, lng=nil) + lat = lat.to_f if lat && !lat.is_a?(Numeric) + lng = lng.to_f if lng && !lng.is_a?(Numeric) + @lat = lat + @lng = lng + end + + # Latitude attribute setter; stored as a float. + def lat=(lat) + @lat = lat.to_f if lat + end + + # Longitude attribute setter; stored as a float; + def lng=(lng) + @lng=lng.to_f if lng + end + + # Returns the lat and lng attributes as a comma-separated string. + def ll + "#{lat},#{lng}" + end + + #returns a string with comma-separated lat,lng values + def to_s + ll + end + + #returns a two-element array + def to_a + [lat,lng] + end + # Returns true if the candidate object is logically equal. Logical equivalence + # is true if the lat and lng attributes are the same for both objects. + def ==(other) + other.is_a?(LatLng) ? self.lat == other.lat && self.lng == other.lng : false + end + + # A *class* method to take anything which can be inferred as a point and generate + # a LatLng from it. You should use this anything you're not sure what the input is, + # and want to deal with it as a LatLng if at all possible. Can take: + # 1) two arguments (lat,lng) + # 2) a string in the format "37.1234,-129.1234" or "37.1234 -129.1234" + # 3) a string which can be geocoded on the fly + # 4) an array in the format [37.1234,-129.1234] + # 5) a LatLng or GeoLoc (which is just passed through as-is) + # 6) anything which acts_as_mappable -- a LatLng will be extracted from it + def self.normalize(thing,other=nil) + # if an 'other' thing is supplied, normalize the input by creating an array of two elements + thing=[thing,other] if other + + if thing.is_a?(String) + thing.strip! + if match=thing.match(/(\-?\d+\.?\d*)[, ] ?(\-?\d+\.?\d*)$/) + return GeoKit::LatLng.new(match[1],match[2]) + else + res = GeoKit::Geocoders::MultiGeocoder.geocode(thing) + return res if res.success + raise GeoKit::Geocoders::GeocodeError + end + elsif thing.is_a?(Array) && thing.size==2 + return GeoKit::LatLng.new(thing[0],thing[1]) + elsif thing.is_a?(LatLng) # will also be true for GeoLocs + return thing + elsif thing.class.respond_to?(:acts_as_mappable) && thing.class.respond_to?(:distance_column_name) + return thing.to_lat_lng + end + + throw ArgumentError.new("#{thing} (#{thing.class}) cannot be normalized to a LatLng. We tried interpreting it as an array, string, Mappable, etc., but no dice.") + end + + end + + # This class encapsulates the result of a geocoding call + # It's primary purpose is to homogenize the results of multiple + # geocoding providers. It also provides some additional functionality, such as + # the "full address" method for geocoders that do not provide a + # full address in their results (for example, Yahoo), and the "is_us" method. + class GeoLoc < LatLng + # Location attributes. Full address is a concatenation of all values. For example: + # 100 Spear St, San Francisco, CA, 94101, US + attr_accessor :street_address, :city, :state, :zip, :country_code, :full_address + # Attributes set upon return from geocoding. Success will be true for successful + # geocode lookups. The provider will be set to the name of the providing geocoder. + # Finally, precision is an indicator of the accuracy of the geocoding. + attr_accessor :success, :provider, :precision + # Street number and street name are extracted from the street address attribute. + attr_reader :street_number, :street_name + + # Constructor expects a hash of symbols to correspond with attributes. + def initialize(h={}) + @street_address=h[:street_address] + @city=h[:city] + @state=h[:state] + @zip=h[:zip] + @country_code=h[:country_code] + @success=false + @precision='unknown' + super(h[:lat],h[:lng]) + end + + # Returns true if geocoded to the United States. + def is_us? + country_code == 'US' + end + + # full_address is provided by google but not by yahoo. It is intended that the google + # geocoding method will provide the full address, whereas for yahoo it will be derived + # from the parts of the address we do have. + def full_address + @full_address ? @full_address : to_geocodeable_s + end + + # Extracts the street number from the street address if the street address + # has a value. + def street_number + street_address[/(\d*)/] if street_address + end + + # Returns the street name portion of the street address. + def street_name + street_address[street_number.length, street_address.length].strip if street_address + end + + # gives you all the important fields as key-value pairs + def hash + res={} + [:success,:lat,:lng,:country_code,:city,:state,:zip,:street_address,:provider,:full_address,:is_us?,:ll,:precision].each { |s| res[s] = self.send(s.to_s) } + res + end + alias to_hash hash + + # Sets the city after capitalizing each word within the city name. + def city=(city) + @city = city.titleize if city + end + + # Sets the street address after capitalizing each word within the street address. + def street_address=(address) + @street_address = address.titleize if address + end + + # Returns a comma-delimited string consisting of the street address, city, state, + # zip, and country code. Only includes those attributes that are non-blank. + def to_geocodeable_s + a=[street_address, city, state, zip, country_code].compact + a.delete_if { |e| !e || e == '' } + a.join(', ') + end + + # Returns a string representation of the instance. + def to_s + "Provider: #{provider}\n Street: #{street_address}\nCity: #{city}\nState: #{state}\nZip: #{zip}\nLatitude: #{lat}\nLongitude: #{lng}\nCountry: #{country_code}\nSuccess: #{success}" + end + end + + # Bounds represents a rectangular bounds, defined by the SW and NE corners + class Bounds + # sw and ne are LatLng objects + attr_accessor :sw, :ne + + # provide sw and ne to instantiate a new Bounds instance + def initialize(sw,ne) + raise ArguementError if !(sw.is_a?(GeoKit::LatLng) && ne.is_a?(GeoKit::LatLng)) + @sw,@ne=sw,ne + end + + #returns the a single point which is the center of the rectangular bounds + def center + @sw.midpoint_to(@ne) + end + + # a simple string representation:sw,ne + def to_s + "#{@sw.to_s},#{@ne.to_s}" + end + + # a two-element array of two-element arrays: sw,ne + def to_a + [@sw.to_a, @ne.to_a] + end + + # Returns true if the bounds contain the passed point. + # allows for bounds which cross the meridian + def contains?(point) + point=GeoKit::LatLng.normalize(point) + res = point.lat > @sw.lat && point.lat < @ne.lat + if crosses_meridian? + res &= point.lng < @ne.lng || point.lng > @sw.lng + else + res &= point.lng < @ne.lng && point.lng > @sw.lng + end + res + end + + # returns true if the bounds crosses the international dateline + def crosses_meridian? + @sw.lng > @ne.lng + end + + # Returns true if the candidate object is logically equal. Logical equivalence + # is true if the lat and lng attributes are the same for both objects. + def ==(other) + other.is_a?(Bounds) ? self.sw == other.sw && self.ne == other.ne : false + end + + class <true +end + +# Uses deviations from conventions. +class CustomLocation < ActiveRecord::Base #:nodoc: all + belongs_to :company + acts_as_mappable :distance_column_name => 'dist', + :default_units => :kms, + :default_formula => :flat, + :lat_column_name => 'latitude', + :lng_column_name => 'longitude' + + def to_s + "lat: #{latitude} lng: #{longitude} dist: #{dist}" + end +end + +class ActsAsMappableTest < Test::Unit::TestCase #:nodoc: all + + LOCATION_A_IP = "217.10.83.5" + + #self.fixture_path = File.dirname(__FILE__) + '/fixtures' + #self.fixture_path = RAILS_ROOT + '/test/fixtures/' + #puts "Rails Path #{RAILS_ROOT}" + #puts "Fixture Path: #{self.fixture_path}" + #self.fixture_path = ' /Users/bill_eisenhauer/Projects/geokit_test/test/fixtures/' + fixtures :companies, :locations, :custom_locations, :stores + + def setup + @location_a = GeoKit::GeoLoc.new + @location_a.lat = 32.918593 + @location_a.lng = -96.958444 + @location_a.city = "Irving" + @location_a.state = "TX" + @location_a.country_code = "US" + @location_a.success = true + + @sw = GeoKit::LatLng.new(32.91663,-96.982841) + @ne = GeoKit::LatLng.new(32.96302,-96.919495) + @bounds_center=GeoKit::LatLng.new((@sw.lat+@ne.lat)/2,(@sw.lng+@ne.lng)/2) + + @starbucks = companies(:starbucks) + @loc_a = locations(:a) + @custom_loc_a = custom_locations(:a) + @loc_e = locations(:e) + @custom_loc_e = custom_locations(:e) + end + + def test_override_default_units_the_hard_way + Location.default_units = :kms + locations = Location.find(:all, :origin => @loc_a, :conditions => "distance < 3.97") + assert_equal 5, locations.size + locations = Location.count(:origin => @loc_a, :conditions => "distance < 3.97") + assert_equal 5, locations + Location.default_units = :miles + end + + def test_include + locations = Location.find(:all, :origin => @loc_a, :include => :company, :conditions => "company_id = 1") + assert !locations.empty? + assert_equal 1, locations[0].company.id + assert_equal 'Starbucks', locations[0].company.name + end + + def test_distance_between_geocoded + GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("Irving, TX").returns(@location_a) + GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("San Francisco, CA").returns(@location_a) + assert_equal 0, Location.distance_between("Irving, TX", "San Francisco, CA") + end + + def test_distance_to_geocoded + GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("Irving, TX").returns(@location_a) + assert_equal 0, @custom_loc_a.distance_to("Irving, TX") + end + + def test_distance_to_geocoded_error + GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("Irving, TX").returns(GeoKit::GeoLoc.new) + assert_raise(GeoKit::Geocoders::GeocodeError) { @custom_loc_a.distance_to("Irving, TX") } + end + + def test_custom_attributes_distance_calculations + assert_equal 0, @custom_loc_a.distance_to(@loc_a) + assert_equal 0, CustomLocation.distance_between(@custom_loc_a, @loc_a) + end + + def test_distance_column_in_select + locations = Location.find(:all, :origin => @loc_a, :order => "distance ASC") + assert_equal 6, locations.size + assert_equal 0, @loc_a.distance_to(locations.first) + assert_in_delta 3.97, @loc_a.distance_to(locations.last, :units => :miles, :formula => :sphere), 0.01 + end + + def test_find_with_distance_condition + locations = Location.find(:all, :origin => @loc_a, :conditions => "distance < 3.97") + assert_equal 5, locations.size + locations = Location.count(:origin => @loc_a, :conditions => "distance < 3.97") + assert_equal 5, locations + end + + def test_find_with_distance_condition_with_units_override + locations = Location.find(:all, :origin => @loc_a, :units => :kms, :conditions => "distance < 6.387") + assert_equal 5, locations.size + locations = Location.count(:origin => @loc_a, :units => :kms, :conditions => "distance < 6.387") + assert_equal 5, locations + end + + def test_find_with_distance_condition_with_formula_override + locations = Location.find(:all, :origin => @loc_a, :formula => :flat, :conditions => "distance < 6.387") + assert_equal 6, locations.size + locations = Location.count(:origin => @loc_a, :formula => :flat, :conditions => "distance < 6.387") + assert_equal 6, locations + end + + def test_find_within + locations = Location.find_within(3.97, :origin => @loc_a) + assert_equal 5, locations.size + locations = Location.count_within(3.97, :origin => @loc_a) + assert_equal 5, locations + end + + def test_find_within_with_token + locations = Location.find(:all, :within => 3.97, :origin => @loc_a) + assert_equal 5, locations.size + locations = Location.count(:within => 3.97, :origin => @loc_a) + assert_equal 5, locations + end + + def test_find_within_with_coordinates + locations = Location.find_within(3.97, :origin =>[@loc_a.lat,@loc_a.lng]) + assert_equal 5, locations.size + locations = Location.count_within(3.97, :origin =>[@loc_a.lat,@loc_a.lng]) + assert_equal 5, locations + end + + def test_find_with_compound_condition + locations = Location.find(:all, :origin => @loc_a, :conditions => "distance < 5 and city = 'Coppell'") + assert_equal 2, locations.size + locations = Location.count(:origin => @loc_a, :conditions => "distance < 5 and city = 'Coppell'") + assert_equal 2, locations + end + + def test_find_with_secure_compound_condition + locations = Location.find(:all, :origin => @loc_a, :conditions => ["distance < ? and city = ?", 5, 'Coppell']) + assert_equal 2, locations.size + locations = Location.count(:origin => @loc_a, :conditions => ["distance < ? and city = ?", 5, 'Coppell']) + assert_equal 2, locations + end + + def test_find_beyond + locations = Location.find_beyond(3.95, :origin => @loc_a) + assert_equal 1, locations.size + locations = Location.count_beyond(3.95, :origin => @loc_a) + assert_equal 1, locations + end + + def test_find_beyond_with_token + locations = Location.find(:all, :beyond => 3.95, :origin => @loc_a) + assert_equal 1, locations.size + locations = Location.count(:beyond => 3.95, :origin => @loc_a) + assert_equal 1, locations + end + + def test_find_beyond_with_coordinates + locations = Location.find_beyond(3.95, :origin =>[@loc_a.lat, @loc_a.lng]) + assert_equal 1, locations.size + locations = Location.count_beyond(3.95, :origin =>[@loc_a.lat, @loc_a.lng]) + assert_equal 1, locations + end + + def test_find_range_with_token + locations = Location.find(:all, :range => 0..10, :origin => @loc_a) + assert_equal 6, locations.size + locations = Location.count(:range => 0..10, :origin => @loc_a) + assert_equal 6, locations + end + + def test_find_range_with_token_with_conditions + locations = Location.find(:all, :origin => @loc_a, :range => 0..10, :conditions => ["city = ?", 'Coppell']) + assert_equal 2, locations.size + locations = Location.count(:origin => @loc_a, :range => 0..10, :conditions => ["city = ?", 'Coppell']) + assert_equal 2, locations + end + + def test_find_range_with_token_excluding_end + locations = Location.find(:all, :range => 0...10, :origin => @loc_a) + assert_equal 6, locations.size + locations = Location.count(:range => 0...10, :origin => @loc_a) + assert_equal 6, locations + end + + def test_find_nearest + assert_equal @loc_a, Location.find_nearest(:origin => @loc_a) + end + + def test_find_nearest_through_find + assert_equal @loc_a, Location.find(:nearest, :origin => @loc_a) + end + + def test_find_nearest_with_coordinates + assert_equal @loc_a, Location.find_nearest(:origin =>[@loc_a.lat, @loc_a.lng]) + end + + def test_find_farthest + assert_equal @loc_e, Location.find_farthest(:origin => @loc_a) + end + + def test_find_farthest_through_find + assert_equal @loc_e, Location.find(:farthest, :origin => @loc_a) + end + + def test_find_farthest_with_coordinates + assert_equal @loc_e, Location.find_farthest(:origin =>[@loc_a.lat, @loc_a.lng]) + end + + def test_scoped_distance_column_in_select + locations = @starbucks.locations.find(:all, :origin => @loc_a, :order => "distance ASC") + assert_equal 5, locations.size + assert_equal 0, @loc_a.distance_to(locations.first) + assert_in_delta 3.97, @loc_a.distance_to(locations.last, :units => :miles, :formula => :sphere), 0.01 + end + + def test_scoped_find_with_distance_condition + locations = @starbucks.locations.find(:all, :origin => @loc_a, :conditions => "distance < 3.97") + assert_equal 4, locations.size + locations = @starbucks.locations.count(:origin => @loc_a, :conditions => "distance < 3.97") + assert_equal 4, locations + end + + def test_scoped_find_within + locations = @starbucks.locations.find_within(3.97, :origin => @loc_a) + assert_equal 4, locations.size + locations = @starbucks.locations.count_within(3.97, :origin => @loc_a) + assert_equal 4, locations + end + + def test_scoped_find_with_compound_condition + locations = @starbucks.locations.find(:all, :origin => @loc_a, :conditions => "distance < 5 and city = 'Coppell'") + assert_equal 2, locations.size + locations = @starbucks.locations.count( :origin => @loc_a, :conditions => "distance < 5 and city = 'Coppell'") + assert_equal 2, locations + end + + def test_scoped_find_beyond + locations = @starbucks.locations.find_beyond(3.95, :origin => @loc_a) + assert_equal 1, locations.size + locations = @starbucks.locations.count_beyond(3.95, :origin => @loc_a) + assert_equal 1, locations + end + + def test_scoped_find_nearest + assert_equal @loc_a, @starbucks.locations.find_nearest(:origin => @loc_a) + end + + def test_scoped_find_farthest + assert_equal @loc_e, @starbucks.locations.find_farthest(:origin => @loc_a) + end + + def test_ip_geocoded_distance_column_in_select + GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a) + locations = Location.find(:all, :origin => LOCATION_A_IP, :order => "distance ASC") + assert_equal 6, locations.size + assert_equal 0, @loc_a.distance_to(locations.first) + assert_in_delta 3.97, @loc_a.distance_to(locations.last, :units => :miles, :formula => :sphere), 0.01 + end + + def test_ip_geocoded_find_with_distance_condition + GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a) + locations = Location.find(:all, :origin => LOCATION_A_IP, :conditions => "distance < 3.97") + assert_equal 5, locations.size + GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a) + locations = Location.count(:origin => LOCATION_A_IP, :conditions => "distance < 3.97") + assert_equal 5, locations + end + + def test_ip_geocoded_find_within + GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a) + locations = Location.find_within(3.97, :origin => LOCATION_A_IP) + assert_equal 5, locations.size + GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a) + locations = Location.count_within(3.97, :origin => LOCATION_A_IP) + assert_equal 5, locations + end + + def test_ip_geocoded_find_with_compound_condition + GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a) + locations = Location.find(:all, :origin => LOCATION_A_IP, :conditions => "distance < 5 and city = 'Coppell'") + assert_equal 2, locations.size + GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a) + locations = Location.count(:origin => LOCATION_A_IP, :conditions => "distance < 5 and city = 'Coppell'") + assert_equal 2, locations + end + + def test_ip_geocoded_find_with_secure_compound_condition + GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a) + locations = Location.find(:all, :origin => LOCATION_A_IP, :conditions => ["distance < ? and city = ?", 5, 'Coppell']) + assert_equal 2, locations.size + GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a) + locations = Location.count(:origin => LOCATION_A_IP, :conditions => ["distance < ? and city = ?", 5, 'Coppell']) + assert_equal 2, locations + end + + def test_ip_geocoded_find_beyond + GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a) + locations = Location.find_beyond(3.95, :origin => LOCATION_A_IP) + assert_equal 1, locations.size + GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a) + locations = Location.count_beyond(3.95, :origin => LOCATION_A_IP) + assert_equal 1, locations + end + + def test_ip_geocoded_find_nearest + GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a) + assert_equal @loc_a, Location.find_nearest(:origin => LOCATION_A_IP) + end + + def test_ip_geocoded_find_farthest + GeoKit::Geocoders::IpGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a) + assert_equal @loc_e, Location.find_farthest(:origin => LOCATION_A_IP) + end + + def test_ip_geocoder_exception + GeoKit::Geocoders::IpGeocoder.expects(:geocode).with('127.0.0.1').returns(GeoKit::GeoLoc.new) + assert_raises GeoKit::Geocoders::GeocodeError do + Location.find_farthest(:origin => '127.0.0.1') + end + end + + def test_address_geocode + GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with('Irving, TX').returns(@location_a) + locations = Location.find(:all, :origin => 'Irving, TX', :conditions => ["distance < ? and city = ?", 5, 'Coppell']) + assert_equal 2, locations.size + end + + def test_find_with_custom_distance_condition + locations = CustomLocation.find(:all, :origin => @loc_a, :conditions => "dist < 3.97") + assert_equal 5, locations.size + locations = CustomLocation.count(:origin => @loc_a, :conditions => "dist < 3.97") + assert_equal 5, locations + end + + def test_find_with_custom_distance_condition_using_custom_origin + locations = CustomLocation.find(:all, :origin => @custom_loc_a, :conditions => "dist < 3.97") + assert_equal 5, locations.size + locations = CustomLocation.count(:origin => @custom_loc_a, :conditions => "dist < 3.97") + assert_equal 5, locations + end + + def test_find_within_with_custom + locations = CustomLocation.find_within(3.97, :origin => @loc_a) + assert_equal 5, locations.size + locations = CustomLocation.count_within(3.97, :origin => @loc_a) + assert_equal 5, locations + end + + def test_find_within_with_coordinates_with_custom + locations = CustomLocation.find_within(3.97, :origin =>[@loc_a.lat, @loc_a.lng]) + assert_equal 5, locations.size + locations = CustomLocation.count_within(3.97, :origin =>[@loc_a.lat, @loc_a.lng]) + assert_equal 5, locations + end + + def test_find_with_compound_condition_with_custom + locations = CustomLocation.find(:all, :origin => @loc_a, :conditions => "dist < 5 and city = 'Coppell'") + assert_equal 1, locations.size + locations = CustomLocation.count(:origin => @loc_a, :conditions => "dist < 5 and city = 'Coppell'") + assert_equal 1, locations + end + + def test_find_with_secure_compound_condition_with_custom + locations = CustomLocation.find(:all, :origin => @loc_a, :conditions => ["dist < ? and city = ?", 5, 'Coppell']) + assert_equal 1, locations.size + locations = CustomLocation.count(:origin => @loc_a, :conditions => ["dist < ? and city = ?", 5, 'Coppell']) + assert_equal 1, locations + end + + def test_find_beyond_with_custom + locations = CustomLocation.find_beyond(3.95, :origin => @loc_a) + assert_equal 1, locations.size + locations = CustomLocation.count_beyond(3.95, :origin => @loc_a) + assert_equal 1, locations + end + + def test_find_beyond_with_coordinates_with_custom + locations = CustomLocation.find_beyond(3.95, :origin =>[@loc_a.lat, @loc_a.lng]) + assert_equal 1, locations.size + locations = CustomLocation.count_beyond(3.95, :origin =>[@loc_a.lat, @loc_a.lng]) + assert_equal 1, locations + end + + def test_find_nearest_with_custom + assert_equal @custom_loc_a, CustomLocation.find_nearest(:origin => @loc_a) + end + + def test_find_nearest_with_coordinates_with_custom + assert_equal @custom_loc_a, CustomLocation.find_nearest(:origin =>[@loc_a.lat, @loc_a.lng]) + end + + def test_find_farthest_with_custom + assert_equal @custom_loc_e, CustomLocation.find_farthest(:origin => @loc_a) + end + + def test_find_farthest_with_coordinates_with_custom + assert_equal @custom_loc_e, CustomLocation.find_farthest(:origin =>[@loc_a.lat, @loc_a.lng]) + end + + def test_find_with_array_origin + locations = Location.find(:all, :origin =>[@loc_a.lat,@loc_a.lng], :conditions => "distance < 3.97") + assert_equal 5, locations.size + locations = Location.count(:origin =>[@loc_a.lat,@loc_a.lng], :conditions => "distance < 3.97") + assert_equal 5, locations + end + + + # Bounding box tests + + def test_find_within_bounds + locations = Location.find_within_bounds([@sw,@ne]) + assert_equal 2, locations.size + locations = Location.count_within_bounds([@sw,@ne]) + assert_equal 2, locations + end + + def test_find_within_bounds_ordered_by_distance + locations = Location.find_within_bounds([@sw,@ne], :origin=>@bounds_center, :order=>'distance asc') + assert_equal locations[0], locations(:d) + assert_equal locations[1], locations(:a) + end + + def test_find_within_bounds_with_token + locations = Location.find(:all, :bounds=>[@sw,@ne]) + assert_equal 2, locations.size + locations = Location.count(:bounds=>[@sw,@ne]) + assert_equal 2, locations + end + + def test_find_within_bounds_with_string_conditions + locations = Location.find(:all, :bounds=>[@sw,@ne], :conditions=>"id !=#{locations(:a).id}") + assert_equal 1, locations.size + end + + def test_find_within_bounds_with_array_conditions + locations = Location.find(:all, :bounds=>[@sw,@ne], :conditions=>["id != ?", locations(:a).id]) + assert_equal 1, locations.size + end + + def test_auto_geocode + GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("Irving, TX").returns(@location_a) + store=Store.new(:address=>'Irving, TX') + store.save + assert_equal store.lat,@location_a.lat + assert_equal store.lng,@location_a.lng + assert_equal 0, store.errors.size + end + + def test_auto_geocode_failure + GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("BOGUS").returns(GeoKit::GeoLoc.new) + store=Store.new(:address=>'BOGUS') + store.save + assert store.new_record? + assert_equal 1, store.errors.size + end +end diff --git a/vendor/plugins/geokit/test/base_geocoder_test.rb b/vendor/plugins/geokit/test/base_geocoder_test.rb new file mode 100644 index 0000000..b51a739 --- /dev/null +++ b/vendor/plugins/geokit/test/base_geocoder_test.rb @@ -0,0 +1,57 @@ +require 'test/unit' +require 'net/http' +require 'rubygems' +require 'mocha' +require File.join(File.dirname(__FILE__), '../../../../config/environment') + + +class MockSuccess < Net::HTTPSuccess #:nodoc: all + def initialize + end +end + +class MockFailure < Net::HTTPServiceUnavailable #:nodoc: all + def initialize + end +end + +# Base class for testing geocoders. +class BaseGeocoderTest < Test::Unit::TestCase #:nodoc: all + + # Defines common test fixtures. + def setup + @address = 'San Francisco, CA' + @full_address = '100 Spear St, San Francisco, CA, 94105-1522, US' + @full_address_short_zip = '100 Spear St, San Francisco, CA, 94105, US' + + @success = GeoKit::GeoLoc.new({:city=>"SAN FRANCISCO", :state=>"CA", :country_code=>"US", :lat=>37.7742, :lng=>-122.417068}) + @success.success = true + end + + def test_timeout_call_web_service + GeoKit::Geocoders::Geocoder.class_eval do + def self.do_get(url) + sleep(2) + end + end + url = "http://www.anything.com" + GeoKit::Geocoders::timeout = 1 + assert_nil GeoKit::Geocoders::Geocoder.call_geocoder_service(url) + end + + def test_successful_call_web_service + url = "http://www.anything.com" + GeoKit::Geocoders::Geocoder.expects(:do_get).with(url).returns("SUCCESS") + assert_equal "SUCCESS", GeoKit::Geocoders::Geocoder.call_geocoder_service(url) + end + + def test_find_geocoder_methods + public_methods = GeoKit::Geocoders::Geocoder.public_methods + assert public_methods.include?("yahoo_geocoder") + assert public_methods.include?("google_geocoder") + assert public_methods.include?("ca_geocoder") + assert public_methods.include?("us_geocoder") + assert public_methods.include?("multi_geocoder") + assert public_methods.include?("ip_geocoder") + end +end \ No newline at end of file diff --git a/vendor/plugins/geokit/test/bounds_test.rb b/vendor/plugins/geokit/test/bounds_test.rb new file mode 100644 index 0000000..4cabfde --- /dev/null +++ b/vendor/plugins/geokit/test/bounds_test.rb @@ -0,0 +1,75 @@ +$LOAD_PATH.unshift File.join('..', 'lib') +require 'geo_kit/mappable' +require 'test/unit' + +class BoundsTest < Test::Unit::TestCase #:nodoc: all + + def setup + # This is the area in Texas + @sw = GeoKit::LatLng.new(32.91663,-96.982841) + @ne = GeoKit::LatLng.new(32.96302,-96.919495) + @bounds=GeoKit::Bounds.new(@sw,@ne) + @loc_a=GeoKit::LatLng.new(32.918593,-96.958444) # inside bounds + @loc_b=GeoKit::LatLng.new(32.914144,-96.958444) # outside bouds + + # this is a cross-meridan area + @cross_meridian=GeoKit::Bounds.normalize([30,170],[40,-170]) + @inside_cm=GeoKit::LatLng.new(35,175) + @inside_cm_2=GeoKit::LatLng.new(35,-175) + @east_of_cm=GeoKit::LatLng.new(35,-165) + @west_of_cm=GeoKit::LatLng.new(35,165) + + end + + def test_equality + assert_equal GeoKit::Bounds.new(@sw,@ne), GeoKit::Bounds.new(@sw,@ne) + end + + def test_normalize + res=GeoKit::Bounds.normalize(@sw,@ne) + assert_equal res,GeoKit::Bounds.new(@sw,@ne) + res=GeoKit::Bounds.normalize([@sw,@ne]) + assert_equal res,GeoKit::Bounds.new(@sw,@ne) + res=GeoKit::Bounds.normalize([@sw.lat,@sw.lng],[@ne.lat,@ne.lng]) + assert_equal res,GeoKit::Bounds.new(@sw,@ne) + res=GeoKit::Bounds.normalize([[@sw.lat,@sw.lng],[@ne.lat,@ne.lng]]) + assert_equal res,GeoKit::Bounds.new(@sw,@ne) + end + + def test_point_inside_bounds + assert @bounds.contains?(@loc_a) + end + + def test_point_outside_bounds + assert !@bounds.contains?(@loc_b) + end + + def test_point_inside_bounds_cross_meridian + assert @cross_meridian.contains?(@inside_cm) + assert @cross_meridian.contains?(@inside_cm_2) + end + + def test_point_outside_bounds_cross_meridian + assert !@cross_meridian.contains?(@east_of_cm) + assert !@cross_meridian.contains?(@west_of_cm) + end + + def test_center + assert_in_delta 32.939828,@bounds.center.lat,0.00005 + assert_in_delta -96.9511763,@bounds.center.lng,0.00005 + end + + def test_center_cross_meridian + assert_in_delta 35.41160, @cross_meridian.center.lat,0.00005 + assert_in_delta 179.38112, @cross_meridian.center.lng,0.00005 + end + + def test_creation_from_circle + bounds=GeoKit::Bounds.from_point_and_radius([32.939829, -96.951176],2.5) + inside=GeoKit::LatLng.new 32.9695270000,-96.9901590000 + outside=GeoKit::LatLng.new 32.8951550000,-96.9584440000 + assert bounds.contains?(inside) + assert !bounds.contains?(outside) + end + +end \ No newline at end of file diff --git a/vendor/plugins/geokit/test/ca_geocoder_test.rb b/vendor/plugins/geokit/test/ca_geocoder_test.rb new file mode 100644 index 0000000..9d797ce --- /dev/null +++ b/vendor/plugins/geokit/test/ca_geocoder_test.rb @@ -0,0 +1,41 @@ +require File.join(File.dirname(__FILE__), 'base_geocoder_test') + +GeoKit::Geocoders::geocoder_ca = "SOMEKEYVALUE" + +class CaGeocoderTest < BaseGeocoderTest #:nodoc: all + + CA_SUCCESS=<<-EOF + + 49.243086-123.153684 + EOF + + def setup + @ca_full_hash = {:street_address=>"2105 West 32nd Avenue",:city=>"Vancouver", :state=>"BC"} + @ca_full_loc = GeoKit::GeoLoc.new(@ca_full_hash) + end + + def test_geocoder_with_geo_loc_with_account + response = MockSuccess.new + response.expects(:body).returns(CA_SUCCESS) + url = "http://geocoder.ca/?stno=2105&addresst=West+32nd+Avenue&city=Vancouver&prov=BC&auth=SOMEKEYVALUE&geoit=xml" + GeoKit::Geocoders::CaGeocoder.expects(:call_geocoder_service).with(url).returns(response) + verify(GeoKit::Geocoders::CaGeocoder.geocode(@ca_full_loc)) + end + + def test_service_unavailable + response = MockFailure.new + #Net::HTTP.expects(:get_response).with(URI.parse("http://geocoder.ca/?stno=2105&addresst=West+32nd+Avenue&city=Vancouver&prov=BC&auth=SOMEKEYVALUE&geoit=xml")).returns(response) + url = "http://geocoder.ca/?stno=2105&addresst=West+32nd+Avenue&city=Vancouver&prov=BC&auth=SOMEKEYVALUE&geoit=xml" + GeoKit::Geocoders::CaGeocoder.expects(:call_geocoder_service).with(url).returns(response) + assert !GeoKit::Geocoders::CaGeocoder.geocode(@ca_full_loc).success + end + + private + + def verify(location) + assert_equal "BC", location.state + assert_equal "Vancouver", location.city + assert_equal "49.243086,-123.153684", location.ll + assert !location.is_us? + end +end \ No newline at end of file diff --git a/vendor/plugins/geokit/test/database.yml b/vendor/plugins/geokit/test/database.yml new file mode 100644 index 0000000..c2c6591 --- /dev/null +++ b/vendor/plugins/geokit/test/database.yml @@ -0,0 +1,12 @@ +mysql: + adapter: mysql + host: localhost + username: root + password: + database: geokit_plugin_test +postgresql: + adapter: postgresql + host: localhost + username: root + password: + database: geokit_plugin_test \ No newline at end of file diff --git a/vendor/plugins/geokit/test/fixtures/companies.yml b/vendor/plugins/geokit/test/fixtures/companies.yml new file mode 100644 index 0000000..d48a2e8 --- /dev/null +++ b/vendor/plugins/geokit/test/fixtures/companies.yml @@ -0,0 +1,7 @@ +starbucks: + id: 1 + name: Starbucks + +barnes_and_noble: + id: 2 + name: Barnes & Noble \ No newline at end of file diff --git a/vendor/plugins/geokit/test/fixtures/custom_locations.yml b/vendor/plugins/geokit/test/fixtures/custom_locations.yml new file mode 100644 index 0000000..f5a1e92 --- /dev/null +++ b/vendor/plugins/geokit/test/fixtures/custom_locations.yml @@ -0,0 +1,54 @@ +a: + id: 1 + company_id: 1 + street: 7979 N MacArthur Blvd + city: Irving + state: TX + postal_code: 75063 + latitude: 32.918593 + longitude: -96.958444 +b: + id: 2 + company_id: 1 + street: 7750 N Macarthur Blvd # 160 + city: Irving + state: TX + postal_code: 75063 + latitude: 32.914144 + longitude: -96.958444 +c: + id: 3 + company_id: 1 + street: 5904 N Macarthur Blvd # 160 + city: Irving + state: TX + postal_code: 75039 + latitude: 32.895155 + longitude: -96.958444 +d: + id: 4 + company_id: 1 + street: 817 S Macarthur Blvd # 145 + city: Coppell + state: TX + postal_code: 75019 + latitude: 32.951613 + longitude: -96.958444 +e: + id: 5 + company_id: 1 + street: 106 N Denton Tap Rd # 350 + city: Coppell + state: TX + postal_code: 75019 + latitude: 32.969527 + longitude: -96.990159 +f: + id: 6 + company_id: 2 + street: 5904 N Macarthur Blvd # 160 + city: Irving + state: TX + postal_code: 75039 + latitude: 32.895155 + longitude: -96.958444 \ No newline at end of file diff --git a/vendor/plugins/geokit/test/fixtures/locations.yml b/vendor/plugins/geokit/test/fixtures/locations.yml new file mode 100644 index 0000000..779faba --- /dev/null +++ b/vendor/plugins/geokit/test/fixtures/locations.yml @@ -0,0 +1,54 @@ +a: + id: 1 + company_id: 1 + street: 7979 N MacArthur Blvd + city: Irving + state: TX + postal_code: 75063 + lat: 32.918593 + lng: -96.958444 +b: + id: 2 + company_id: 1 + street: 7750 N Macarthur Blvd # 160 + city: Irving + state: TX + postal_code: 75063 + lat: 32.914144 + lng: -96.958444 +c: + id: 3 + company_id: 1 + street: 5904 N Macarthur Blvd # 160 + city: Irving + state: TX + postal_code: 75039 + lat: 32.895155 + lng: -96.958444 +d: + id: 4 + company_id: 1 + street: 817 S Macarthur Blvd # 145 + city: Coppell + state: TX + postal_code: 75019 + lat: 32.951613 + lng: -96.958444 +e: + id: 5 + company_id: 1 + street: 106 N Denton Tap Rd # 350 + city: Coppell + state: TX + postal_code: 75019 + lat: 32.969527 + lng: -96.990159 +f: + id: 6 + company_id: 2 + street: 5904 N Macarthur Blvd # 160 + city: Irving + state: TX + postal_code: 75039 + lat: 32.895155 + lng: -96.958444 \ No newline at end of file diff --git a/vendor/plugins/geokit/test/fixtures/stores.yml b/vendor/plugins/geokit/test/fixtures/stores.yml new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/vendor/plugins/geokit/test/fixtures/stores.yml diff --git a/vendor/plugins/geokit/test/geoloc_test.rb b/vendor/plugins/geokit/test/geoloc_test.rb new file mode 100644 index 0000000..5cf6411 --- /dev/null +++ b/vendor/plugins/geokit/test/geoloc_test.rb @@ -0,0 +1,49 @@ +require 'test/unit' +require File.join(File.dirname(__FILE__), '../../../../config/environment') + +class GeoLocTest < Test::Unit::TestCase #:nodoc: all + + def setup + @loc = GeoKit::GeoLoc.new + end + + def test_is_us + assert !@loc.is_us? + @loc.country_code = 'US' + assert @loc.is_us? + end + + def test_street_number + @loc.street_address = '123 Spear St.' + assert_equal '123', @loc.street_number + end + + def test_street_name + @loc.street_address = '123 Spear St.' + assert_equal 'Spear St.', @loc.street_name + end + + def test_city + @loc.city = "san francisco" + assert_equal 'San Francisco', @loc.city + end + + def test_full_address + @loc.city = 'San Francisco' + @loc.state = 'CA' + @loc.zip = '94105' + @loc.country_code = 'US' + assert_equal 'San Francisco, CA, 94105, US', @loc.full_address + @loc.full_address = 'Irving, TX, 75063, US' + assert_equal 'Irving, TX, 75063, US', @loc.full_address + end + + def test_hash + @loc.city = 'San Francisco' + @loc.state = 'CA' + @loc.zip = '94105' + @loc.country_code = 'US' + @another = GeoKit::GeoLoc.new @loc.to_hash + assert_equal @loc, @another + end +end \ No newline at end of file diff --git a/vendor/plugins/geokit/test/google_geocoder_test.rb b/vendor/plugins/geokit/test/google_geocoder_test.rb new file mode 100644 index 0000000..dfa8a0c --- /dev/null +++ b/vendor/plugins/geokit/test/google_geocoder_test.rb @@ -0,0 +1,88 @@ +require File.join(File.dirname(__FILE__), 'base_geocoder_test') + +GeoKit::Geocoders::google = 'Google' + +class GoogleGeocoderTest < BaseGeocoderTest #:nodoc: all + + GOOGLE_FULL=<<-EOF.strip + 100 spear st, san francisco, ca200geocode
100 Spear St, San Francisco, CA 94105, USA
USCASan FranciscoSan Francisco100 Spear St94105-122.393985,37.792501,0
+ EOF + + GOOGLE_CITY=<<-EOF.strip + San Francisco200geocode
San Francisco, CA, USA
USCASan Francisco-122.418333,37.775000,0
+ EOF + + def setup + super + @google_full_hash = {:street_address=>"100 Spear St", :city=>"San Francisco", :state=>"CA", :zip=>"94105", :country_code=>"US"} + @google_city_hash = {:city=>"San Francisco", :state=>"CA"} + + @google_full_loc = GeoKit::GeoLoc.new(@google_full_hash) + @google_city_loc = GeoKit::GeoLoc.new(@google_city_hash) + end + + def test_google_full_address + response = MockSuccess.new + response.expects(:body).returns(GOOGLE_FULL) + url = "http://maps.google.com/maps/geo?q=#{CGI.escape(@address)}&output=xml&key=Google&oe=utf-8" + GeoKit::Geocoders::GoogleGeocoder.expects(:call_geocoder_service).with(url).returns(response) + res=GeoKit::Geocoders::GoogleGeocoder.geocode(@address) + assert_equal "CA", res.state + assert_equal "San Francisco", res.city + assert_equal "37.792501,-122.393985", res.ll # slightly dif from yahoo + assert res.is_us? + assert_equal "100 Spear St, San Francisco, CA 94105, USA", res.full_address #slightly different from yahoo + assert_equal "google", res.provider + end + + def test_google_full_address_with_geo_loc + response = MockSuccess.new + response.expects(:body).returns(GOOGLE_FULL) + url = "http://maps.google.com/maps/geo?q=#{CGI.escape(@full_address_short_zip)}&output=xml&key=Google&oe=utf-8" + GeoKit::Geocoders::GoogleGeocoder.expects(:call_geocoder_service).with(url).returns(response) + res=GeoKit::Geocoders::GoogleGeocoder.geocode(@google_full_loc) + assert_equal "CA", res.state + assert_equal "San Francisco", res.city + assert_equal "37.792501,-122.393985", res.ll # slightly dif from yahoo + assert res.is_us? + assert_equal "100 Spear St, San Francisco, CA 94105, USA", res.full_address #slightly different from yahoo + assert_equal "google", res.provider + end + + def test_google_city + response = MockSuccess.new + response.expects(:body).returns(GOOGLE_CITY) + url = "http://maps.google.com/maps/geo?q=#{CGI.escape(@address)}&output=xml&key=Google&oe=utf-8" + GeoKit::Geocoders::GoogleGeocoder.expects(:call_geocoder_service).with(url).returns(response) + res=GeoKit::Geocoders::GoogleGeocoder.geocode(@address) + assert_equal "CA", res.state + assert_equal "San Francisco", res.city + assert_equal "37.775,-122.418333", res.ll + assert res.is_us? + assert_equal "San Francisco, CA, USA", res.full_address + assert_nil res.street_address + assert_equal "google", res.provider + end + + def test_google_city_with_geo_loc + response = MockSuccess.new + response.expects(:body).returns(GOOGLE_CITY) + url = "http://maps.google.com/maps/geo?q=#{CGI.escape(@address)}&output=xml&key=Google&oe=utf-8" + GeoKit::Geocoders::GoogleGeocoder.expects(:call_geocoder_service).with(url).returns(response) + res=GeoKit::Geocoders::GoogleGeocoder.geocode(@google_city_loc) + assert_equal "CA", res.state + assert_equal "San Francisco", res.city + assert_equal "37.775,-122.418333", res.ll + assert res.is_us? + assert_equal "San Francisco, CA, USA", res.full_address + assert_nil res.street_address + assert_equal "google", res.provider + end + + def test_service_unavailable + response = MockFailure.new + url = "http://maps.google.com/maps/geo?q=#{CGI.escape(@address)}&output=xml&key=Google&oe=utf-8" + GeoKit::Geocoders::GoogleGeocoder.expects(:call_geocoder_service).with(url).returns(response) + assert !GeoKit::Geocoders::GoogleGeocoder.geocode(@google_city_loc).success + end +end \ No newline at end of file diff --git a/vendor/plugins/geokit/test/ip_geocode_lookup_test.rb b/vendor/plugins/geokit/test/ip_geocode_lookup_test.rb new file mode 100644 index 0000000..31f3582 --- /dev/null +++ b/vendor/plugins/geokit/test/ip_geocode_lookup_test.rb @@ -0,0 +1,84 @@ +require File.join(File.dirname(__FILE__), '../../../../config/environment') +require 'action_controller/test_process' +require 'test/unit' +require 'rubygems' +require 'mocha' + + +class LocationAwareController < ActionController::Base #:nodoc: all + geocode_ip_address + + def index + render :nothing => true + end +end + +class ActionController::TestRequest #:nodoc: all + attr_accessor :remote_ip +end + +# Re-raise errors caught by the controller. +class LocationAwareController #:nodoc: all + def rescue_action(e) raise e end; +end + +class IpGeocodeLookupTest < Test::Unit::TestCase #:nodoc: all + + def setup + @success = GeoKit::GeoLoc.new + @success.provider = "hostip" + @success.lat = 41.7696 + @success.lng = -88.4588 + @success.city = "Sugar Grove" + @success.state = "IL" + @success.country_code = "US" + @success.success = true + + @failure = GeoKit::GeoLoc.new + @failure.provider = "hostip" + @failure.city = "(Private Address)" + @failure.success = false + + @controller = LocationAwareController.new + @request = ActionController::TestRequest.new + @response = ActionController::TestResponse.new + end + + def test_no_location_in_cookie_or_session + GeoKit::Geocoders::IpGeocoder.expects(:geocode).with("good ip").returns(@success) + @request.remote_ip = "good ip" + get :index + verify + end + + def test_location_in_cookie + @request.remote_ip = "good ip" + @request.cookies['geo_location'] = CGI::Cookie.new('geo_location', @success.to_yaml) + get :index + verify + end + + def test_location_in_session + @request.remote_ip = "good ip" + @request.session[:geo_location] = @success + @request.cookies['geo_location'] = CGI::Cookie.new('geo_location', @success.to_yaml) + get :index + verify + end + + def test_ip_not_located + GeoKit::Geocoders::IpGeocoder.expects(:geocode).with("bad ip").returns(@failure) + @request.remote_ip = "bad ip" + get :index + assert_nil @request.session[:geo_location] + end + + private + + def verify + assert_response :success + assert_equal @success, @request.session[:geo_location] + assert_not_nil cookies['geo_location'] + assert_equal @success, YAML.load(cookies['geo_location'].join) + end +end \ No newline at end of file diff --git a/vendor/plugins/geokit/test/ipgeocoder_test.rb b/vendor/plugins/geokit/test/ipgeocoder_test.rb new file mode 100644 index 0000000..4d2b6a0 --- /dev/null +++ b/vendor/plugins/geokit/test/ipgeocoder_test.rb @@ -0,0 +1,87 @@ +require File.join(File.dirname(__FILE__), 'base_geocoder_test') + +class IpGeocoderTest < BaseGeocoderTest #:nodoc: all + + IP_FAILURE=<<-EOF + Country: (Private Address) (XX) + City: (Private Address) + Latitude: + Longitude: + EOF + + IP_SUCCESS=<<-EOF + Country: UNITED STATES (US) + City: Sugar Grove, IL + Latitude: 41.7696 + Longitude: -88.4588 + EOF + + IP_UNICODED=<<-EOF + Country: SWEDEN (SE) + City: Borås + Latitude: 57.7167 + Longitude: 12.9167 + EOF + + def setup + super + @success.provider = "hostip" + end + + def test_successful_lookup + success = MockSuccess.new + success.expects(:body).returns(IP_SUCCESS) + url = 'http://api.hostip.info/get_html.php?ip=12.215.42.19&position=true' + GeoKit::Geocoders::IpGeocoder.expects(:call_geocoder_service).with(url).returns(success) + location = GeoKit::Geocoders::IpGeocoder.geocode('12.215.42.19') + assert_not_nil location + assert_equal 41.7696, location.lat + assert_equal -88.4588, location.lng + assert_equal "Sugar Grove", location.city + assert_equal "IL", location.state + assert_equal "US", location.country_code + assert_equal "hostip", location.provider + assert location.success + end + + def test_unicoded_lookup + success = MockSuccess.new + success.expects(:body).returns(IP_UNICODED) + url = 'http://api.hostip.info/get_html.php?ip=12.215.42.19&position=true' + GeoKit::Geocoders::IpGeocoder.expects(:call_geocoder_service).with(url).returns(success) + location = GeoKit::Geocoders::IpGeocoder.geocode('12.215.42.19') + assert_not_nil location + assert_equal 57.7167, location.lat + assert_equal 12.9167, location.lng + assert_equal "Borås", location.city + assert_nil location.state + assert_equal "SE", location.country_code + assert_equal "hostip", location.provider + assert location.success + end + + def test_failed_lookup + failure = MockSuccess.new + failure.expects(:body).returns(IP_FAILURE) + url = 'http://api.hostip.info/get_html.php?ip=0.0.0.0&position=true' + GeoKit::Geocoders::IpGeocoder.expects(:call_geocoder_service).with(url).returns(failure) + location = GeoKit::Geocoders::IpGeocoder.geocode("0.0.0.0") + assert_not_nil location + assert !location.success + end + + def test_invalid_ip + location = GeoKit::Geocoders::IpGeocoder.geocode("blah") + assert_not_nil location + assert !location.success + end + + def test_service_unavailable + failure = MockFailure.new + url = 'http://api.hostip.info/get_html.php?ip=0.0.0.0&position=true' + GeoKit::Geocoders::IpGeocoder.expects(:call_geocoder_service).with(url).returns(failure) + location = GeoKit::Geocoders::IpGeocoder.geocode("0.0.0.0") + assert_not_nil location + assert !location.success + end +end \ No newline at end of file diff --git a/vendor/plugins/geokit/test/latlng_test.rb b/vendor/plugins/geokit/test/latlng_test.rb new file mode 100644 index 0000000..993d2be --- /dev/null +++ b/vendor/plugins/geokit/test/latlng_test.rb @@ -0,0 +1,112 @@ +$LOAD_PATH.unshift File.join('..', 'lib') +require 'geo_kit/mappable' +require 'test/unit' + +class LatLngTest < Test::Unit::TestCase #:nodoc: all + + def setup + @loc_a = GeoKit::LatLng.new(32.918593,-96.958444) + @loc_e = GeoKit::LatLng.new(32.969527,-96.990159) + @point = GeoKit::LatLng.new(@loc_a.lat, @loc_a.lng) + end + + def test_distance_between_same_using_defaults + assert_equal 0, GeoKit::LatLng.distance_between(@loc_a, @loc_a) + assert_equal 0, @loc_a.distance_to(@loc_a) + end + + def test_distance_between_same_with_miles_and_flat + assert_equal 0, GeoKit::LatLng.distance_between(@loc_a, @loc_a, :units => :miles, :formula => :flat) + assert_equal 0, @loc_a.distance_to(@loc_a, :units => :miles, :formula => :flat) + end + + def test_distance_between_same_with_kms_and_flat + assert_equal 0, GeoKit::LatLng.distance_between(@loc_a, @loc_a, :units => :kms, :formula => :flat) + assert_equal 0, @loc_a.distance_to(@loc_a, :units => :kms, :formula => :flat) + end + + def test_distance_between_same_with_miles_and_sphere + assert_equal 0, GeoKit::LatLng.distance_between(@loc_a, @loc_a, :units => :miles, :formula => :sphere) + assert_equal 0, @loc_a.distance_to(@loc_a, :units => :miles, :formula => :sphere) + end + + def test_distance_between_same_with_kms_and_sphere + assert_equal 0, GeoKit::LatLng.distance_between(@loc_a, @loc_a, :units => :kms, :formula => :sphere) + assert_equal 0, @loc_a.distance_to(@loc_a, :units => :kms, :formula => :sphere) + end + + def test_distance_between_diff_using_defaults + assert_in_delta 3.97, GeoKit::LatLng.distance_between(@loc_a, @loc_e), 0.01 + assert_in_delta 3.97, @loc_a.distance_to(@loc_e), 0.01 + end + + def test_distance_between_diff_with_miles_and_flat + assert_in_delta 3.97, GeoKit::LatLng.distance_between(@loc_a, @loc_e, :units => :miles, :formula => :flat), 0.2 + assert_in_delta 3.97, @loc_a.distance_to(@loc_e, :units => :miles, :formula => :flat), 0.2 + end + + def test_distance_between_diff_with_kms_and_flat + assert_in_delta 6.39, GeoKit::LatLng.distance_between(@loc_a, @loc_e, :units => :kms, :formula => :flat), 0.4 + assert_in_delta 6.39, @loc_a.distance_to(@loc_e, :units => :kms, :formula => :flat), 0.4 + end + + def test_distance_between_diff_with_miles_and_sphere + assert_in_delta 3.97, GeoKit::LatLng.distance_between(@loc_a, @loc_e, :units => :miles, :formula => :sphere), 0.01 + assert_in_delta 3.97, @loc_a.distance_to(@loc_e, :units => :miles, :formula => :sphere), 0.01 + end + + def test_distance_between_diff_with_kms_and_sphere + assert_in_delta 6.39, GeoKit::LatLng.distance_between(@loc_a, @loc_e, :units => :kms, :formula => :sphere), 0.01 + assert_in_delta 6.39, @loc_a.distance_to(@loc_e, :units => :kms, :formula => :sphere), 0.01 + end + + def test_manually_mixed_in + assert_equal 0, GeoKit::LatLng.distance_between(@point, @point) + assert_equal 0, @point.distance_to(@point) + assert_equal 0, @point.distance_to(@loc_a) + assert_in_delta 3.97, @point.distance_to(@loc_e, :units => :miles, :formula => :flat), 0.2 + assert_in_delta 6.39, @point.distance_to(@loc_e, :units => :kms, :formula => :flat), 0.4 + end + + def test_heading_between + assert_in_delta 332, GeoKit::LatLng.heading_between(@loc_a,@loc_e), 0.5 + end + + def test_heading_to + assert_in_delta 332, @loc_a.heading_to(@loc_e), 0.5 + end + + def test_class_endpoint + endpoint=GeoKit::LatLng.endpoint(@loc_a, 332, 3.97) + assert_in_delta @loc_e.lat, endpoint.lat, 0.0005 + assert_in_delta @loc_e.lng, endpoint.lng, 0.0005 + end + + def test_instance_endpoint + endpoint=@loc_a.endpoint(332, 3.97) + assert_in_delta @loc_e.lat, endpoint.lat, 0.0005 + assert_in_delta @loc_e.lng, endpoint.lng, 0.0005 + end + + def test_midpoint + midpoint=@loc_a.midpoint_to(@loc_e) + assert_in_delta 32.944061, midpoint.lat, 0.0005 + assert_in_delta -96.974296, midpoint.lng, 0.0005 + end + + def test_normalize + lat=37.7690 + lng=-122.443 + res=GeoKit::LatLng.normalize(lat,lng) + assert_equal res,GeoKit::LatLng.new(lat,lng) + res=GeoKit::LatLng.normalize("#{lat}, #{lng}") + assert_equal res,GeoKit::LatLng.new(lat,lng) + res=GeoKit::LatLng.normalize("#{lat} #{lng}") + assert_equal res,GeoKit::LatLng.new(lat,lng) + res=GeoKit::LatLng.normalize("#{lat.to_i} #{lng.to_i}") + assert_equal res,GeoKit::LatLng.new(lat.to_i,lng.to_i) + res=GeoKit::LatLng.normalize([lat,lng]) + assert_equal res,GeoKit::LatLng.new(lat,lng) + end + +end \ No newline at end of file diff --git a/vendor/plugins/geokit/test/multi_geocoder_test.rb b/vendor/plugins/geokit/test/multi_geocoder_test.rb new file mode 100644 index 0000000..57f326c --- /dev/null +++ b/vendor/plugins/geokit/test/multi_geocoder_test.rb @@ -0,0 +1,44 @@ +require File.join(File.dirname(__FILE__), 'base_geocoder_test') + +GeoKit::Geocoders::provider_order=[:google,:yahoo,:us] + +class MultiGeocoderTest < BaseGeocoderTest #:nodoc: all + + def setup + super + @failure = GeoKit::GeoLoc.new + end + + def test_successful_first + GeoKit::Geocoders::GoogleGeocoder.expects(:geocode).with(@address).returns(@success) + assert_equal @success, GeoKit::Geocoders::MultiGeocoder.geocode(@address) + end + + def test_failover + GeoKit::Geocoders::GoogleGeocoder.expects(:geocode).with(@address).returns(@failure) + GeoKit::Geocoders::YahooGeocoder.expects(:geocode).with(@address).returns(@success) + assert_equal @success, GeoKit::Geocoders::MultiGeocoder.geocode(@address) + end + + def test_double_failover + GeoKit::Geocoders::GoogleGeocoder.expects(:geocode).with(@address).returns(@failure) + GeoKit::Geocoders::YahooGeocoder.expects(:geocode).with(@address).returns(@failure) + GeoKit::Geocoders::UsGeocoder.expects(:geocode).with(@address).returns(@success) + assert_equal @success, GeoKit::Geocoders::MultiGeocoder.geocode(@address) + end + + def test_failure + GeoKit::Geocoders::GoogleGeocoder.expects(:geocode).with(@address).returns(@failure) + GeoKit::Geocoders::YahooGeocoder.expects(:geocode).with(@address).returns(@failure) + GeoKit::Geocoders::UsGeocoder.expects(:geocode).with(@address).returns(@failure) + assert_equal @failure, GeoKit::Geocoders::MultiGeocoder.geocode(@address) + end + + def test_invalid_provider + temp = GeoKit::Geocoders::provider_order + GeoKit::Geocoders.provider_order = [:bogus] + assert_equal @failure, GeoKit::Geocoders::MultiGeocoder.geocode(@address) + GeoKit::Geocoders.provider_order = temp + end + +end \ No newline at end of file diff --git a/vendor/plugins/geokit/test/schema.rb b/vendor/plugins/geokit/test/schema.rb new file mode 100644 index 0000000..ad69e08 --- /dev/null +++ b/vendor/plugins/geokit/test/schema.rb @@ -0,0 +1,31 @@ +ActiveRecord::Schema.define(:version => 0) do + create_table :companies, :force => true do |t| + t.column :name, :string + end + + create_table :locations, :force => true do |t| + t.column :company_id, :integer, :default => 0, :null => false + t.column :street, :string, :limit => 60 + t.column :city, :string, :limit => 60 + t.column :state, :string, :limit => 2 + t.column :postal_code, :string, :limit => 16 + t.column :lat, :decimal, :precision => 15, :scale => 10 + t.column :lng, :decimal, :precision => 15, :scale => 10 + end + + create_table :custom_locations, :force => true do |t| + t.column :company_id, :integer, :default => 0, :null => false + t.column :street, :string, :limit => 60 + t.column :city, :string, :limit => 60 + t.column :state, :string, :limit => 2 + t.column :postal_code, :string, :limit => 16 + t.column :latitude, :decimal, :precision => 15, :scale => 10 + t.column :longitude, :decimal, :precision => 15, :scale => 10 + end + + create_table :stores, :force=> true do |t| + t.column :address, :string + t.column :lat, :decimal, :precision => 15, :scale => 10 + t.column :lng, :decimal, :precision => 15, :scale => 10 + end +end \ No newline at end of file diff --git a/vendor/plugins/geokit/test/test_helper.rb b/vendor/plugins/geokit/test/test_helper.rb new file mode 100644 index 0000000..5cd8f92 --- /dev/null +++ b/vendor/plugins/geokit/test/test_helper.rb @@ -0,0 +1,18 @@ +require 'test/unit' + +plugin_test_dir = File.dirname(__FILE__) + +# Load the Rails environment +require File.join(plugin_test_dir, '../../../../config/environment') +require 'active_record/fixtures' +databases = YAML::load(IO.read(plugin_test_dir + '/database.yml')) +ActiveRecord::Base.logger = Logger.new(plugin_test_dir + "/debug.log") + +# A specific database can be used by setting the DB environment variable +ActiveRecord::Base.establish_connection(databases[ENV['DB'] || 'mysql']) + +# Load the test schema into the database +load(File.join(plugin_test_dir, 'schema.rb')) + +# Load fixtures from the plugin +Test::Unit::TestCase.fixture_path = File.join(plugin_test_dir, 'fixtures/') \ No newline at end of file diff --git a/vendor/plugins/geokit/test/us_geocoder_test.rb b/vendor/plugins/geokit/test/us_geocoder_test.rb new file mode 100644 index 0000000..4457803 --- /dev/null +++ b/vendor/plugins/geokit/test/us_geocoder_test.rb @@ -0,0 +1,47 @@ +require File.join(File.dirname(__FILE__), 'base_geocoder_test') + +GeoKit::Geocoders::geocoder_us = nil + +class UsGeocoderTest < BaseGeocoderTest #:nodoc: all + + GEOCODER_US_FULL='37.792528,-122.393981,100 Spear St,San Francisco,CA,94105' + + def setup + super + @us_full_hash = {:city=>"San Francisco", :state=>"CA"} + @us_full_loc = GeoKit::GeoLoc.new(@us_full_hash) + end + + def test_geocoder_us + response = MockSuccess.new + response.expects(:body).returns(GEOCODER_US_FULL) + url = "http://geocoder.us/service/csv/geocode?address=#{CGI.escape(@address)}" + GeoKit::Geocoders::UsGeocoder.expects(:call_geocoder_service).with(url).returns(response) + verify(GeoKit::Geocoders::UsGeocoder.geocode(@address)) + end + + def test_geocoder_with_geo_loc + response = MockSuccess.new + response.expects(:body).returns(GEOCODER_US_FULL) + url = "http://geocoder.us/service/csv/geocode?address=#{CGI.escape(@address)}" + GeoKit::Geocoders::UsGeocoder.expects(:call_geocoder_service).with(url).returns(response) + verify(GeoKit::Geocoders::UsGeocoder.geocode(@us_full_loc)) + end + + def test_service_unavailable + response = MockFailure.new + url = "http://geocoder.us/service/csv/geocode?address=#{CGI.escape(@address)}" + GeoKit::Geocoders::UsGeocoder.expects(:call_geocoder_service).with(url).returns(response) + assert !GeoKit::Geocoders::UsGeocoder.geocode(@us_full_loc).success + end + + private + + def verify(location) + assert_equal "CA", location.state + assert_equal "San Francisco", location.city + assert_equal "37.792528,-122.393981", location.ll + assert location.is_us? + assert_equal "100 Spear St, San Francisco, CA, 94105, US", location.full_address #slightly different from yahoo + end +end \ No newline at end of file diff --git a/vendor/plugins/geokit/test/yahoo_geocoder_test.rb b/vendor/plugins/geokit/test/yahoo_geocoder_test.rb new file mode 100644 index 0000000..abf9a4e --- /dev/null +++ b/vendor/plugins/geokit/test/yahoo_geocoder_test.rb @@ -0,0 +1,87 @@ +require File.join(File.dirname(__FILE__), 'base_geocoder_test') + +GeoKit::Geocoders::yahoo = 'Yahoo' + +class YahooGeocoderTest < BaseGeocoderTest #:nodoc: all + YAHOO_FULL=<<-EOF.strip + + 37.792406-122.39411
100 SPEAR ST
SAN FRANCISCOCA94105-1522US
+ + EOF + + YAHOO_CITY=<<-EOF.strip + + 37.7742-122.417068
SAN FRANCISCOCAUS
+ + EOF + + def setup + super + @yahoo_full_hash = {:street_address=>"100 Spear St", :city=>"San Francisco", :state=>"CA", :zip=>"94105-1522", :country_code=>"US"} + @yahoo_city_hash = {:city=>"San Francisco", :state=>"CA"} + @yahoo_full_loc = GeoKit::GeoLoc.new(@yahoo_full_hash) + @yahoo_city_loc = GeoKit::GeoLoc.new(@yahoo_city_hash) + end + + # the testing methods themselves + def test_yahoo_full_address + response = MockSuccess.new + response.expects(:body).returns(YAHOO_FULL) + url = "http://api.local.yahoo.com/MapsService/V1/geocode?appid=Yahoo&location=#{CGI.escape(@address)}" + GeoKit::Geocoders::YahooGeocoder.expects(:call_geocoder_service).with(url).returns(response) + do_full_address_assertions(GeoKit::Geocoders::YahooGeocoder.geocode(@address)) + end + + def test_yahoo_full_address_with_geo_loc + response = MockSuccess.new + response.expects(:body).returns(YAHOO_FULL) + url = "http://api.local.yahoo.com/MapsService/V1/geocode?appid=Yahoo&location=#{CGI.escape(@full_address)}" + GeoKit::Geocoders::YahooGeocoder.expects(:call_geocoder_service).with(url).returns(response) + do_full_address_assertions(GeoKit::Geocoders::YahooGeocoder.geocode(@yahoo_full_loc)) + end + + def test_yahoo_city + response = MockSuccess.new + response.expects(:body).returns(YAHOO_CITY) + url = "http://api.local.yahoo.com/MapsService/V1/geocode?appid=Yahoo&location=#{CGI.escape(@address)}" + GeoKit::Geocoders::YahooGeocoder.expects(:call_geocoder_service).with(url).returns(response) + do_city_assertions(GeoKit::Geocoders::YahooGeocoder.geocode(@address)) + end + + def test_yahoo_city_with_geo_loc + response = MockSuccess.new + response.expects(:body).returns(YAHOO_CITY) + url = "http://api.local.yahoo.com/MapsService/V1/geocode?appid=Yahoo&location=#{CGI.escape(@address)}" + GeoKit::Geocoders::YahooGeocoder.expects(:call_geocoder_service).with(url).returns(response) + do_city_assertions(GeoKit::Geocoders::YahooGeocoder.geocode(@yahoo_city_loc)) + end + + def test_service_unavailable + response = MockFailure.new + url = "http://api.local.yahoo.com/MapsService/V1/geocode?appid=Yahoo&location=#{CGI.escape(@address)}" + GeoKit::Geocoders::YahooGeocoder.expects(:call_geocoder_service).with(url).returns(response) + assert !GeoKit::Geocoders::YahooGeocoder.geocode(@yahoo_city_loc).success + end + + private + + # next two methods do the assertions for both address-level and city-level lookups + def do_full_address_assertions(res) + assert_equal "CA", res.state + assert_equal "San Francisco", res.city + assert_equal "37.792406,-122.39411", res.ll + assert res.is_us? + assert_equal "100 Spear St, San Francisco, CA, 94105-1522, US", res.full_address + assert_equal "yahoo", res.provider + end + + def do_city_assertions(res) + assert_equal "CA", res.state + assert_equal "San Francisco", res.city + assert_equal "37.7742,-122.417068", res.ll + assert res.is_us? + assert_equal "San Francisco, CA, US", res.full_address + assert_nil res.street_address + assert_equal "yahoo", res.provider + end +end \ No newline at end of file -- libgit2 0.21.2