Skip to content

Instantly share code, notes, and snippets.

@cristovao-trevisan
Last active December 5, 2020 15:15
Show Gist options
  • Save cristovao-trevisan/8921f8e3da316d048f4abced8e467701 to your computer and use it in GitHub Desktop.
Save cristovao-trevisan/8921f8e3da316d048f4abced8e467701 to your computer and use it in GitHub Desktop.
Svelte Geolocation API
import { writable, get } from 'svelte/store'
const initialState = {
supported: false,
allowed: false,
error: null,
location: null,
loading: false,
timestamp: -1,
}
export const geolocation = writable(initialState)
if ('geolocation' in navigator) {
geolocation.update(state => ({ ...state, supported: true }))
}
export const readLocation = () => new Promise((resolve, reject) => {
if (get(geolocation).supported) {
geolocation.update(state => ({ ...state, loading: true }))
navigator.geolocation.getCurrentPosition(({ coords, timestamp }) => {
geolocation.set({ loading: false, supported: true, allowed: true, location: coords, timestamp, error: null })
resolve({ geolocation: coords, timestamp })
}, (error) => {
geolocation.update(state => ({ ...state, error, loading: false }))
reject(error)
}, {
enableHighAccuracy: true,
maximumAge: 10000,
timeout: 5000,
})
} else {
reject(new Error('Seu navegador não é suportado'))
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment