Geocoder

Build Status Coverage Status Module Version Hex Docs Total Download License Last Updated

A simple, efficient geocoder/reverse geocoder with a built-in cache. This library is flexible and extensible: you can replace the provider, the HTTP client, the JSON codec, the caching store and the workers.

Out of the box
Providers OpenStreetMap (default, no key needed), Google Maps, OpenCage Data
HTTP clients HTTPoison (default), Req, Hackney
JSON codecs Jason (default), JSX
Caching stores in memory (Geocoder.Store)

Installation

Add :geocoder to your mix.exs dependencies, together with the HTTP client and the JSON codec you want to use. They are optional dependencies of Geocoder, so that you only install the ones you need. With the defaults:

def deps do
  [
    {:geocoder, "~> 2.4"},
    {:httpoison, "~> 2.1 or ~> 3.0"},
    {:jason, "~> 1.2"}
  ]
end

Update your mix dependencies:

mix deps.get

Geocoder requires Elixir 1.17 and Erlang/OTP 27 or later.

Getting started

Add Geocoder.Supervisor to your supervision tree:

children = [
  Geocoder.Supervisor
]

This starts a pool of workers and the cache with all the default options. Then:

{:ok, coordinates} = Geocoder.call("Toronto, ON")
{:ok, coordinates} = Geocoder.call({43.653226, -79.383184})

coordinates.lat
coordinates.lon
coordinates.location.formatted_address

Geocoder.call/2 returns one result. Geocoder.call_list/2 returns all the results of the provider:

{:ok, list_of_coordinates} = Geocoder.call_list("Toronto, ON")

You can pass options that will be passed on to the provider, for example:

Geocoder.call("Toronto, ON", language: "es")

See here and here for a list of supported parameters for the Google Maps provider (Geocoder.Providers.GoogleMaps).

Other options change how the call itself behaves:

Option Default
:timeout 5000 milliseconds to wait for the result. The calling process exits when it elapses
:store true false skips the cache lookup
:stream_to a pid to send the result to, instead of waiting for it
:pool_name :geocoder_workers the pool to use, when you start several
:supervisor Geocoder.Supervisor the supervisor whose strategy routes the call
:worker_config overrides the configuration for this call, see below

Guides

Configuration

Configuration is done by passing options to Geocoder.Supervisor. See Geocoder.Config for all the options and their defaults.

Using a different provider

The default provider is OpenStreetMap, which needs no key. To use another one:

children = [
  {Geocoder.Supervisor, worker_config: [provider: Geocoder.Providers.GoogleMaps, key: "some_api_key"]}
]

You can write your own provider by implementing the Geocoder.Provider behaviour. The ones in lib/geocoder/providers/ are good examples.

The configuration can also be changed for one call. The worker_config of the call is merged into the one given to the supervisor, so you only pass what differs:

Geocoder.call("Toronto, ON",
  worker_config: [provider: Geocoder.Providers.OpenCageData, key: "another_api_key"]
)

This is one way to fall back to another provider.

Fallback and traffic split

A single supervisor can run several providers and route your calls over them. With strategy: :fallback, the next provider is tried when one fails:

children = [
  {Geocoder.Supervisor,
   strategy: :fallback,
   pools: [
     [pool_name: :google, worker_config: [provider: Geocoder.Providers.GoogleMaps, key: "some_api_key"]],
     [pool_name: :osm]
   ]}
]

With strategy: :split, each call goes to one of them according to weights:

children = [
  {Geocoder.Supervisor,
   strategy: :split,
   pools: [
     [pool_name: :google, weight: 90, worker_config: [provider: Geocoder.Providers.GoogleMaps, key: "some_api_key"]],
     [pool_name: :osm, weight: 10]
   ]}
]

Geocoder.call/2 and Geocoder.call_list/2 are used as usual. See the fallback and traffic split guides.

Using a different HTTP client

