Created
September 27, 2019 19:52
-
-
Save nandomoreirame/607480aa351c0981605b350e678bb655 to your computer and use it in GitHub Desktop.
GeoLocation Vuex Store
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
const state = { | |
loading: false, | |
geolocation: {}, | |
}; | |
const mutations = { | |
TOGGLE_LOADING(state, payload) { | |
state.loading = !!payload; | |
}, | |
CHANGE_GEOLOCATION(state, payload) { | |
state.geolocation = payload; | |
}, | |
}; | |
const actions = { | |
currentLocation({ commit }) { | |
const { geolocation } = navigator; | |
commit('TOGGLE_LOADING', true); | |
return new Promise((resolve, reject) => { | |
if (geolocation) { | |
geolocation | |
.getCurrentPosition(({ coords }) => { | |
const currentPosition = { | |
long: coords.longitude, | |
lat: coords.latitude, | |
}; | |
commit('CHANGE_GEOLOCATION', currentPosition); | |
commit('TOGGLE_LOADING', false); | |
resolve(currentPosition); | |
}, | |
(err) => { | |
commit('TOGGLE_LOADING', false); | |
reject(err); | |
}); | |
} else { | |
console.info('Geolocation is not supported by this browser.'); | |
commit('TOGGLE_LOADING', false); | |
reject(); | |
} | |
}); | |
}, | |
}; | |
export const store = { | |
namespaced: true, | |
state, | |
mutations, | |
actions, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment