Files
czzj-app/src/utils/amap.ts
2026-10-28 10:36:39 +08:00

343 lines
9.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { getAmapWebKey } from '@/config/app-env'
export interface MapLocationPoint {
name?: string
address: string
latitude: number
longitude: number
}
export interface AmapSearchResult {
places: MapLocationPoint[]
error?: string
}
interface AmapBaseResponse {
status?: string | number
info?: string
infocode?: string
}
interface AmapRegeoResponse extends AmapBaseResponse {
regeocode?: {
formatted_address?: string
addressComponent?: {
province?: string
city?: string | string[]
district?: string
}
}
}
function getAmapApiBaseUrl(): string {
// #ifdef H5
if (import.meta.env.DEV) return '/amap-api'
// #endif
return 'https://restapi.amap.com'
}
interface AmapInputTip {
id?: string
name?: string
district?: string
address?: string
location?: string
}
interface AmapInputTipsResponse extends AmapBaseResponse {
tips?: AmapInputTip[]
}
interface AmapPoi {
name?: string
address?: string
pname?: string
cityname?: string
adname?: string
location?: string
distance?: string
}
interface AmapPlaceSearchResponse extends AmapBaseResponse {
pois?: AmapPoi[]
}
function isAmapOk(status?: string | number): boolean {
return String(status) === '1'
}
/** 高德部分字段在 JSON 里会是 [] 而非字符串,需统一转成文本再解析 */
function amapFieldText(value: unknown): string {
if (value == null) return ''
if (Array.isArray(value)) return ''
const text = String(value).trim()
return text === '[]' ? '' : text
}
function parseAmapLocation(location?: unknown): { longitude: number; latitude: number } | null {
const text = amapFieldText(location)
if (!text) return null
const [lngText, latText] = text.split(',')
const longitude = Number(lngText)
const latitude = Number(latText)
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return null
return { longitude, latitude }
}
function parseAmapBody<T>(raw: unknown): T | null {
if (raw == null) return null
if (typeof raw === 'string') {
try {
return JSON.parse(raw) as T
} catch {
return null
}
}
return raw as T
}
function resolveCityName(component?: AmapRegeoResponse['regeocode']): string {
const city = component?.addressComponent?.city
if (Array.isArray(city)) {
const first = city.find((item) => item?.trim())
if (first) return first.trim()
} else if (typeof city === 'string' && city.trim()) {
return city.trim()
}
const province = component?.addressComponent?.province?.trim()
const district = component?.addressComponent?.district?.trim()
return province || district || ''
}
function dedupePlaces(list: MapLocationPoint[]): MapLocationPoint[] {
const seen = new Set<string>()
const result: MapLocationPoint[] = []
for (const item of list) {
const key = `${item.longitude.toFixed(6)},${item.latitude.toFixed(6)}`
if (seen.has(key)) continue
seen.add(key)
result.push(item)
}
return result
}
function mapPois(pois: AmapPoi[] | undefined): MapLocationPoint[] {
if (!Array.isArray(pois)) return []
const results: MapLocationPoint[] = []
for (const poi of pois) {
const name = amapFieldText(poi.name)
if (!name) continue
const coords = parseAmapLocation(poi.location)
if (!coords) continue
const region = [poi.pname, poi.cityname, poi.adname]
.map((part) => amapFieldText(part))
.filter(Boolean)
.join('')
const address = amapFieldText(poi.address) || region || name
results.push({
name,
address,
latitude: coords.latitude,
longitude: coords.longitude,
})
}
return results
}
function mapInputTips(body: AmapInputTipsResponse | null): MapLocationPoint[] {
if (!body || !isAmapOk(body.status) || !Array.isArray(body.tips)) return []
const results: MapLocationPoint[] = []
for (const tip of body.tips) {
const name = amapFieldText(tip.name)
if (!name) continue
const coords = parseAmapLocation(tip.location)
if (!coords) continue
const address = amapFieldText(tip.address) || amapFieldText(tip.district) || name
results.push({
name,
address,
latitude: coords.latitude,
longitude: coords.longitude,
})
}
return results
}
function mapAmapError(body: AmapBaseResponse | null, fallback = '地点搜索失败'): string {
if (!body) return fallback
const info = body.info?.trim()
if (!info || info === 'OK') return fallback
if (/USERKEY_PLAT_NWM/i.test(info)) {
return '地图 Key 平台不匹配,请在高德控制台开启 Web 服务'
}
if (/INVALID_USER_KEY|USERKEY_PLAT/i.test(info)) {
return '地图服务 Key 无效,请检查配置'
}
return info
}
export function formatMapLocation(point: { name?: string; address?: string }): string {
const name = point.name?.trim()
const address = point.address?.trim()
if (name && address && name !== address) return `${name} · ${address}`
return name || address || ''
}
export function toMapCoords(point: Pick<MapLocationPoint, 'latitude' | 'longitude'>) {
return {
latitude: point.latitude,
longitude: point.longitude,
}
}
async function requestAmap<T extends AmapBaseResponse>(
url: string,
data: Record<string, string>,
): Promise<T | null> {
const key = getAmapWebKey()
if (!key) return null
try {
const res = await uni.request({
url: `${getAmapApiBaseUrl()}${url}`,
method: 'GET',
data: { ...data, key },
timeout: 15000,
})
const statusCode = res.statusCode ?? 200
if (statusCode < 200 || statusCode >= 300) return null
return parseAmapBody<T>(res.data)
} catch {
return null
}
}
/** 高德逆地理编码(需配置 VITE_AMAP_WEB_KEY) */
export async function reverseGeocodeAmap(
latitude: number,
longitude: number,
): Promise<string | undefined> {
const detail = await reverseGeocodeAmapDetail(latitude, longitude)
return detail?.address
}
/** 逆地理编码,附带城市信息(供搜索限定范围) */
export async function reverseGeocodeAmapDetail(
latitude: number,
longitude: number,
): Promise<{ address: string; city: string } | undefined> {
const data = await requestAmap<AmapRegeoResponse>('/v3/geocode/regeo', {
location: `${longitude},${latitude}`,
extensions: 'base',
})
if (!data || !isAmapOk(data.status)) return undefined
const address = data.regeocode?.formatted_address?.trim()
const city = resolveCityName(data.regeocode)
if (!address && !city) return undefined
return {
address: address || '',
city,
}
}
/** 高德地点搜索(周边 + 输入提示 + 文本搜索) */
export async function searchAmapPlaces(
keyword: string,
options?: { latitude?: number; longitude?: number; city?: string },
): Promise<AmapSearchResult> {
const trimmed = keyword.trim()
if (!trimmed) return { places: [] }
if (!getAmapWebKey()) {
return { places: [], error: '地图搜索服务未配置' }
}
const hasCoords = options?.latitude != null && options?.longitude != null
const location = hasCoords
? `${options!.longitude},${options!.latitude}`
: undefined
let city = options?.city?.trim() || ''
if (!city && hasCoords) {
const detail = await reverseGeocodeAmapDetail(options!.latitude!, options!.longitude!)
city = detail?.city || ''
}
const tipsData: Record<string, string> = {
keywords: trimmed,
datatype: 'all',
}
if (city) tipsData.city = city
if (location) tipsData.location = location
const textData: Record<string, string> = {
keywords: trimmed,
offset: '20',
page: '1',
extensions: 'base',
}
if (city) {
textData.city = city
// 仅作范围偏好,避免严格 citylimit 导致模糊词搜不到
textData.citylimit = 'false'
}
const [aroundBody, tipsBody, textBody] = await Promise.all([
location
? requestAmap<AmapPlaceSearchResponse>('/v3/place/around', {
keywords: trimmed,
location,
radius: '50000',
offset: '20',
page: '1',
extensions: 'base',
sortrule: 'distance',
})
: Promise.resolve(null),
requestAmap<AmapInputTipsResponse>('/v3/assistant/inputtips', tipsData),
requestAmap<AmapPlaceSearchResponse>('/v3/place/text', textData),
])
const places = dedupePlaces([
...mapPois(aroundBody?.pois),
...mapInputTips(tipsBody),
...mapPois(textBody?.pois),
])
if (places.length) {
return { places }
}
if (city) {
const [fallbackTips, fallbackText] = await Promise.all([
requestAmap<AmapInputTipsResponse>('/v3/assistant/inputtips', {
keywords: trimmed,
datatype: 'all',
...(location ? { location } : {}),
}),
requestAmap<AmapPlaceSearchResponse>('/v3/place/text', {
keywords: trimmed,
offset: '20',
page: '1',
extensions: 'base',
}),
])
const fallbackPlaces = dedupePlaces([
...mapInputTips(fallbackTips),
...mapPois(fallbackText?.pois),
])
if (fallbackPlaces.length) {
return { places: fallbackPlaces }
}
}
const failed = [aroundBody, tipsBody, textBody].find((item) => item && !isAmapOk(item.status))
if (failed) {
return { places: [], error: mapAmapError(failed) }
}
return { places: [] }
}
export function hasAmapWebKey(): boolean {
return !!getAmapWebKey()
}