/** * 多端实时定位、微信小程序原生授权与定位缓存工具 * - 微信小程序端:直接触发官方原生授权(wx.getLocation / wx.authorize)及设置页(wx.openSetting),不阻塞、不伪造假权限弹窗 * - H5 端:调用浏览器 Geolocation API,失败或被拒时安全回传状态供上层拉起天地图地点选择面板 * - 严禁返回假经纬度或 mock 数据 */ import { tiandituWebKey } from '@/config/config.js'; const MANUAL_LOC_KEY = 'yjyf_master_manual_loc_v1'; const RECENT_LOCS_KEY = 'yjyf_master_recent_locs_v1'; const MANUAL_LOC_TTL_MS = 24 * 60 * 60 * 1000; const MAX_RECENT_LOCS = 6; let tiandituScriptPromise = null; /** * 读取用户近期主动确认/选择过的接单定位 * @returns {{ lat: number, lng: number, label: string, city: string, district?: string, serveRadius?: number, updatedAt: number } | null} */ export function getSavedManualLocation() { try { const raw = uni.getStorageSync(MANUAL_LOC_KEY); if (!raw || typeof raw !== 'object') return null; const lat = Number(raw.lat); const lng = Number(raw.lng); const updatedAt = Number(raw.updatedAt) || 0; if (!Number.isFinite(lat) || !Number.isFinite(lng) || (Math.abs(lat) < 0.0001 && Math.abs(lng) < 0.0001)) { return null; } if (!raw.manual && updatedAt > 0 && Date.now() - updatedAt > MANUAL_LOC_TTL_MS) { return null; } return { lat, lng, label: String(raw.label || ''), city: String(raw.city || ''), district: String(raw.district || ''), serveRadius: Number(raw.serveRadius) || 0, manual: Boolean(raw.manual), updatedAt }; } catch (e) { return null; } } /** * 保存用户主动定位或选定的真实经纬度坐标 */ export function saveManualLocation({ lat, lng, label = '', city = '', district = '', serveRadius = 0, manual = false }) { const latNum = Number(lat); const lngNum = Number(lng); if (!Number.isFinite(latNum) || !Number.isFinite(lngNum)) return; try { uni.setStorageSync(MANUAL_LOC_KEY, { lat: Number(latNum.toFixed(6)), lng: Number(lngNum.toFixed(6)), label: String(label || ''), city: String(city || ''), district: String(district || ''), serveRadius: Number(serveRadius) || 0, manual: Boolean(manual), updatedAt: Date.now() }); } catch (e) {} } /** * 清除缓存的定位信息 */ export function clearSavedManualLocation() { try { uni.removeStorageSync(MANUAL_LOC_KEY); } catch (e) {} } /** * 读取最近真实使用/确认过的接单位置记录 */ export function getRecentLocations() { try { const raw = uni.getStorageSync(RECENT_LOCS_KEY); if (!Array.isArray(raw)) return []; return raw.filter((item) => { if (!item || typeof item !== 'object') return false; const lat = Number(item.lat); const lng = Number(item.lng); return Number.isFinite(lat) && Number.isFinite(lng) && (Math.abs(lat) > 0.0001 || Math.abs(lng) > 0.0001); }); } catch (e) { return []; } } /** * 写入一条最近真实选定的位置记录(自动去重与限制数量) */ export function saveRecentLocation({ lat, lng, name = '', address = '', city = '', district = '' }) { const latNum = Number(lat); const lngNum = Number(lng); if (!Number.isFinite(latNum) || !Number.isFinite(lngNum)) return []; const normLat = Number(latNum.toFixed(6)); const normLng = Number(lngNum.toFixed(6)); const key = `${normLat.toFixed(4)}_${normLng.toFixed(4)}`; const list = getRecentLocations().filter((it) => it.key !== key && it.name !== name); const next = [ { key, lat: normLat, lng: normLng, name: String(name || city || '已选位置'), address: String(address || ''), city: String(city || ''), district: String(district || ''), updatedAt: Date.now() }, ...list ].slice(0, MAX_RECENT_LOCS); try { uni.setStorageSync(RECENT_LOCS_KEY, next); } catch (e) {} return next; } /** * 移除指定最近位置记录 */ export function removeRecentLocation(key) { const next = getRecentLocations().filter((it) => it.key !== key); try { uni.setStorageSync(RECENT_LOCS_KEY, next); } catch (e) {} return next; } /** * 清空最近使用位置记录 */ export function clearRecentLocations() { try { uni.removeStorageSync(RECENT_LOCS_KEY); } catch (e) {} return []; } /** * H5 端动态加载天地图 JavaScript API v4.0 * @returns {Promise} */ export function loadTiandituScript() { // #ifdef H5 if (typeof window === 'undefined' || typeof document === 'undefined') { return Promise.reject(new Error('非浏览器环境')); } if (window.T && typeof window.T.Map === 'function') { return Promise.resolve(window.T); } if (tiandituScriptPromise) { return tiandituScriptPromise; } tiandituScriptPromise = new Promise((resolve, reject) => { const timer = setTimeout(() => { tiandituScriptPromise = null; reject(new Error('天地图脚本加载超时')); }, 6500); if (!document.getElementById('yjyf-tianditu-css')) { const link = document.createElement('link'); link.id = 'yjyf-tianditu-css'; link.rel = 'stylesheet'; link.href = 'https://api.tianditu.gov.cn/v4.0/css/tianditu4.0.css'; document.head.appendChild(link); } const existing = document.getElementById('yjyf-tianditu-sdk'); if (existing) { existing.remove(); } const script = document.createElement('script'); script.id = 'yjyf-tianditu-sdk'; script.type = 'text/javascript'; script.async = true; script.src = `https://api.tianditu.gov.cn/api?v=4.0&tk=${encodeURIComponent(tiandituWebKey)}`; script.onload = () => { clearTimeout(timer); if (window.T && typeof window.T.Map === 'function') { resolve(window.T); } else { tiandituScriptPromise = null; reject(new Error('天地图对象初始化失败')); } }; script.onerror = () => { clearTimeout(timer); tiandituScriptPromise = null; reject(new Error('天地图脚本加载失败')); }; document.head.appendChild(script); }); return tiandituScriptPromise; // #endif // #ifndef H5 return Promise.reject(new Error('仅 H5 端加载天地图 Web SDK')); // #endif } /** * 检测当前设备位置权限状态 * @returns {Promise<'granted'|'denied'|'prompt'|'unavailable'>} */ export function checkLocationPermissionStatus() { return new Promise((resolve) => { // #ifdef MP-WEIXIN uni.getSetting({ success: (res) => { const setting = res && res.authSetting ? res.authSetting : {}; if (setting['scope.userLocation'] === true) { resolve('granted'); } else if (setting['scope.userLocation'] === false) { resolve('denied'); } else { resolve('prompt'); } }, fail: () => resolve('prompt') }); return; // #endif // #ifdef H5 if (typeof navigator === 'undefined' || !navigator.geolocation) { resolve('unavailable'); return; } if (typeof window !== 'undefined' && window.isSecureContext === false) { resolve('unavailable'); return; } if (navigator.permissions && typeof navigator.permissions.query === 'function') { navigator.permissions.query({ name: 'geolocation' }) .then((status) => { const state = status && status.state ? status.state : 'prompt'; if (state === 'granted' || state === 'denied' || state === 'prompt') { resolve(state); } else { resolve('prompt'); } }) .catch(() => resolve('prompt')); } else { resolve('prompt'); } return; // #endif // #ifndef MP-WEIXIN || H5 resolve('prompt'); // #endif }); } /** * 真实获取当前设备经纬度坐标 * 注意:在微信小程序 `prompt` 状态下调用会直接弹出微信官方底部定位授权弹窗 * @param {{ timeout?: number, enableHighAccuracy?: boolean }} options * @returns {Promise<{ ok: boolean, lat?: number, lng?: number, reason?: string, message?: string }>} */ export function getCurrentCoordinates(options = {}) { const timeout = Number(options.timeout) > 0 ? Number(options.timeout) : 5000; const enableHighAccuracy = Boolean(options.enableHighAccuracy); return new Promise((resolve) => { // #ifdef H5 if (typeof navigator === 'undefined' || !navigator.geolocation) { resolve({ ok: false, reason: 'unavailable', message: '当前浏览器不支持自动定位,请在下方搜索选择位置' }); return; } if (typeof window !== 'undefined' && window.isSecureContext === false) { resolve({ ok: false, reason: 'unavailable', message: '非 HTTPS 环境限制自动定位,请在下方搜索选择位置' }); return; } let settled = false; const guardTimer = setTimeout(() => { if (!settled) { settled = true; resolve({ ok: false, reason: 'timeout', message: '获取当前位置超时,可搜索选择所在地区' }); } }, timeout + 400); navigator.geolocation.getCurrentPosition( (pos) => { if (settled) return; settled = true; clearTimeout(guardTimer); const coords = pos && pos.coords ? pos.coords : null; if (coords && Number.isFinite(coords.latitude) && Number.isFinite(coords.longitude)) { resolve({ ok: true, lat: Number(coords.latitude.toFixed(6)), lng: Number(coords.longitude.toFixed(6)) }); } else { resolve({ ok: false, reason: 'error', message: '未获取到有效坐标,请手动选择位置' }); } }, (err) => { if (settled) return; settled = true; clearTimeout(guardTimer); const code = err && typeof err.code === 'number' ? err.code : 0; if (code === 1) { resolve({ ok: false, reason: 'denied', message: '位置权限未开启,请允许浏览器访问位置或搜索选择位置' }); } else if (code === 3) { resolve({ ok: false, reason: 'timeout', message: '获取当前位置超时,可搜索选择所在地区' }); } else { resolve({ ok: false, reason: 'unavailable', message: '当前设备定位服务不可用,请直接搜索选择所在位置' }); } }, { enableHighAccuracy, timeout, maximumAge: 60000 } ); return; // #endif // #ifndef H5 uni.getLocation({ type: 'gcj02', success: (res) => { if (res && Number.isFinite(Number(res.latitude)) && Number.isFinite(Number(res.longitude))) { resolve({ ok: true, lat: Number(Number(res.latitude).toFixed(6)), lng: Number(Number(res.longitude).toFixed(6)) }); } else { resolve({ ok: false, reason: 'error', message: '定位坐标无效' }); } }, fail: (err) => { const msg = String((err && (err.errMsg || err.message)) || '').toLowerCase(); if (msg.includes('auth') || msg.includes('deny') || msg.includes('denied') || msg.includes('permission')) { resolve({ ok: false, reason: 'denied', message: '您尚未开启位置权限' }); } else { resolve({ ok: false, reason: 'error', message: '定位失败,请检查手机定位开关或手动选择位置' }); } } }); // #endif }); } /** * 直接在点击手势中打开微信小程序设置页(必须同步由点击回调触发) * @returns {Promise<{ ok: boolean, lat?: number, lng?: number, reason?: string, message?: string }>} */ export function openMiniProgramLocationSettingSync() { return new Promise((resolve) => { // #ifdef MP-WEIXIN uni.openSetting({ success: async (res) => { const auth = res && res.authSetting ? res.authSetting : {}; if (auth['scope.userLocation'] === true) { const loc = await getCurrentCoordinates(); resolve(loc); } else { resolve({ ok: false, reason: 'denied', message: '位置权限仍处于关闭状态' }); } }, fail: () => { // 若环境限制无法直接打开 openSetting,使用原生模态框二次确认(确认回调属于有效用户点击手势) uni.showModal({ title: '开启位置权限', content: '请在小程序设置中允许使用“位置信息”,以便为您推荐附近工单', confirmText: '去设置', confirmColor: '#F0710D', success: (mRes) => { if (!mRes.confirm) { resolve({ ok: false, reason: 'denied', message: '已取消' }); return; } uni.openSetting({ success: async (sRes) => { const auth = sRes && sRes.authSetting ? sRes.authSetting : {}; if (auth['scope.userLocation'] === true) { const loc = await getCurrentCoordinates(); resolve(loc); } else { resolve({ ok: false, reason: 'denied', message: '位置权限尚未开启' }); } }, fail: () => resolve({ ok: false, reason: 'error', message: '无法打开授权设置,可手动选择区域' }) }); } }); } }); return; // #endif // #ifndef MP-WEIXIN resolve({ ok: false, reason: 'unsupported', message: '非小程序环境' }); // #endif }); }