Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

geocoder

> 编程语言
Open source

Complete Ruby geocoding solution.

6.4K stars0 likes5 views
WebsiteGitHub

About

Complete Ruby geocoding solution.

Geocoder

Complete geocoding solution for Ruby. Key features:

  • Forward and reverse geocoding.
  • IP address geocoding.
  • Connects to more than 40 APIs worldwide.
  • Performance-enhancing features like caching.
  • Integrates with ActiveRecord and Mongoid.
  • Basic geospatial queries: search within radius (or rectangle, or ring).

Compatibility:

  • Ruby versions: 2.5+ and JRuby.
  • Databases: MySQL, PostgreSQL, SQLite, and MongoDB.
  • Rails: 5.x, 6.x, 7.x and 8.x.
  • Works outside of Rails with the json (for MRI) or json_pure (for JRuby) gem.

Table of Contents

Basic Features:

  • Basic Search
  • Geocoding Objects
  • Geospatial Database Queries
  • Geocoding HTTP Requests
  • Geocoding Service ("Lookup") Configuration

Advanced Features:

  • Performance and Optimization
  • Advanced Model Configuration
  • Advanced Database Queries
  • Geospatial Calculations
  • Batch Geocoding
  • Testing
  • Error Handling
  • Command Line Interface

The Rest:

  • Technical Discussions
  • Troubleshooting
  • Known Issues
  • Reporting Issues
  • Contributing

See Also:

  • Guide to Geocoding APIs (formerly part of this README)

Basic Search

In its simplest form, Geocoder takes an address and searches for its latitude/longitude coordinates:

ruby
results = Geocoder.search("Paris")
results.first.coordinates
# => [48.856614, 2.3522219]  # latitude and longitude

The reverse is possible too. Given coordinates, it finds an address:

ruby
results = Geocoder.search([48.856614, 2.3522219])
results.first.address
# => "Hôtel de Ville, 75004 Paris, France"

You can also look up the location of an IP address:

ruby
results = Geocoder.search("172.56.21.89")
results.first.coordinates
# => [30.267153, -97.7430608]
results.first.country
# => "United States"

The success and accuracy of geocoding depends entirely on the API being used to do these lookups. Most queries work fairly well with the default configuration, but every application has different needs and every API has its particular strengths and weaknesses. If you need better coverage for your application you'll want to get familiar with the large number of supported APIs, listed in the API Guide.

Geocoding Objects

To automatically geocode your objects:

1. Your model must provide a method that returns an address to geocode. This can be a single attribute, but it can also be a method that returns a string assembled from different attributes (eg: city, state, and country). For example, if your model has street, city, state, and country attributes you might do something like this:

ruby
def address
  [street, city, state, country].compact.join(', ')
end

2. Your model must have a way to store latitude/longitude coordinates. With ActiveRecord, add two attributes/columns (of type float or decimal) called latitude and longitude. For MongoDB, use a single field (of type Array) called coordinates (i.e., field :coordinates, type: Array). (See Advanced Model Configuration for using different attribute names.)

3. In your model, tell geocoder where to find the object's address:

ruby
geocoded_by :address

This adds a geocode method which you can invoke via callback:

ruby
after_validation :geocode

Reverse geocoding (given lat/lon coordinates, find an address) is similar:

ruby
reverse_geocoded_by :latitude, :longitude
after_validation :reverse_geocode

With any geocoded objects, you can do the following:

ruby
obj.distance_to([43.9,-98.6])  # distance from obj to point
obj.bearing_to([43.9,-98.6])   # bearing from obj to point
obj.bearing_from(obj2)         # bearing from obj2 to obj

The bearing_from/to methods take a single argument which can be: a [lat,lon] array, a geocoded object, or a geocodable address (string). The distance_from/to methods also take a units argument (:mi, :km, or :nm for nautical miles). See Distance and Bearing below for more info.

One More Thing for MongoDB!

Before you can call geocoded_by you'll need to include the necessary module using one of the following:

ruby
include Geocoder::Model::Mongoid
include Geocoder::Model::MongoMapper

Latitude/Longitude Order in MongoDB

Everywhere coordinates are passed to methods as two-element arrays, Geocoder expects them to be in the order: [lat, lon]. However, as per the GeoJSON spec, MongoDB requires that coordinates be stored longitude-first ([lon, lat]), so internally they are stored "backwards." Geocoder's methods attempt to hide this, so calling obj.to_coordinates (a method added to the object by Geocoder via geocoded_by) returns coordinates in the conventional order:

ruby
obj.to_coordinates  # => [37.7941013, -122.3951096] # [lat, lon]

whereas calling the object's coordinates attribute directly (obj.coordinates by default) returns the internal representation which is probably the reverse of what you want:

ruby
obj.coordinates     # => [-122.3951096, 37.7941013] # [lon, lat]

So, be careful.

Use Outside of Rails

To use Geocoder with ActiveRecord and a framework other than Rails (like Sinatra or Padrino), you will need to add this in your model before calling Geocoder methods:

ruby
extend Geocoder::Model::ActiveRecord

Geospatial Database Queries

For ActiveRecord models:

To find objects by location, use the following scopes:

ruby
Venue.near('Omaha, NE, US')                   # venues within 20 miles of Omaha
Venue.near([40.71, -100.23], 50)              # venues within 50 miles of a point
Venue.near([40.71, -100.23], 50, units: :km)  # venues within 50 kilometres of a point
Venue.geocoded                                # venues with coordinates
Venue.not_geocoded                            # venues without coordinates

