-
Notifications
You must be signed in to change notification settings - Fork 0
/
geolocation.js
40 lines (36 loc) · 1.21 KB
/
geolocation.js
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
import GOOGLE_API_KEY from "../config/keys"
import callApi from "./apiCaller"
const getLocationFromIp = async () => {
const url = `https://www.googleapis.com/geolocation/v1/geolocate?key=${GOOGLE_API_KEY}`
const init = { method: "POST" }
return callApi(url, init)
}
// Turn an HTML5 Geoposition object into a regular object
// https://github.com/zeke/geoposition-to-object
export const geopositionToObject = geoposition => ({
timestamp: geoposition.timestamp,
coords: {
accuracy: geoposition.coords.accuracy,
latitude: geoposition.coords.latitude,
longitude: geoposition.coords.longitude
}
})
export const getCurrentPosition = async () =>
new Promise(resolve => {
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`) // eslint-disable-line no-console
getLocationFromIp().then(response => {
const { lat, lng } = response.location
const defaultLocation = {
title: "Current Location",
coords: { latitude: lat, longitude: lng }
}
resolve(defaultLocation)
})
}
const options = {
timeout: 5000,
maximumAge: 60000
}
window.navigator.geolocation.getCurrentPosition(resolve, error, options)
})