Geocoder Ruby Library

repository·master·Indexed 27 days ago

https://github.com/alexreisner/geocoder

A comprehensive geocoding solution for Ruby supporting forward, reverse, and IP-based geocoding. It connects to over 40 different geocoding APIs and provides deep integration with ActiveRecord and Mongoid for automatic geocoding and geospatial database queries. Features include a CLI tool, caching support, batch geocoding via Rake, and a testing framework with stubs.

Tokens
8.1K
Snippets
28
Records
65
Agent score
88%

What's inside Geocoder

  1. Test Geocoding with Stubs

    master

    To avoid network calls during testing, configure the :test lookup and provide stubs for expected queries.

    Setup:

    1. Set lookup: :test in Geocoder.configure.
    2. Use Geocoder::Lookup::Test.add_stub(query_string, results_array) to define behavior.
    3. Use Geocoder::Lookup::Test.set_default_stub(results_array) for a fallback.

    Note: Stub keys must be strings, not symbols.

    Geocoder.configure(lookup: :test, ip_lookup: :test)
    
    Geocoder::Lookup::Test.add_stub(
      "New York, NY", [
        {
          'coordinates'  => [40.7143528, -74.0059731],
          'address'      => 'New York, NY, USA',
          'city'         => 'New York',
          'state'        => 'New York',
          'state_code'   => 'NY',
          'country'      => 'United States',
          'country_code' => 'US'
        }
      ]
    )
  2. Implement Caching for Geocoding Results

    master

    To improve performance and stability, configure a cache store. The store must support #[], #[]=, #del, and optionally #keys.

    Using Redis:

    Geocoder.configure(cache: Redis.new)

    Using Rails Cache:

    Geocoder.configure(cache: Geocoder::CacheStore::Generic.new(Rails.cache, {}))

    Expiring Cache:

    • Expire all results for a specific lookup: Geocoder::Lookup.get(:service_name).cache.expire(:all)
    • Expire all results for all services: Geocoder::Lookup.all_services.each { |s| Geocoder::Lookup.get(s).cache.expire(:all) }
  3. Import MaxMind Local CSV data

    master

    To use MaxMind Local with CSV data, follow these steps to set up your database:

    1. Generate the ActiveRecord migration: rails generate geocoder:maxmind:geolite_city (or geolite_country)
    2. Download, unpack, and import the data: rake geocoder:maxmind:geolite:load PACKAGE=city LICENSE_KEY=<KEY> (or PACKAGE=country)

    Note: Replace city with country in all commands and configurations where applicable.

    # generate migration to create tables
    rails generate geocoder:maxmind:geolite_city
    
    # download, unpack, and import data
    rake geocoder:maxmind:geolite:load PACKAGE=city LICENSE_KEY=<KEY>
  4. Configure Geocoder for ActiveRecord or Mongoid Models

    master

    To enable automatic geocoding for your models, follow these steps:

    1. Define an address method: Your model must have a method (or attribute) that returns a geocodable string.
    2. Prepare storage:
      • ActiveRecord: Add latitude and longitude columns (float or decimal).
      • MongoDB: Add a coordinates field of type Array.
    3. Configure the model:
      • Use geocoded_by :method_name for forward geocoding.
      • Use reverse_geocoded_by :latitude, :longitude for reverse geocoding.
      • For MongoDB, you must include the appropriate module: include Geocoder::Model::Mongoid or include Geocoder::Model::MongoMapper.
      • For non-Rails ActiveRecord environments (e.g., Sinatra), use extend Geocoder::Model::ActiveRecord.
    # Example ActiveRecord Model
    class Venue < ActiveRecord::Base
      def address
        [street, city, state, country].compact.join(', ')
      end
    
      geocoded_by :address
      after_validation :geocode
    end
    
    # Example MongoDB Model
    class Venue
      include Mongoid::Document
      field :coordinates, type: Array
      include Geocoder::Model::Mongoid
    
      def address
        [street, city, state, country].compact.join(', ')
      end
    
      geocoded_by :address
      after_validation :geocode
    end
  5. Configure AMap for Regional Street Address Lookups

    master

    To use AMap for geocoding in China, configure the lookup to :amap and provide your required API key. Note that AMap is intended for non-commercial use; check their terms for commercial usage.

    Geocoder.configure(lookup: :amap, api_key: "your_api_key")
  6. Configure Pelias (`:pelias`) lookup

    master

    The :pelias lookup can be used with self-hosted instances. Configure your self-hosted Pelias using the endpoint option within the pelias configuration hash.

    Geocoder.configure(lookup: :pelias, api_key: 'your_api_key', pelias: {endpoint: 'self.hosted/pelias'})
  7. Configure MaxMind Local for IP lookups (Experimental)

    master

    MaxMind Local (:maxmind_local) is an experimental feature for local IP geocoding. It supports two formats:

    1. Binary file: Requires the geoip (or jgeoip for JRuby) gem. Specify the path using the :file option.
    2. CSV file: Requires importing the data into an SQL database. Specify the package using the :package option (e.g., :city or :country).

    To use CSV files, you can use provided Rake tasks to generate migrations and import data.

  8. Configure Ipstack for IP lookups

    master

    To use Ipstack for IP address geocoding, configure the ip_lookup option to :ipstack and provide your API key. You can also pass optional parameters such as :hostname, :security, :fields, and :language.

    Geocoder.configure(ip_lookup: :ipstack, api_key: "your_ipstack_api_key")