With geocoded objects you can do things like this:

ruby
if obj.geocoded?
  obj.nearbys(30)                       # other objects within 30 miles
  obj.distance_from([40.714,-100.234])  # distance from arbitrary point to object
  obj.bearing_to("Paris, France")       # direction from object to arbitrary point
end

For MongoDB-backed models:

Please do not use Geocoder's near method. Instead use MongoDB's built-in geospatial query language, which is faster. Mongoid also provides a DSL for geospatial queries.

Geocoding HTTP Requests

Geocoder adds location and safe_location methods to the standard Rack::Request object so you can easily look up the location of any HTTP request by IP address. For example, in a Rails controller or a Sinatra app:

ruby
# returns Geocoder::Result object
result = request.location

The location method is vulnerable to trivial IP address spoofing via HTTP headers. If that's a problem for your application, use safe_location instead, but be aware that safe_location will not try to trace a request's originating IP through proxy headers; you will instead get the location of the last proxy the request passed through, if any (excepting any proxies you have explicitly whitelisted in your Rack config).

Note that these methods will usually return nil in test and development environments because things like "localhost" and "0.0.0.0" are not geocodable IP addresses.

Geocoding Service ("Lookup") Configuration

Geocoder supports a variety of street and IP address geocoding services. The default lookups are :nominatim for street addresses and :ipinfo_io for IP addresses. Please see the API Guide for details on specific geocoding services (not all settings are supported by all services).

To create a Rails initializer with sample configuration:

bash
rails generate geocoder:config

Some common options are:

ruby
# config/initializers/geocoder.rb
Geocoder.configure(
  # street address geocoding service (default :nominatim)
  lookup: :yandex,

  # IP address geocoding service (default :ipinfo_io)
  ip_lookup: :maxmind,

  # to use an API key:
  api_key: "...",

  # geocoding service request timeout, in seconds (default 3):
  timeout: 5,

  # set default units to kilometers:
  units: :km,

  # caching (see Caching section below for details):
  cache: Redis.new,
  cache_options: {
    expiration: 1.day, # Defaults to `nil`
    prefix: "another_key:" # Defaults to `geocoder:`
  }
)

Please see lib/geocoder/configuration.rb for a complete list of configuration options. Additionally, some lookups have their own special configuration options which are directly supported by Geocoder. For example, to specify a value for Google's bounds parameter:

ruby
# with Google:
Geocoder.search("Middletown", bounds: [[40.6,-77.9], [39.9,-75.9]])

Please see the source code for each lookup to learn about directly supported parameters. Parameters which are not directly supported can be specified using the :params option, which appends options to the query string of the geocoding request. For example:

ruby
# Nominatim's `countrycodes` parameter:
Geocoder.search("Rome", params: {countrycodes: "us,ca"})

# Google's `region` parameter:
Geocoder.search("Rome", params: {region: "..."})

Configuring Multiple Services

You can configure multiple geocoding services at once by using the service's name as a key for a sub-configuration hash, like this:

ruby
Geocoder.configure(

  timeout: 2,
  cache: Redis.new,

  yandex: {
    api_key: "...",
    timeout: 5
  },

  baidu: {
    api_key: "..."
  },

  maxmind: {
    api_key: "...",
    service: :omni
  }

)

Lookup-specific settings override global settings so, in this example, the timeout for all lookups is 2 seconds, except for Yandex which is 5.

Performance and Optimization

Database Indices

In MySQL and Postgres, queries use a bounding box to limit the number of points over which a more precise distance calculation needs to be done. To take advantage of this optimisation, you need to add a composite index on latitude and longitude. In your Rails migration:

ruby
add_index :table, [:latitude, :longitude]

In MongoDB, by default, the methods geocoded_by and reverse_geocoded_by create a geospatial index. You can avoid index creation with the :skip_index option, for example:

ruby
include Geocoder::Model::Mongoid
geocoded_by :address, skip_index: true

Avoiding Unnecessary API Requests

Geocoding only needs to be performed under certain conditions. To avoid unnecessary work (and quota usage) you will probably want to geocode an object only when:

  • an address is present
  • the address has been changed since last save (or it has never been saved)

The exact code will vary depending on the method you use for your g

Issues· 55 open

View all issuesOpen on GitHub
  • #1713

    Add Presend to IP Address Lookups in README_API_GUIDE.md

    Updated Sep 21, 2026
  • #1708

    Mapbox: support the new Geocoding v6 API

    Updated Jun 5, 2026
  • #1701

    Amazon Location Service - New API

    Updated Dec 8, 2025
  • #1699

    http_headers is used for both IP and location lookups when different services are configured

    Updated Nov 9, 2025
  • #1696

    New Google Places API

    Updated Oct 1, 2025
  • #1689

    Unable to perform structured Nominatim lookup

    Updated Jun 16, 2025
  • #1676

    [MapBox lookup] Ommited result

    Updated Jun 7, 2025
  • #1628

    Allow `address_components_of_type` for Geocoder::Result::Test

    Updated Jun 5, 2025
  • #1685

    Documentation and/or consistency issue

    Updated Apr 24, 2025
  • #1669

    Support for PostGIS in model geocoding

    Updated Nov 26, 2024

> Tags

Rubygeocodinggeocoding-apigeocoding-objectsgeocoding-requests

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 24, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言