useGeolocation
Purpose
Enable a controller to subscribe to a user's location, and update the state of the controller when the user's location changes.
Side Effects
The controller will setup an an event listener using navigator.watchPosition
Usage
useGeolocation
Parameters | Type | Purpose | Default | |
---|---|---|---|---|
controller | Controller | The instance of the controller to install the behaviour on. This allows the mixin to automatically register cleanup on the controller's disconnect . | this | |
options | Object | Options to modify how the location data is polled. Any of the options allowed by the options parameter accepted by Geolocation.getCurrentPosition() | - | |
update (Optional) | Function(position) | A callback that is fired when the user's position updates | - | |
position | Position | The position object returned by the Geolocation.getCurrentPosition() call | - | |
error (Optional) | Function(positionError) | A callback that is fired when there is an error, either because the user denied permission or because of a bad GPS signal | - | |
positionError | GeolocationPositionError | The error object raised by the Geolocation service | - |
How to Use
import {Controller} from '@hotwired/stimulus';
import {useGeolocation} from 'stimulus-library';
export default class extends Controller {
connect() {
this.location = useGeolocation(this, {enableHighAccuracy: true}, this.update, this.error);
}
update(position) {
this.element.innerHTML = `Located at: ${position.latitude} ${position.longitude}`;
}
error(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
this.element.innerHTML = "User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
this.element.innerHTML = "Location information is unavailable.";
break;
case error.TIMEOUT:
this.element.innerHTML = "The request to get user location timed out.";
break;
default:
this.element.innerHTML = "An unknown error occurred.";
break;
}
}
}