The default HTTP client is HTTPoison. Req and Hackney are also supported, and you can write your own by implementing the Geocoder.HttpClient behaviour. For example, to use Req, add {:req, "~> 0.7"} to your dependencies instead of httpoison, and select the client:

children = [
  {Geocoder.Supervisor, worker_config: [http_client: Geocoder.HttpClient.Req]}
]

Options for the HTTP client, such as a timeout or a proxy, go in http_client_opts:

children = [
  {Geocoder.Supervisor,
   worker_config: [
     http_client_opts: [proxy: "my.proxy.server:3128", proxy_auth: {"username", "password"}]
   ]}
]

The HTTP clients guide has the details for each client.

Using a different JSON codec

The default JSON codec is Jason. Geocoder.JSONCodec.JSX is also provided, and you can use any module implementing the Geocoder.JSONCodec behaviour:

children = [
  {Geocoder.Supervisor, worker_config: [json_codec: Geocoder.JSONCodec.JSX]}
]

Using a different store

The default caching store is Geocoder.Store, a simple in-memory cache held by a process. It is unbounded and never expires, see the architecture guide.

You can provide your own store module, using Geocoder.Store as a model:

children = [
  {Geocoder.Supervisor, store_module: MyApp.MyStore}
]

Telemetry

Geocoder emits telemetry events for each geocoding request (including whether it was served from the cache) and for each HTTP request made to the provider. See Geocoder.Telemetry for the list of events, measurements and metadata.

:telemetry.attach(
  "geocoder-requests",
  [:geocoder, :request, :stop],
  fn _event, %{duration: duration}, %{provider: provider, cache: cache, result: result}, _config ->
    ms = System.convert_time_unit(duration, :native, :millisecond)
    IO.puts("#{inspect(provider)} #{result} (cache #{cache}) in #{ms}ms")
  end,
  nil
)

The events never contain the address, the coordinates or the provider key.

Testing

:geocoder supports three external providers (i.e. sources):

To run the tests for these, and any future providers, you'll want to pass a PROVIDER environment variable as well as the API_KEY:

PROVIDER=google API_KEY="mykey" mix test

By default, the tests run against the Fake provider.

To avoid making external requests in the test suite of your own application, use the Fake provider there as well.

The fake provider is configured with a :data map, as shown below. An address or coordinates that match none of its keys return {:error, nil} ({:ok, []} with Geocoder.call_list/2).

The keys of the data map must be in either regex or tuple format (specifically a {lat, lng} style pair of floats).

[
  {Geocoder.Supervisor, worker_config:
    [
      provider: Geocoder.Providers.Fake,
      data: %{
        ~r/.*New York, NY.*/ => %{
          lat: 40.7587905,
          lon: -73.9787755,
          bounds: %{
            bottom: 40.7587405,
            left: -73.9788255,
            right: -73.9787255,
            top: 40.7588405,
          },
          location: %{
            city: "New York",
            country: "United States",
            country_code: "us",
            county: "New York County",
            formatted_address: "30 Rockefeller Plaza, New York, NY 10112, United States of America",
            postal_code: "10112",
            state: "New York",
            street: "Rockefeller Plaza",
            street_number: "30"
          },
        },
        {40.7587905, -73.9787755} => %{
          lat: 40.7587905,
          lon: -73.9787755,
          bounds: %{
            bottom: 40.7587405,
            left: -73.9788255,
            right: -73.9787255,
            top: 40.7588405,
          },
          location: %{
            city: "New York",
            country: "United States",
            country_code: "us",
            county: "New York County",
            formatted_address: "30 Rockefeller Plaza, New York, NY 10112, United States of America",
            postal_code: "10112",
            state: "New York",
            street: "Rockefeller Plaza",
            street_number: "30"
          },
        }
      }
    ]
   }
  ...
]

Copyright (c) 2015-2026 Cyrus Nouroozi and contributors

The source code is licensed under the MIT License.