# Geocoder

[![Build Status](https://github.com/CyrusNuevoDia/geocoder/actions/workflows/elixir.yml/badge.svg)](https://github.com/CyrusNuevoDia/geocoder/actions/workflows/elixir.yml)
[![Coverage Status](https://coveralls.io/repos/github/CyrusNuevoDia/geocoder/badge.svg?branch=master)](https://coveralls.io/github/CyrusNuevoDia/geocoder?branch=master)
[![Module Version](https://img.shields.io/hexpm/v/geocoder.svg)](https://hex.pm/packages/geocoder)
[![Hex Docs](https://img.shields.io/badge/hex-docs-lightgreen.svg)](https://hexdocs.pm/geocoder/)
[![Total Download](https://img.shields.io/hexpm/dt/geocoder.svg)](https://hex.pm/packages/geocoder)
[![License](https://img.shields.io/hexpm/l/geocoder.svg)](https://github.com/CyrusNuevoDia/geocoder/blob/master/LICENSE.md)
[![Last Updated](https://img.shields.io/github/last-commit/CyrusNuevoDia/geocoder.svg)](https://github.com/CyrusNuevoDia/geocoder/commits/master)

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:

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

Update your mix dependencies:

```bash
mix deps.get
```

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

## Getting started

Add `Geocoder.Supervisor` to your supervision tree:

```elixir
children = [
  Geocoder.Supervisor
]
```

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

```elixir
{: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:

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

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

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

See [here](https://developers.google.com/maps/documentation/geocoding/intro#geocoding) and [here](https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding) 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](guides/multiple-pools.md) |
| `:supervisor` | `Geocoder.Supervisor` | the supervisor whose [strategy](guides/fallback-provider.md) routes the call |
| `:worker_config` | | overrides the configuration for this call, see below |

## Guides

* [Architecture](guides/architecture.md): the processes, what happens during a call, the cache, timeouts and the extension points
* [HTTP clients](guides/http-clients.md): setting up Req, HTTPoison or Hackney, or writing your own client
* [Multiple pools](guides/multiple-pools.md): running several pools, each with its own provider and cache
* [Falling back to another provider](guides/fallback-provider.md): trying a second provider when the first one is down
* [Splitting traffic between providers](guides/traffic-split.md): sending a percentage of the calls to each provider
* [Custom workers](guides/custom-workers.md): running your own code around every request

## 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:

```elixir
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:

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

This is one way to [fall back to another provider](guides/fallback-provider.md).

### 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:

```elixir
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:

```elixir
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](guides/fallback-provider.md) and [traffic split](guides/traffic-split.md) 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](https://hexdocs.pm/req), add `{:req, "~> 0.7"}` to your dependencies instead of `httpoison`, and select the client:

```elixir
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`:

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

The [HTTP clients guide](guides/http-clients.md) 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:

```elixir
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](guides/architecture.md#the-cache).

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

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

### Telemetry

Geocoder emits [telemetry](https://hexdocs.pm/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.

```elixir
: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):

* `Geocoder.Providers.GoogleMaps`
* `Geocoder.Providers.OpenCageData`
* `Geocoder.Providers.OpenStreetMaps`

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`:

```shell
PROVIDER=google API_KEY="mykey" mix test
```

By default, the tests run against the [`Fake`](./lib/geocoder/providers/fake.ex) provider.

To avoid making external requests in the test suite of your own application, use the [`Fake`](./lib/geocoder/providers/fake.ex) 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](https://hexdocs.pm/elixir/Regex.html) or
[tuple](https://hexdocs.pm/elixir/Tuple.html) format (specifically a `{lat, lng}` style pair of floats).

```elixir
[
  {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"
          },
        }
      }
    ]
   }
  ...
]
```

## Related & Alternative Packages

* https://github.com/amotion-city/lib_lat_lon
* https://github.com/navinpeiris/geoip
* https://github.com/elixir-geolix/geolix

## Copyright and License

Copyright (c) 2015-2026 Cyrus Nouroozi and contributors

The source code is licensed under the [MIT License](./LICENSE.md).
