Geolocation Component
Keep browser geolocation state inside your store with the Geolocation type.
Setup
javascript
import { createStore } from "@inglorious/store"
import { Geolocation } from "@inglorious/web/geolocation"
const store = createStore({
types: { Geolocation },
autoCreateEntities: true,
})
1
2
3
4
5
6
7
2
3
4
5
6
7
With autoCreateEntities, the store automatically creates a geolocation entity.
Entity State
The geolocation entity tracks:
isSupported— whethernavigator.geolocationis availableisLoading— whether a current position request or the first watch result is pendingisWatching— whether a geolocation watch is activeposition— the latest normalized{ coords, timestamp }valueerror— the latest normalized{ code, message }errorwatchId— the browser watch ID, ornull
Events
Use api.notify() to drive the geolocation flow.
javascript
api.notify("geolocationRequest", {
enableHighAccuracy: true,
timeout: 5000,
})
api.notify("geolocationWatch")
api.notify("geolocationUnwatch")
1
2
3
4
5
6
7
2
3
4
5
6
7
What each event does
geolocationRequest— request the current device position oncegeolocationWatch— start watching position updatesgeolocationUnwatch— stop the active watch
Example
javascript
import { mount, html } from "@inglorious/web"
import { store } from "./store.js"
const renderApp = (api) => {
const geolocation = api.getEntity("geolocation")
const position = geolocation.position
return html`
<section>
<h2>Geolocation</h2>
<p>Supported: ${geolocation.isSupported ? "yes" : "no"}</p>
<p>Loading: ${geolocation.isLoading ? "yes" : "no"}</p>
<p>
Position:
${position
? html`${position.coords.latitude.toFixed(4)},
${position.coords.longitude.toFixed(4)}`
: "unknown"}
</p>
<p>Error: ${geolocation.error ? geolocation.error.message : "none"}</p>
<button
@click=${() =>
api.notify("geolocationRequest", {
enableHighAccuracy: true,
timeout: 5000,
})}
>
Request Current Position
</button>
<button @click=${() => api.notify("geolocationWatch")}>
Start Watch
</button>
<button @click=${() => api.notify("geolocationUnwatch")}>
Stop Watch
</button>
</section>
`
}
mount(store, renderApp, document.getElementById("root"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
Notes
The Geolocation type normalizes browser errors and keeps the state in your entity store so your UI can react predictably to permission, loading, and watch changes.
Inglorious Web