Skip to content

Commit

Permalink
feat: Add autoTrigger prop to GeolocateControl (#87)
Browse files Browse the repository at this point in the history
  • Loading branch information
ciscorn authored Jan 23, 2025
1 parent 9f1e1ba commit 9728ba6
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/content/examples/geolocate/Geolocate.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
position="top-left"
positionOptions={{ enableHighAccuracy: true }}
trackUserLocation={true}
showAccuracyCircle={true}
ontrackuserlocationstart={() => log('trackuserlocationstart')}
ontrackuserlocationend={() => log('trackuserlocationend')}
ongeolocate={(ev) => log(`geolocate ${JSON.stringify(ev.coords, null, 2)}`)}
Expand Down
17 changes: 16 additions & 1 deletion src/lib/maplibre/controls/GeolocateControl.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@
type GeolocateEvent = Event<maplibregl.GeolocateControl> & object;
interface Props extends maplibregl.GeolocateControlOptions {
// Position on the map where the control placed
position?: maplibregl.ControlPosition;
// Automatically call trigger() to start locating the user
autoTrigger?: boolean;
control?: maplibregl.GeolocateControl;
// Events
// https://maplibre.org/maplibre-gl-js/docs/API/classes/GeolocateControl/#events
ontrackuserlocationend?: Listener<GeolocateEvent>;
Expand All @@ -23,6 +27,8 @@
}
let {
position,
control = $bindable(),
autoTrigger = false,
ontrackuserlocationend,
ontrackuserlocationstart,
onuserlocationlostfocus,
Expand All @@ -36,13 +42,22 @@
const mapCtx = getMapContext();
if (!mapCtx.map) throw new Error('Map instance is not initialized.');
let control: maplibregl.GeolocateControl | null = null;
$effect(() => {
control && mapCtx.map?.removeControl(control);
control = new maplibregl.GeolocateControl(options);
mapCtx.map?.addControl(control, position);
});
$effect(() => {
if (mapCtx.map?.loaded()) {
control?.trigger();
} else {
mapCtx.map?.once('load', () => {
control?.trigger();
});
}
});
$effect(() => resetEventListener(control, 'trackuserlocationstart', ontrackuserlocationstart));
$effect(() => resetEventListener(control, 'trackuserlocationend', ontrackuserlocationend));
$effect(() => resetEventListener(control, 'userlocationlostfocus', onuserlocationlostfocus));
Expand Down

0 comments on commit 9728ba6

Please sign in to comment.