// 高德地图获取定位 // #ifdef H5 import keyConfig from './mapKeyConfig'; import AMapLoader from '@amap/amap-jsapi-loader'; // #endif /** * 传入经纬度返回地址 * @param {Array} lnglat 经纬度 * @param {Boolean} geocode 是否解析地址信息 * @returns {Promise} 返回promise **/ const getAddress = (lnglat, geocode) => { return new Promise((resolve, reject) => { if (!geocode) { resolve(); return; } const geocoder = new AMap.Geocoder({ city: '全国', //城市设为北京,默认:“全国” radius: 1000, //范围,默认:500 }); geocoder.getAddress(lnglat, (status, result) => { if (status === 'complete' && result.regeocode) { resolve(result.regeocode); return; } reject(result); console.error('根据经纬度查询地址失败'); }); }); }; /** * 获取定位信息 * @param {Boolean} geocode 是否解析地址信息 * @returns {Promise} 返回定位信息 **/ const Geolocation = (AMap, geocode, options) => { return new Promise((resolve, reject) => { AMap.plugin('AMap.Geolocation', () => { const geolocation = new AMap.Geolocation(options); //getCurrentPosition 调用此方法可实现打开页面自动定位 geolocation.getCurrentPosition(async (status, res) => { if (status === 'complete') { // 定位成功 const { position } = res; const arrPosition = Array.isArray(position) ? position : [position.lng, position.lat]; // todo pc和app打印结果不一致 const address = await getAddress(arrPosition, geocode); resolve({ ...res, position: arrPosition, address }); return; } // 定位失败 uni.showToast({ title: '定位失败,请开启定位后重试', icon: 'none', }); reject(res); }); }); }); }; //geocode 是否解析地址 const appGetLocation = (option) => { return new Promise((resolve, reject) => { uni.getLocation({ ...option, success: async (res) => { resolve(res); }, fail: (err) => { reject(err); uni.showToast({ title: '定位失败,请开启定位后重试', icon: 'none', }); }, }); }); }; const defaultOpt = { // 默认配置 type: 'wgs84', isHighAccuracy: true, //开启高精度定位 }; async function getAppLocation(option) { // 当前运行在app const appRes = await appGetLocation(option); const newRes = { ...appRes }; if (option.geocode) { // 默认false,是否解析地址信息 const { province, city, district, street, streetNum } = appRes.address; newRes.formattedAddress = `${province}${city}${district}${street}${streetNum}`; // 自定义的参数,拼接地址 } return newRes; } async function getWebLocation(option) { window._AMapSecurityConfig = { securityJsCode: keyConfig.securityJsCode, }; const AMap = await AMapLoader.load({ key: keyConfig.key, // 申请好的Web端开发者Key,首次调用 load 时必填(plc-key) version: '2.0', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15 plugins: [ 'AMap.DistrictSearch', 'AMap.Geocoder', 'AMap.AutoComplete ', //2.0版本是AMap.AutoComplete, 2.0以下是AMap.Autocomplete // 输入提示插件 'AMap.PlaceSearch', // POI搜索插件 'AMap.Scale', // 右下角缩略图插件 比例尺 'AMap.OverView', // 地图鹰眼插件 'AMap.ToolBar', // 地图工具条 'AMap.MapType', // 类别切换控件,实现默认图层与卫星图、实施交通图层之间切换的控制 'AMap.PolyEditor', // 编辑 折线多,边形 'AMap.CircleEditor', // 圆形编辑器插件 'AMap.Geolocation', // 定位控件,用来获取和展示用户主机所在的经纬度位置], // 需要使用的的插件列表,如比例尺'AMap.Scale'等 ], }); const { geocode } = option || {}; // map初始化完成 const res = await Geolocation(AMap, geocode, { enableHighAccuracy: true, //是否使用高精度定位,默认:true timeout: 10000, //超过10秒后停止定位,默认:5s GeoLocationFirst: true, //默认为false,设置为true的时候可以调整PC端为优先使用浏览器定位,失败后使用IP定位 }); // 返回结果保持跟uni.getLocation 一致 const [longitude, latitude] = res.position; const address = res.address || {}; const { province, city, district, street, streetNumber, cityCode } = address.addressComponent; const newData = { longitude, latitude, address: { // 文档参数说明https://uniapp.dcloud.net.cn/api/location/location.html country: '', province, city, district, street, streetNum: streetNumber, poiName: '', postalCode: '', cityCode, }, formattedAddress: address.formattedAddress, }; return newData; } /** * 获取定位,并返回定位信息 * @param {Object} options uni.getLocation的配置项, h5只支持 geocode 是否解析地址信息 * @returns {Promise} 返回promise **/ export const getLocation = async (option = defaultOpt) => { const uniPlatform = uni.$u.sys().uniPlatform; if (uniPlatform === 'app') { const res = await getAppLocation(option); return res; } const webRes = await getWebLocation(option); return webRes; };