Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/metonym/svelte-geolocation

Geolocation API wrapper for Svelte
https://github.com/metonym/svelte-geolocation

coordinates geolocation latitude longitude svelte svelte-component

Last synced: 11 days ago
JSON representation

Geolocation API wrapper for Svelte

Awesome Lists containing this project

README

        

# svelte-geolocation

[![NPM][npm]][npm-url]

> Svelte bindings for the [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API)

Declaratively access the Geolocation API in Svelte components. This package provides a simple way to fetch the geolocation coordinates of the device.

**Features**

- Bind to coordinates in a 2-tuple (`[longtitude: number, latitude: number]`).
- Slotted states: loading/error/success.
- Programmatic access to the Geolocation API (e.g., `geolocation.getCurrentPosition`).
- Watch the current position.

---

## Installation

```bash
# npm
npm i -D svelte-geolocation

# pnpm
pnpm i -D svelte-geolocation

# Bun
bun i -D svelte-geolocation

# Yarn
yarn add -D svelte-geolocation
```

## Usage

### Binding coordinates

Set `getPosition` to `true` to automatically invoke the `geolocation.getCurrentPosition` method and bind to the `coords` prop to retrieve the `[longitude, latitude]` of the device. The default `coords` value is `[-1, -1]`.

```svelte

import Geolocation from "svelte-geolocation";

let coords = [];

{JSON.stringify(coords)}

```

### Binding geolocation position

Bind to `position` to access all properties from [GeolocationPosition](https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPosition).

```svelte

import Geolocation from "svelte-geolocation";

let position;

{JSON.stringify(position, null, 2)}

```

### Programmatic usage

By default, the component will not automatically fetch the geolocation coordinates. This method must be programmatically triggered.

```svelte no-eval

let ref;

// Access the component instance and programmatically invoke the method.
$: ref?.getGeolocationPosition({ enableHighAccuracy: true });

```

### Slotted states

This example shows programmatic usage of `geolocation.getCurrentPosition`.

Using the default slot, you can destructure the following props:

- **`coords`**: geolocation coordinates in `[lng, lat]` format
- **`loading`**: `true` when the geolocation is being fetched
- **`success`**: `true` if the geolocation has been obtained
- **`error`**: `true` if an error occurs when fetching the geolocation
- **`notSupported`**: `true` if the device does not support the Geolocation API

```svelte

import Geolocation from "svelte-geolocation";

let getPosition = false;

(getPosition = true)}> Get geolocation

{#if notSupported}
Your browser does not support the Geolocation API.
{:else}
{#if loading}
Loading...
{/if}
{#if success}
{JSON.stringify(coords)}
{/if}
{#if error}
An error occurred. {error.code} {error.message}
{/if}
{/if}

```

### Watching Position

Set `watch` to `true` to invoke the `geolocation.watchPosition` method and get informed if the user changes position.

```svelte

import Geolocation from "svelte-geolocation";

let getPositionAgain = false;
let detail = {};

(getPositionAgain = !getPositionAgain)}>
Get Position

{
detail = e.detail;
}}
/>

{JSON.stringify(detail, null, 2)}

```

### Dispatched Events

You can listen to dispatched events as an alternative to binding.

- **`on:position`**: fired when `geolocation.getCurrentPosition` succeeds
- **`on:error`**: fired when `geolocation.getCurrentPosition` fails

```svelte

import Geolocation from "svelte-geolocation";

let events = [];

{
events = [...events, e.detail];
console.log(e.detail); // GeolocationPosition
}}
on:error={(e) => {
events = [...events, e.detail];
console.log(e.detail); // GeolocationError
}}
/>

Dispatched events:

{#each events as event}

{JSON.stringify(event, null, 2)}

{/each}
```

### Geolocation options

Specify [Geolocation position options](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions) using the `options` prop.

```svelte no-eval

import Geolocation from "svelte-geolocation";

let options = {
/**
* @type {boolean}
* @default false
*/
enableHighAccuracy: true,

/**
* @type {number}
* @default Infinity
*/
timeout: 5000, // milliseconds

/**
* @type {number}
* @default 0
*/
maximumAge: 60 * 60 * 1000, // milliseconds
};

```

## API

### Props

| Prop name | Value |
| :----------- | :--------------------------------------------------------------------------------------------------------------------------------- |
| coords | `[longitude: number, latitude: number];` (default: `[-1, -1]`) |
| position | [GeolocationPosition](https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPosition) |
| options | [PositionOptions](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions) |
| getPosition | `boolean` (default: `false`) |
| watch | `boolean` (default: `false`) |
| loading | `boolean` (default: `false`) |
| success | `boolean` (default: `false`) |
| error | `false` or [GeolocationPositionError](https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPositionError) (default:`false`) |
| notSupported | `boolean` (default: `false`) |

### Accessors

Use the `bind:this` directive to access the accessor methods available on the component instance.

```svelte no-display

import Geolocation from "svelte-geolocation";

let geolocation;

$: geolocation?.getGeolocationPosition({ enableHighAccuracy: true });

```

#### API

```ts
interface Accessors {
/** Watch the geolocation position. */
watchPosition: (options: PositionOptions) => undefined | number;

/** Programmatically get the geolocation position. */
getGeolocationPosition: (options: PositionOptions) => Promise;

/** Clear the Geolocation watcher. */
clearWatcher: (watcherId: number) => void;
}
```

## Examples

- [examples/sveltekit](examples/sveltekit)
- [examples/vite](examples/vite)
- [examples/rollup](examples/rollup)
- [examples/webpack](examples/webpack)

## Changelog

[CHANGELOG.md](CHANGELOG.md)

## License

[MIT](LICENSE)

[npm]: https://img.shields.io/npm/v/svelte-geolocation.svg?style=for-the-badge&color=%23ff3e00
[npm-url]: https://npmjs.com/package/svelte-geolocation