6.5 KiB · text History 44bc4f7
defmodule CartosnapApp.Geocoder do
  @moduledoc """
  Finds places by name in OpenStreetMap through a
  [Photon](https://github.com/komoot/photon) geocoder, for pinning a photo
  to where it was taken. Photon rather than Nominatim because it is built
  for search-as-you-type; Nominatim's usage policy forbids autocomplete.

  Two servers, asked in order, as the sibling apps do. The primary is our
  own, behind tiles.neiam.org: fast, but its index covers North America
  only. When it errors or finds nothing, komoot's public instance is asked:
  worldwide, but slower and offered on a fair-use basis, which the caller
  respects by debouncing keystrokes. Set with
  `config :cartosnap_app, :geocoder, base_url: ..., fallback_url: ...`
  (`PHOTON_URL` / `PHOTON_FALLBACK_URL`; an empty fallback turns it off).

  Nothing depends on this: on any failure the search offers nothing, and a
  pin can still be dropped on the map by hand.
  """

  require Logger

  alias CartosnapApp.Geocoder.Place

  @min_length 3

  @doc "Places matching `query`, best first. Queries under three characters find nothing."
  def search(query, opts \\ []) when is_binary(query) do
    query = String.trim(query)
    limit = Keyword.get(opts, :limit, 8)

    if String.length(query) < @min_length do
      {:ok, []}
    else
      # Asked for extra: roads are dropped and duplicates merged afterwards.
      params = [q: query, limit: limit * 2, lang: "en"] ++ bias(opts[:near])
      primary = fetch(base_url(), params, limit)

      case {primary, fallback_url()} do
        {{:ok, [_ | _]}, _} -> primary
        {_, nil} -> primary
        # The primary's error is the one reported if both fail: it's ours to fix.
        {_, fallback} -> with {:error, _} <- fetch(fallback, params, limit), do: primary
      end
    end
  end

  @doc """
  What to call the place at `{lat, lon}`, for naming an area of a trip.
  With `scale: :town` (the default) that's the city or town it's in; with
  `scale: :neighbourhood`, the district or neighbourhood, for areas within
  one city. Falls back up the hierarchy (to the county, the state) when
  the finer name isn't known.

  `{:ok, name}`, `{:ok, nil}` when nothing is known there, or
  `{:error, reason}` when neither server answered.
  """
  def reverse(lat, lon, opts \\ []) when is_number(lat) and is_number(lon) do
    scale = Keyword.get(opts, :scale, :town)
    params = [lat: lat, lon: lon, lang: "en", limit: 1]
    primary = fetch_reverse(base_url(), params, scale)

    case {primary, fallback_url()} do
      {{:ok, name}, _} when is_binary(name) -> primary
      {_, nil} -> primary
      {_, fallback} -> with {:error, _} <- fetch_reverse(fallback, params, scale), do: primary
    end
  end

  @neighbourhood_keys ~w(district locality name city town village county state)
  @town_keys ~w(city town village county state)

  defp fetch_reverse(base_url, params, scale) do
    keys = if scale == :neighbourhood, do: @neighbourhood_keys, else: @town_keys

    case request(base_url <> "/reverse", params) do
      {:ok, %{status: 200, body: %{"features" => [%{"properties" => props} | _]}}} ->
        {:ok, Enum.find_value(keys, &present(props[&1]))}

      {:ok, %{status: 200}} ->
        {:ok, nil}

      {:ok, %{status: status}} ->
        Logger.debug("geocoder: #{status} from #{base_url} reversing #{inspect(params)}")
        {:error, {:http, status}}

      {:error, reason} ->
        Logger.debug("geocoder: #{inspect(reason)} from #{base_url} reversing")
        {:error, reason}
    end
  end

  defp present(value) when is_binary(value) and value != "", do: value
  defp present(_), do: nil

  defp request(url, params) do
    [
      url: url,
      params: params,
      headers: [{"user-agent", "CartoSnap photo locations"}],
      receive_timeout: 10_000,
      retry: false
    ]
    # How tests stub the server: `req_options: [plug: {Req.Test, ...}]`.
    |> Keyword.merge(Keyword.get(config(), :req_options, []))
    |> Req.get()
  end

  # Ranks places near the photo's current position first, without
  # excluding anything elsewhere.
  defp bias({lat, lon}) when is_number(lat) and is_number(lon), do: [lat: lat, lon: lon]
  defp bias(_), do: []

  defp fetch(base_url, params, limit) do
    case request(base_url <> "/api", params) do
      {:ok, %{status: 200, body: %{"features" => features}}} when is_list(features) ->
        places =
          features
          |> Enum.reject(&road?/1)
          |> Enum.map(&to_place/1)
          |> Enum.reject(&is_nil/1)
          |> Enum.uniq_by(&{&1.name, &1.locality, &1.admin_area, &1.country})
          |> Enum.take(limit)

        {:ok, places}

      {:ok, %{status: status}} ->
        Logger.debug("geocoder: #{status} from #{base_url} for #{inspect(params[:q])}")
        {:error, {:http, status}}

      {:error, reason} ->
        Logger.debug("geocoder: #{inspect(reason)} from #{base_url} for #{inspect(params[:q])}")
        {:error, reason}
    end
  end

  defp to_place(%{"properties" => props, "geometry" => %{"coordinates" => [lon, lat]}})
       when is_number(lat) and is_number(lon) do
    case props["name"] || props["city"] do
      name when is_binary(name) and name != "" ->
        %Place{
          id:
            "#{props["osm_type"]}#{props["osm_id"]}-#{Float.round(lat * 1.0, 5)},#{Float.round(lon * 1.0, 5)}",
          name: name,
          category: category(props),
          locality: props["city"] || props["town"] || props["village"],
          admin_area: props["state"],
          country: props["country"],
          lat: lat * 1.0,
          lon: lon * 1.0
        }

      _ ->
        nil
    end
  end

  defp to_place(_feature), do: nil

  # A bare street or a house number is rarely where a photo "was".
  defp road?(%{"properties" => props}) do
    props["osm_key"] == "highway" or props["type"] == "street" or
      (props["osm_key"] == "place" and props["osm_value"] == "house")
  end

  defp road?(_feature), do: false

  # "leisure: stadium" -> "Stadium".
  defp category(%{"osm_value" => value}) when is_binary(value) and value not in ["yes", ""],
    do: value |> String.replace("_", " ") |> String.capitalize()

  defp category(%{"type" => type}) when is_binary(type), do: String.capitalize(type)
  defp category(_props), do: nil

  defp base_url do
    config()
    |> Keyword.get(:base_url, "https://tiles.neiam.org/geocode")
    |> String.trim_trailing("/")
  end

  defp fallback_url do
    case Keyword.get(config(), :fallback_url, "https://photon.komoot.io") do
      url when url in [nil, ""] -> nil
      url -> String.trim_trailing(url, "/")
    end
  end

  defp config, do: Application.get_env(:cartosnap_app, :geocoder, [])
end