Skip to main content
Api

<ScriptMapLibreGeolocateControl>

Adds MapLibre's geolocate button to the nearest parent map. The button asks the browser for the user's location and moves the camera there.

<script setup lang="ts">
import type { ScriptMapLibreGeolocateControlEmits } from '@nuxt/scripts'

const message = ref('')

function onError(event: ScriptMapLibreGeolocateControlEmits['error'][0]) {
  message.value = event.code === 1 ? 'Location permission denied.' : event.message
}
</script>

<template>
  <ScriptMapLibreMap map-style="https://tiles.openfreemap.org/styles/liberty" :center="[147.33, -42.88]">
    <ScriptMapLibreGeolocateControl
      position="top-left"
      :options="{ trackUserLocation: true }"
      @error="onError"
      @unavailable="message = 'Location is not available in this browser.'"
    />
  </ScriptMapLibreMap>
  <p role="status">
    {{ message }}
  </p>
</template>

new maplibregl.GeolocateControl() reads options and position once, when it creates the control. To apply a change, change the component key.

The component exposes the MapLibre control as control. Call control.value.trigger() to request the location from code.

Events

The component emits every GeolocateControl event with MapLibre's event object:

  • geolocate fires when the browser returns a position.
  • error fires when the browser returns an error.
  • outofmaxbounds fires when the position is outside the map's maxBounds.
  • trackuserlocationstart and trackuserlocationend fire when tracking starts and stops. They need trackUserLocation.
  • userlocationfocus and userlocationlostfocus fire when the camera locks to or leaves the user's location.

Permission denied

Geolocation can fail in two ways. The component reports both.

  • If the user denies the permission prompt, error fires with code 1. MapLibre then disables the button.
  • If the permission was already denied when the control loaded, MapLibre disables the button and fires no event. The component emits unavailable with 'permission-denied'.
  • If the browser has no Geolocation API, the component emits unavailable with 'unsupported'.

Geolocation needs a secure context. On a plain HTTP origin other than localhost, the browser denies it.

positionMapLibre.ControlPosition
optionsMapLibre.GeolocateControlOptions
Was this page helpful?