Skip to content

Commit 9b42913

Browse files
committed
feat(example): add watch support for geolocation
1 parent 97dfe29 commit 9b42913

2 files changed

Lines changed: 63 additions & 2 deletions

File tree

examples/api/src-tauri/capabilities/mobile.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
"geolocation:allow-request-permissions",
1717
"geolocation:allow-watch-position",
1818
"geolocation:allow-get-current-position",
19+
"geolocation:allow-clear-watch",
1920
"haptics:allow-impact-feedback",
2021
"haptics:allow-notification-feedback",
2122
"haptics:allow-selection-feedback",

examples/api/src/views/Geolocation.svelte

Lines changed: 62 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,18 @@
22
import {
33
checkPermissions,
44
requestPermissions,
5-
getCurrentPosition
5+
getCurrentPosition,
6+
7+
watchPosition,
8+
clearWatch
9+
610
} from '@tauri-apps/plugin-geolocation'
711
812
export let onMessage
913
14+
let pos = null
15+
let watchId = null
16+
1017
async function getPosition() {
1118
let permissions = await checkPermissions()
1219
if (
@@ -17,13 +24,66 @@
1724
}
1825
1926
if (permissions.location === 'granted') {
20-
getCurrentPosition().then(onMessage).catch(onMessage)
27+
getCurrentPosition().then((position) => {
28+
pos = position
29+
onMessage(position)
30+
}).catch((err) => {
31+
pos = null
32+
onMessage(err)
33+
})
34+
} else {
35+
onMessage('permission denied')
36+
}
37+
}
38+
39+
async function watchPos() {
40+
let permissions = await checkPermissions()
41+
if (
42+
permissions.location === 'prompt' ||
43+
permissions.location === 'prompt-with-rationale'
44+
) {
45+
permissions = await requestPermissions(['location'])
46+
}
47+
48+
if (permissions.location === 'granted') {
49+
watchId = await watchPosition({
50+
enableHighAccuracy: true,
51+
timeout: 5000,
52+
maximumAge: 0
53+
}, (position) => {
54+
pos = position
55+
onMessage(position)
56+
})
57+
onMessage('watchId: ' + watchId)
2158
} else {
2259
onMessage('permission denied')
2360
}
2461
}
62+
63+
async function stopWatching() {
64+
await clearWatch(watchId)
65+
watchId = null
66+
pos = null
67+
}
68+
2569
</script>
2670

2771
<button class="btn" id="cli-matches" on:click={getPosition}>
2872
Get Position
2973
</button>
74+
75+
<button class="btn" on:click={watchPos}>
76+
Watch Position
77+
</button>
78+
79+
<button class="btn" on:click={stopWatching}>
80+
Stop Watching
81+
</button>
82+
83+
{#if watchId}
84+
<span>Watch ID: {watchId}</span>
85+
{/if}
86+
87+
{#if pos}
88+
<pre>{JSON.stringify(pos, null, 2)}</pre>
89+
{/if}

0 commit comments

Comments
 (0)