├── .npmignore ├── .prettierrc ├── .editorconfig ├── .gitignore ├── nuxt ├── plugin.js └── index.js ├── .eslintrc.js ├── src ├── helpers.js ├── wrapper.js └── vue-geolocation-api.js ├── LICENSE.md ├── package.json ├── types └── index.d.ts └── README.md /.npmignore: -------------------------------------------------------------------------------- 1 | .git 2 | .editorconfig 3 | .eslintrx.js 4 | .prettierrc 5 | build 6 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | trailingComma: "es5" 2 | tabWidth: 2 3 | semi: false 4 | singleQuote: true 5 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | root = true 3 | 4 | [*] 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | /dist 4 | 5 | # local env files 6 | .env.local 7 | .env.*.local 8 | 9 | # Log files 10 | npm-debug.log* 11 | yarn-debug.log* 12 | yarn-error.log* 13 | 14 | # Editor directories and files 15 | .idea 16 | .vscode 17 | *.suo 18 | *.ntvs* 19 | *.njsproj 20 | *.sln 21 | *.sw* 22 | -------------------------------------------------------------------------------- /nuxt/plugin.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import VGA from 'vue-geolocation-api' 3 | 4 | export default (ctx, inject) => { 5 | // eslint-disable-next-line 6 | const Component = VGA.VueGeolocationApi(Vue, <%= JSON.stringify(options, null, 2) %>) 7 | const geolocation = new Component() 8 | ctx.app.$geolocation = geolocation 9 | inject('geolocation', geolocation) 10 | } 11 | -------------------------------------------------------------------------------- /nuxt/index.js: -------------------------------------------------------------------------------- 1 | const { resolve } = require('path') 2 | 3 | module.exports = function(moduleOptions) { 4 | const options = Object.assign({}, this.options.geolocation, moduleOptions) 5 | this.addPlugin({ 6 | src: resolve(__dirname, 'plugin.js'), 7 | fileName: 'vue-geolocation-api.js', 8 | options, 9 | }) 10 | } 11 | 12 | module.exports.meta = require('../package.json') 13 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { 4 | node: true 5 | }, 6 | extends: ["plugin:vue/essential", "@vue/prettier"], 7 | rules: { 8 | "no-console": process.env.NODE_ENV === "production" ? "error" : "off", 9 | "no-debugger": process.env.NODE_ENV === "production" ? "error" : "off" 10 | }, 11 | parserOptions: { 12 | parser: "babel-eslint" 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /src/helpers.js: -------------------------------------------------------------------------------- 1 | export const getCurrentPosition = options => 2 | new Promise((resolve, reject) => 3 | navigator.geolocation.getCurrentPosition(resolve, reject, options) 4 | ) 5 | 6 | export const positionToObject = ({ coords, timestamp }) => ({ 7 | coords: { 8 | latitude: coords.latitude, 9 | longitude: coords.longitude, 10 | altitude: coords.altitude, 11 | accuracy: coords.accuracy, 12 | altitudeAccuracy: coords.altitudeAccuracy, 13 | heading: coords.heading, 14 | speed: coords.speed, 15 | }, 16 | timestamp, 17 | }) 18 | -------------------------------------------------------------------------------- /src/wrapper.js: -------------------------------------------------------------------------------- 1 | import VueGeolocationApi from './vue-geolocation-api' 2 | 3 | export function install(Vue, options) { 4 | if (install.installed) return 5 | const Component = VueGeolocationApi(Vue, options) 6 | const geolocation = new Component() 7 | install.installed = true 8 | Vue.prototype.$geolocation = geolocation 9 | } 10 | 11 | const plugin = { install } 12 | 13 | let GlobalVue = null 14 | if (typeof window !== 'undefined') { 15 | GlobalVue = window.Vue 16 | } else if (typeof global !== 'undefined') { 17 | GlobalVue = global.Vue 18 | } 19 | if (GlobalVue) { 20 | GlobalVue.use(plugin) 21 | } 22 | 23 | export default { 24 | install, 25 | VueGeolocationApi, 26 | } 27 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright 2019 Antonio Eduardo (https://skyatura.com.br/) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vue-geolocation-api", 3 | "author": "Antonio Eduardo (https://skyatura.com.br/)", 4 | "keywords": [ 5 | "geolocation", 6 | "vue", 7 | "nuxt", 8 | "geojson" 9 | ], 10 | "repository": "github:skyatura/vue-geolocation-api", 11 | "version": "0.1.21", 12 | "license": "MIT", 13 | "types": "types/index.d.ts", 14 | "scripts": { 15 | "build": "npm run build:umd & npm run build:es & npm run build:unpkg", 16 | "build:umd": "rollup --config build/rollup.config.js --format umd --file dist/vue-geolocation-api.umd.js", 17 | "build:es": "rollup --config build/rollup.config.js --format es --file dist/vue-geolocation-api.esm.js", 18 | "build:unpkg": "rollup --config build/rollup.config.js --format iife --file dist/vue-geolocation-api.min.js", 19 | "lint": "vue-cli-service lint", 20 | "serve": "vue-cli-service serve --open src/components/vue-geolocation-api.vue" 21 | }, 22 | "main": "dist/vue-geolocation-api.umd.js", 23 | "module": "dist/vue-geolocation-api.esm.js", 24 | "unpkg": "dist/vue-geolocation-api.min.js", 25 | "browser": { 26 | "./sfc": "src/vue-geolocation-api.js" 27 | }, 28 | "dependencies": { 29 | "vue": "^2.6.12" 30 | }, 31 | "devDependencies": { 32 | "@babel/core": "^7.12.10", 33 | "@vue/cli-plugin-eslint": "^3.12.1", 34 | "@vue/cli-service": "^4.5.9", 35 | "@vue/eslint-config-prettier": "^4.0.1", 36 | "babel-eslint": "^10.1.0", 37 | "eslint": "^5.16.0", 38 | "eslint-plugin-vue": "^5.2.3", 39 | "rollup": "^0.68.2", 40 | "rollup-plugin-async": "^1.2.0", 41 | "rollup-plugin-babel": "^4.3.2", 42 | "rollup-plugin-vue": "^4.7.2", 43 | "vue-template-compiler": "^2.6.12" 44 | }, 45 | "files": [ 46 | "dist/*", 47 | "types/*", 48 | "src/*", 49 | "nuxt/*", 50 | "*.json" 51 | ] 52 | } 53 | -------------------------------------------------------------------------------- /types/index.d.ts: -------------------------------------------------------------------------------- 1 | import Vue, { VueConstructor, PluginObject } from 'vue' 2 | 3 | export namespace GeolocationPlugin { 4 | interface PositionOptions { 5 | enableHighAccuracy?: boolean 6 | timeout?: number 7 | maximumAge?: number 8 | } 9 | 10 | interface GeoJSONPoint { 11 | type: 'Point' 12 | coordinates: [number, number] 13 | } 14 | 15 | interface PositionCoords { 16 | readonly latitude: number 17 | readonly altitude: number 18 | readonly longitude: number 19 | readonly accuracy: number 20 | readonly altitudeAccuracy: number 21 | readonly heading: number 22 | readonly speed: number 23 | } 24 | 25 | type PositionTimestamp = DOMTimeStamp 26 | 27 | interface Position { 28 | readonly coords: PositionCoords 29 | readonly timestamp: PositionTimestamp 30 | } 31 | 32 | interface Options { 33 | watch: boolean 34 | options: PositionOptions 35 | } 36 | 37 | interface Geolocation { 38 | coords: PositionCoords | null 39 | timestamp: PositionTimestamp | null 40 | geoJSON: GeoJSONPoint | null 41 | loading: boolean 42 | supported: boolean 43 | 44 | getCurrentPosition: (options?: Options) => Promise 45 | setOption: (key: string, value: number | boolean) => void 46 | checkSupport: () => boolean 47 | } 48 | } 49 | 50 | declare module 'vue/types/vue' { 51 | interface Vue { 52 | readonly $geolocation: GeolocationPlugin.Geolocation 53 | } 54 | interface VueConstructor { 55 | readonly $geolocation: GeolocationPlugin.Geolocation 56 | } 57 | } 58 | 59 | declare module '@nuxt/types' { 60 | interface NuxtAppOptions { 61 | readonly $geolocation: GeolocationPlugin.Geolocation 62 | } 63 | interface Context { 64 | readonly $geolocation: GeolocationPlugin.Geolocation 65 | } 66 | } 67 | 68 | interface VueGeolocation extends PluginObject {} 69 | 70 | export default VueGeolocation 71 | -------------------------------------------------------------------------------- /src/vue-geolocation-api.js: -------------------------------------------------------------------------------- 1 | import { getCurrentPosition, positionToObject } from './helpers' 2 | 3 | export const VueGeolocationApi = (Vue, defaultOptions = {}) => 4 | Vue.extend({ 5 | data: () => 6 | Object.assign( 7 | { 8 | options: {}, 9 | watch: false, 10 | }, 11 | defaultOptions, 12 | { 13 | _watcher: null, 14 | position: null, 15 | loading: false, 16 | supported: null, 17 | } 18 | ), 19 | computed: { 20 | coords() { 21 | const { position } = this 22 | return position ? position.coords : null 23 | }, 24 | timestamp() { 25 | const { position } = this 26 | return position ? position.timestamp : null 27 | }, 28 | geoJSON() { 29 | const { coords } = this 30 | if (!coords) return null 31 | const { latitude, longitude, altitude } = coords 32 | const coordinates = [latitude, longitude] 33 | return altitude === null ? coordinates : [...coordinates, altitude] 34 | }, 35 | }, 36 | watch: { 37 | watch: '_watch', 38 | options: { 39 | deep: true, 40 | handler: '_watch', 41 | }, 42 | }, 43 | beforeDestroy() { 44 | this.clearTimer() 45 | }, 46 | created() { 47 | if (typeof window === 'undefined') return 48 | this.checkSupport() 49 | this._watch() 50 | }, 51 | methods: { 52 | checkSupport() { 53 | const supported = 54 | typeof window !== 'undefined' && 55 | navigator && 56 | 'geolocation' in navigator 57 | return (this.supported = supported) 58 | }, 59 | async getCurrentPosition(options) { 60 | if (!this.checkSupport()) return 61 | const params = Object.assign({}, this.options, options || {}) 62 | this.loading = true 63 | const response = await getCurrentPosition(params) 64 | return this._setCurrentPosition(response) 65 | }, 66 | setOption(key, value) { 67 | this.options = Object.assign({}, this.options, { [key]: value }) 68 | }, 69 | _setCurrentPosition(position) { 70 | if (!position) { 71 | this.position = null 72 | } 73 | this.loading = false 74 | this.$emit('changed:position', position) 75 | return (this.position = positionToObject(position)) 76 | }, 77 | _watch() { 78 | if (!this.watch) return this._clearWatch() 79 | this._watchPosition() 80 | }, 81 | _clearWatch() { 82 | if (!this._watcher) return 83 | navigator.geolocation.clearWatch(this._watcher) 84 | this._watcher = null 85 | }, 86 | _watchPosition(_success, _error, options) { 87 | if (!this.checkSupport()) return 88 | this._clearWatch() 89 | this.loading = true 90 | this._watcher = navigator.geolocation.watchPosition( 91 | _success || (position => this._setCurrentPosition(position)), 92 | _error || (positionError => console.error(positionError)), 93 | options 94 | ) 95 | }, 96 | }, 97 | }) 98 | 99 | export default VueGeolocationApi 100 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Vue Geolocation API 2 | A simple reactive wrapper for [Geolocation Web API](https://developer.mozilla.org/pt-BR/docs/Web/API/Geolocation) 3 | 4 | ## Features 5 | * Customizable 6 | * Reactive geolocation position 7 | * Simple watcher control 8 | * SSR Compatibility 9 | * GeoJSON output 10 | 11 | ## Setup 12 | Install with npm 13 | ```bash 14 | npm install --save vue-geolocation-api 15 | ``` 16 | Install with yarn 17 | ```bash 18 | yarn add vue-geolocation-api 19 | ``` 20 | 21 | ### Vue instance 22 | ```js 23 | import Vue from 'vue' 24 | import VueGeolocationApi from 'vue-geolocation-api' 25 | 26 | Vue.use(VueGeolocationApi/*, { ...options } */) 27 | ``` 28 | ### Nuxt 29 | Add to [modules](https://nuxtjs.org/guide/modules) section at your **nuxt.config.js** 30 | ```js 31 | module.exports = { 32 | modules: [ 33 | 'vue-geolocation-api/nuxt', 34 | ], 35 | geolocation: { 36 | // watch: true, 37 | }, 38 | } 39 | ``` 40 | 41 | ## Usage 42 | 43 | ### Computed properties 44 | ```js 45 | export default { 46 | // ... 47 | computed: { 48 | inRange() { 49 | const coords = this.$geolocation.coords 50 | if (!coords) return '?' 51 | return distanceFrom(coords, this.destination) > 150 52 | } 53 | } 54 | } 55 | ``` 56 | *Note that distanceFrom is not included in this package, if you need this feature I recommend to use with [@turf/distance](https://www.npmjs.com/package/@turf/distance) or [geo-distance](https://www.npmjs.com/package/geo-distance)* 57 | 58 | ### Component templates 59 | ```html 60 | 67 | ``` 68 | 69 | ### Watch statements 70 | ```js 71 | export default { 72 | // ... 73 | watch: { 74 | inRange(reached) { 75 | if (reached !== true) return 76 | console.log('Congratulations, you arrived') 77 | this.$geolocation.watch = false // Stop watching location 78 | } 79 | } 80 | } 81 | ``` 82 | 83 | ## Outputs 84 | ### $geolocation.position *[[Position](https://developer.mozilla.org/pt-BR/docs/Web/API/Position)]* 85 | Exposes the results from [getCurrentPosition](https://developer.mozilla.org/pt-BR/docs/Web/API/Geolocation/getCurrentPosition) or the last result from [watchPosition](https://developer.mozilla.org/pt-BR/docs/Web/API/Geolocation/watchPosition). 86 | **Default or unavailable:** null 87 | 88 | ### $geolocation.loading *[Boolean]* 89 | If ***true***, means the location is currently being executed. 90 | 91 | ### $geolocation.supported *[Boolean]* 92 | If ***true*** means the location api is available in the browser. 93 | If ***false*** means the location api is not available in the browser. 94 | if ***null*** means the support wasn't verified yet. 95 | 96 | ### $geolocation.coords *[[Coordinates](https://developer.mozilla.org/pt-BR/docs/Web/API/Coordinates)]* 97 | Alias for `$geolocation.position.coords` 98 | **Default or unavailable:** null 99 | 100 | ### $geolocation.timestamp [[Timestamp](https://www.unixtimestamp.com/)] 101 | Alias for `$geolocation.position.timestamp` 102 | **Default or unavailable:** null 103 | 104 | ### $geolocation.geoJSON [[GeoJSON](http://geojson.org/) Point] 105 | Formatted coordinates. 106 | **Default or unavailable:** null 107 | 108 | ## Options 109 | 110 | ### $geolocation.watch *[Boolean]* 111 | If ***true*** will initiate `watchPosition`. 112 | If ***false*** stop `watchPosition`. 113 | This property **can** be changed dynamically and **will** react to it's changes. 114 | 115 | ### $geolocation.options *[[PositionOptions](https://developer.mozilla.org/pt-BR/docs/Web/API/PositionOptions)]* 116 | Defines the parameters that will be used by `getCurrentPosition` and `watchPosition`. 117 | Changing this property will trigger an `watchPosition` reload if currently watching. 118 | **Important:** This property is only reactive if you replace it entirely. If you just want to change one options check the method `setOption` 119 | 120 | ## Methods 121 | 122 | ### $geolocation.getCurrentPosition(?options) *[Promised [Position](https://developer.mozilla.org/pt-BR/docs/Web/API/Position)]* 123 | Simply wraps the `navigator.geolocation.getCurrentPosition` as a Promise. 124 | 125 | ### $geolocation.setOption(key, value) *[Undefined]* 126 | Reactively updates the `key` property in `$geolocation.options` with `value`. 127 | 128 | ### $geolocation.checkSupport() *[Boolean]* 129 | Forces the `$geolocation.supported` to update. 130 | 131 | ## Contributing or Issuing 132 | ### Coming soon... 133 | # 134 | ### Created by [@SkyaTura](https://github.com/SkyaTura) 135 | --------------------------------------------------------------------------------