UNPKG

just-location

Version:
120 lines (119 loc) 4.36 kB
import Location from './location' export default { install: (Vue, options) => { let wxLocation = () => { return new Promise((resolve, reject) => { let wx = options.wx || window.wx wx.ready(() => { wx.getLocation({ type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02' success: function (res) { resolve({ lat: res.latitude, lng: res.longitude }) }, fail: function () { amapLocation().then(res => { resolve(res) }) } }) }) }) } let amapLocation = () => { let map = new options.aMap.Map(document.createElement('div'), { resizeEnable: true }) return new Promise((resolve, reject) => { map.plugin('AMap.Geolocation', () => { let myLocation = new options.aMap.Geolocation({ enableHighAccuracy: true, // 是否使用高精度定位,默认:true timeout: 3000, // 超过10秒后停止定位,默认:无穷大 buttonOffset: new options.aMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20) zoomToAccuracy: true, // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false buttonPosition: 'RB', panToLocation: true, noGeoLocation: 0 // 0: 可以使用浏览器定位 1: 手机设备禁止使用浏览器定位 2: PC上禁止使用浏览器定位 3: 所有终端禁止使用浏览器定位 }) myLocation.getCurrentPosition() options.aMap.event.addListener(myLocation, 'complete', (res) => { if (res.addressComponent) { resolve({ lat: res.position.getLat(), lng: res.position.getLng(), cityName: res.addressComponent.city }) } else { // 拿不到address 确实定位失败,Chrome、火狐以及部分套壳浏览器接入的定位服务在国外, // 有较大限制,失败率高,message字段包含‘Get geolocation failed.’信息 myLocation.getCityInfo((status, result) => { if (status === 'complete') { resolve({ lat: res.position.getLat(), lng: res.position.getLng(), cityName: result.city }) } else { resolve({ lat: res.position.getLat(), lng: res.position.getLng(), cityName: '' }) } }) } }) // 返回定位信息 options.aMap.event.addListener(myLocation, 'error', () => { resolve(false) }) // 返回定位出错信息 }) }) } let appLocation = () => { return new Promise((resolve, reject) => { let bridge = options.app || window.LeFitWebViewJavascriptBridge bridge.callHandler('getLocation', {}, (res) => { if (!res || res.errCode === -1) { window.alert('为了更好的体验,请开启定位权限') resolve(false) } else { resolve({ lat: res.latitude, lng: res.longitude }) } }) }) } let MyLocation = Vue.extend(Location) let tpl = new MyLocation({ el: document.createElement('div') }) document.body.appendChild(tpl.$el) Vue.prototype.$getLocation = (obj) => { let data = obj || {} tpl.loading = data.loading || true let type = data.type || '' return new Promise((resolve, reject) => { if (type === 'app') { appLocation().then(res => { tpl.loading = false resolve(res) }) } else if (type === 'wx') { wxLocation().then(res => { tpl.loading = false resolve(res) }) } else { amapLocation().then(res => { tpl.loading = false resolve(res) }) } }) } } }