Last active
December 5, 2020 15:15
-
-
Save cristovao-trevisan/8921f8e3da316d048f4abced8e467701 to your computer and use it in GitHub Desktop.
Svelte Geolocation API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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