Skip to content

geolocate_control

Stable

A button that centres the map on the user's location, with optional tracking.

The example's template and LiveView, read from the files that run in the preview.

lib/maplibrex_demo_web/examples/geolocate_control_example.html.heex
<div id="geolocate-control-example">
  <.example_frame error={@map_error} error_id="example-geolocate-map-error">
    <.map
      id="example-geolocate-map"
      center={[0, 25]}
      zoom={1.2}
      style={basemap(@theme)}
      events={["map:error"]}
      class="h-full w-full"
    />
  </.example_frame>

  <%!-- With track_user_location the button keeps the map on the position as
        it changes; pressing it again stops tracking. A new option replaces
        the control in the same place, still tracking if it was. --%>
  <.geolocate_control
    id="example-geolocate"
    map_id="example-geolocate-map"
    track_user_location={@track_user_location}
    show_user_location={@show_user_location}
    show_accuracy_circle={@show_accuracy_circle}
    fit_bounds_options={%{"maxZoom" => 14}}
    events={[
      "geolocate:location_found",
      "geolocate:user_location_updated",
      "geolocate:location_error",
      "geolocate:tracking_started",
      "geolocate:tracking_stopped"
    ]}
  />

  <div class="space-y-4 border-t border-line px-4 py-4">
    <.example_group id="example-geolocate-assigns" label={gettext("Set assigns")}>
      <.form
        for={@options}
        id="example-geolocate-options"
        phx-change="options"
        class="flex flex-wrap gap-x-6 gap-y-2 py-1.5"
      >
        <.example_checkbox field={@options[:track_user_location]} label="track_user_location" />
        <.example_checkbox field={@options[:show_user_location]} label="show_user_location" />
        <.example_checkbox field={@options[:show_accuracy_circle]} label="show_accuracy_circle" />
      </.form>
    </.example_group>

    <.example_note
      :if={@status == "waiting"}
      id="example-geolocate-hint"
      icon="hero-cursor-arrow-rays-micro"
    >
      {gettext(
        "Press the location button in the map's top-right corner. The browser asks for permission first; the position it shares arrives in this LiveView as an event."
      )}
    </.example_note>

    <%!-- geolocate:location_error: the browser did not share a position. --%>
    <div
      :if={@error}
      id="example-geolocate-error"
      role="status"
      class="flex items-start gap-2.5 rounded-ui border border-danger/40 bg-danger-soft px-3 py-2.5 text-ui"
    >
      <.icon name="hero-map-pin-mini" class="mt-px size-5 shrink-0 text-danger" />
      <p>
        <span class="font-bold">{gettext("Your location is not available.")}</span>
        {explain(@error)}
        <span class="mt-0.5 block font-mono text-label text-ink-muted">
          {@error.code}: {@error.message}
        </span>
      </p>
    </div>

    <.example_note
      :if={@status == "found"}
      id="example-geolocate-found"
      icon="hero-check-circle-micro"
    >
      {gettext("The browser shared its position.")}
      <span :if={@track_user_location}>
        {gettext("Press the button again to stop tracking it.")}
      </span>
    </.example_note>
  </div>

  <%!-- The control's events keep these current. --%>
  <.example_readout values={[
    status: @status,
    tracking: @tracking,
    location: location(@location),
    accuracy: accuracy(@accuracy)
  ]} />
</div>
lib/maplibrex_demo_web/examples/geolocate_control_example.ex
defmodule MaplibrexDemoWeb.Examples.GeolocateControlExample do
  @moduledoc """
  The example of `<.geolocate_control>`: a button that asks the browser for
  its position and follows it, with the control's events telling the server
  what happened, including when the browser does not share a position. Its
  options follow the assigns, also while it tracks the position.
  """
  use MaplibrexDemoWeb, :live_view

  import MaplibreX.Components
  import MaplibrexDemoWeb.Examples.ExampleComponents

  # Demo plumbing, not needed in an application: applies the page's locale,
  # copies each map event to the page's Events tab and keeps @theme on the
  # page's light or dark theme.
  on_mount MaplibrexDemoWeb.Examples.Plumbing

  # OpenFreeMap's basemap for the page's theme: the map's style follows @theme.
  defp basemap("dark"), do: "https://tiles.openfreemap.org/styles/dark"
  defp basemap("light"), do: "https://tiles.openfreemap.org/styles/liberty"

  @impl true
  def mount(_params, _session, socket) do
    socket =
      socket
      |> assign(status: "waiting", tracking: false, location: nil, accuracy: nil)
      |> assign(error: nil, map_error: nil)
      |> assign(track_user_location: true, show_user_location: true, show_accuracy_circle: true)
      |> assign_options()

    {:ok, socket}
  end

  # From the checkboxes. A new option replaces the control in the same place;
  # one that was tracking the position goes on tracking it.
  @impl true
  def handle_event("options", params, socket) do
    {:noreply,
     socket
     |> assign(
       track_user_location: params["track_user_location"] == "true",
       show_user_location: params["show_user_location"] == "true",
       show_accuracy_circle: params["show_accuracy_circle"] == "true"
     )
     |> assign_options()}
  end

  # Events from the control. The browser asks the visitor for permission the
  # first time the button is pressed; the answer arrives as one of these.

  def handle_event("geolocate:location_found", %{"coords" => coords}, socket) do
    {:noreply,
     assign(socket,
       status: "found",
       location: [coords["latitude"], coords["longitude"]],
       accuracy: coords["accuracy"],
       error: nil
     )}
  end

  # While tracking, this arrives for every position the browser gives, also
  # once the visitor has moved the map away from it.
  def handle_event("geolocate:user_location_updated", %{"coords" => coords}, socket) do
    {:noreply,
     assign(socket,
       location: [coords["latitude"], coords["longitude"]],
       accuracy: coords["accuracy"]
     )}
  end

  # A refusal (code 1) also ends tracking, without a tracking_stopped event.
  def handle_event("geolocate:location_error", %{"code" => code, "message" => message}, socket) do
    tracking = socket.assigns.tracking and code != 1

    {:noreply,
     assign(socket, status: "error", tracking: tracking, error: %{code: code, message: message})}
  end

  def handle_event("geolocate:tracking_started", _payload, socket) do
    {:noreply, assign(socket, :tracking, true)}
  end

  def handle_event("geolocate:tracking_stopped", _payload, socket) do
    {:noreply, assign(socket, :tracking, false)}
  end

  def handle_event("map:error", %{"error" => message}, socket) do
    {:noreply, assign(socket, :map_error, message)}
  end

  defp assign_options(socket) do
    form =
      to_form(%{
        "track_user_location" => socket.assigns.track_user_location,
        "show_user_location" => socket.assigns.show_user_location,
        "show_accuracy_circle" => socket.assigns.show_accuracy_circle
      })

    assign(socket, :options, form)
  end

  # The codes of the browser's GeolocationPositionError.
  defp explain(%{code: 1}) do
    gettext(
      "The browser denied access to your location. Allow location for this page in the browser's site settings, then press the location button again."
    )
  end

  defp explain(%{code: 2}) do
    gettext(
      "The browser could not find your position. Check that location services are on, then press the location button again."
    )
  end

  defp explain(_error) do
    gettext("Finding your position took too long. Press the location button to try again.")
  end

  defp location(nil), do: "—"
  defp location([lat, lng]), do: "#{round4(lat)}, #{round4(lng)}"

  defp accuracy(nil), do: "—"
  defp accuracy(metres), do: "#{round(metres)} m"

  defp round4(number), do: Float.round(number / 1, 4)
end