fix(admin,partner): replace Tencent iframe picker with server LBS search
CI / verify (pull_request) Has been cancelled
CI / verify (pull_request) Has been cancelled
Avoid locpicker formatted_addresses crash; proxy suggest/nearby/reverse via /common/lbs. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,10 +1,9 @@
|
|||||||
import { useEffect, useMemo, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { Button, Modal, Space, Spin, Typography, message } from 'antd';
|
import { Button, Empty, Input, List, Modal, Space, Spin, Typography, message } from 'antd';
|
||||||
import type { ClientRuntimeConfig } from '@dukang/shared-types';
|
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
import {
|
import {
|
||||||
buildTencentLocPickerUrl,
|
placeToPicked,
|
||||||
parseTencentLocPickerMessage,
|
type LbsPlaceItem,
|
||||||
type TencentPickedLocation,
|
type TencentPickedLocation,
|
||||||
} from '../lib/tencentLocPicker';
|
} from '../lib/tencentLocPicker';
|
||||||
|
|
||||||
@@ -14,19 +13,14 @@ type Props = {
|
|||||||
onPick: (loc: TencentPickedLocation) => void;
|
onPick: (loc: TencentPickedLocation) => void;
|
||||||
latitude?: number | null;
|
latitude?: number | null;
|
||||||
longitude?: number | null;
|
longitude?: number | null;
|
||||||
|
/** 城市名,提升搜索相关性 */
|
||||||
|
region?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
let cachedKey: string | null | undefined;
|
function hasCoords(lat: unknown, lng: unknown): lat is number {
|
||||||
|
const a = typeof lat === 'number' ? lat : Number(lat);
|
||||||
async function loadTencentLbsKey(): Promise<string> {
|
const b = typeof lng === 'number' ? lng : Number(lng);
|
||||||
if (cachedKey) return cachedKey;
|
return Number.isFinite(a) && Number.isFinite(b) && !(a === 0 && b === 0);
|
||||||
const cfg = await request<ClientRuntimeConfig>('/common/client-config');
|
|
||||||
const key = (cfg.tencentLbsKey || '').trim();
|
|
||||||
if (!key) {
|
|
||||||
throw new Error('未配置腾讯位置服务 Key,请在系统设置中填写 TENCENT_LBS_KEY');
|
|
||||||
}
|
|
||||||
cachedKey = key;
|
|
||||||
return key;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function TencentLocPickerModal({
|
export default function TencentLocPickerModal({
|
||||||
@@ -35,64 +29,110 @@ export default function TencentLocPickerModal({
|
|||||||
onPick,
|
onPick,
|
||||||
latitude,
|
latitude,
|
||||||
longitude,
|
longitude,
|
||||||
|
region,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const [key, setKey] = useState<string | null>(cachedKey ?? null);
|
const [keyword, setKeyword] = useState('');
|
||||||
|
const [items, setItems] = useState<LbsPlaceItem[]>([]);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [pending, setPending] = useState<TencentPickedLocation | null>(null);
|
const [pending, setPending] = useState<TencentPickedLocation | null>(null);
|
||||||
|
const [hint, setHint] = useState('输入地点名称搜索,或加载附近地点');
|
||||||
|
const seqRef = useRef(0);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) {
|
if (!open) {
|
||||||
|
setKeyword('');
|
||||||
|
setItems([]);
|
||||||
setPending(null);
|
setPending(null);
|
||||||
|
setHint('输入地点名称搜索,或加载附近地点');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let cancelled = false;
|
const lat = latitude != null ? Number(latitude) : NaN;
|
||||||
setError('');
|
const lng = longitude != null ? Number(longitude) : NaN;
|
||||||
if (key) return;
|
if (hasCoords(lat, lng)) {
|
||||||
setLoading(true);
|
void loadNearby(lat, lng);
|
||||||
void loadTencentLbsKey()
|
|
||||||
.then((k) => {
|
|
||||||
if (!cancelled) setKey(k);
|
|
||||||
})
|
|
||||||
.catch((e) => {
|
|
||||||
if (!cancelled) {
|
|
||||||
const msg = e instanceof Error ? e.message : '加载地图配置失败';
|
|
||||||
setError(msg);
|
|
||||||
message.error(msg);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
if (!cancelled) setLoading(false);
|
|
||||||
});
|
|
||||||
return () => {
|
|
||||||
cancelled = true;
|
|
||||||
};
|
|
||||||
}, [open, key]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!open) return;
|
|
||||||
function onMessage(event: MessageEvent) {
|
|
||||||
const picked = parseTencentLocPickerMessage(event.data);
|
|
||||||
if (!picked) return;
|
|
||||||
setPending(picked);
|
|
||||||
}
|
}
|
||||||
window.addEventListener('message', onMessage);
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
return () => window.removeEventListener('message', onMessage);
|
|
||||||
}, [open]);
|
}, [open]);
|
||||||
|
|
||||||
const src = useMemo(() => {
|
async function loadNearby(lat: number, lng: number) {
|
||||||
if (!key) return '';
|
const seq = ++seqRef.current;
|
||||||
const lat = latitude != null ? Number(latitude) : undefined;
|
setLoading(true);
|
||||||
const lng = longitude != null ? Number(longitude) : undefined;
|
setHint('正在加载附近地点…');
|
||||||
return buildTencentLocPickerUrl(key, {
|
try {
|
||||||
latitude: lat != null && Number.isFinite(lat) ? lat : undefined,
|
const res = await request<{ items: LbsPlaceItem[] }>(
|
||||||
longitude: lng != null && Number.isFinite(lng) ? lng : undefined,
|
`/common/lbs/nearby?lat=${encodeURIComponent(String(lat))}&lng=${encodeURIComponent(String(lng))}`,
|
||||||
});
|
);
|
||||||
}, [key, latitude, longitude]);
|
if (seq !== seqRef.current) return;
|
||||||
|
setItems(res.items ?? []);
|
||||||
|
setHint(res.items?.length ? `附近 ${res.items.length} 个地点,点击选择` : '附近暂无地点,请搜索');
|
||||||
|
} catch (e) {
|
||||||
|
if (seq !== seqRef.current) return;
|
||||||
|
const msg = e instanceof Error ? e.message : '加载附近地点失败';
|
||||||
|
setItems([]);
|
||||||
|
setHint(msg);
|
||||||
|
message.error(msg);
|
||||||
|
} finally {
|
||||||
|
if (seq === seqRef.current) setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runSearch(q: string) {
|
||||||
|
const trimmed = q.trim();
|
||||||
|
if (!trimmed) {
|
||||||
|
message.warning('请输入搜索关键词');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const seq = ++seqRef.current;
|
||||||
|
setLoading(true);
|
||||||
|
setHint('搜索中…');
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams({ keyword: trimmed });
|
||||||
|
if (region?.trim()) params.set('region', region.trim());
|
||||||
|
const lat = latitude != null ? Number(latitude) : NaN;
|
||||||
|
const lng = longitude != null ? Number(longitude) : NaN;
|
||||||
|
if (Number.isFinite(lat) && Number.isFinite(lng)) {
|
||||||
|
params.set('lat', String(lat));
|
||||||
|
params.set('lng', String(lng));
|
||||||
|
}
|
||||||
|
const res = await request<{ items: LbsPlaceItem[] }>(`/common/lbs/suggest?${params.toString()}`);
|
||||||
|
if (seq !== seqRef.current) return;
|
||||||
|
setItems(res.items ?? []);
|
||||||
|
setHint(res.items?.length ? `找到 ${res.items.length} 个结果,点击选择` : '无匹配结果,换个关键词试试');
|
||||||
|
} catch (e) {
|
||||||
|
if (seq !== seqRef.current) return;
|
||||||
|
const msg = e instanceof Error ? e.message : '搜索失败';
|
||||||
|
setItems([]);
|
||||||
|
setHint(msg);
|
||||||
|
message.error(msg);
|
||||||
|
} finally {
|
||||||
|
if (seq === seqRef.current) setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function useBrowserLocation() {
|
||||||
|
if (!navigator.geolocation) {
|
||||||
|
message.error('当前浏览器不支持定位');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoading(true);
|
||||||
|
navigator.geolocation.getCurrentPosition(
|
||||||
|
(pos) => {
|
||||||
|
const lat = pos.coords.latitude;
|
||||||
|
const lng = pos.coords.longitude;
|
||||||
|
setPending({ latitude: lat, longitude: lng, name: '当前位置' });
|
||||||
|
void loadNearby(lat, lng);
|
||||||
|
},
|
||||||
|
() => {
|
||||||
|
setLoading(false);
|
||||||
|
message.error('定位失败,请检查浏览器定位权限');
|
||||||
|
},
|
||||||
|
{ enableHighAccuracy: true, timeout: 12000 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function confirmPick() {
|
function confirmPick() {
|
||||||
if (!pending) {
|
if (!pending) {
|
||||||
message.warning('请先在地图上选择或搜索一个位置');
|
message.warning('请先从列表中选择一个地点');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
onPick(pending);
|
onPick(pending);
|
||||||
@@ -101,12 +141,11 @@ export default function TencentLocPickerModal({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title="腾讯地图选点"
|
title="地图选点(腾讯位置服务)"
|
||||||
open={open}
|
open={open}
|
||||||
onCancel={onClose}
|
onCancel={onClose}
|
||||||
width={720}
|
width={720}
|
||||||
destroyOnClose
|
destroyOnClose
|
||||||
styles={{ body: { padding: 0, height: 560 } }}
|
|
||||||
footer={
|
footer={
|
||||||
<Space style={{ width: '100%', justifyContent: 'space-between' }}>
|
<Space style={{ width: '100%', justifyContent: 'space-between' }}>
|
||||||
<Typography.Text type="secondary" style={{ maxWidth: 420 }} ellipsis>
|
<Typography.Text type="secondary" style={{ maxWidth: 420 }} ellipsis>
|
||||||
@@ -114,7 +153,7 @@ export default function TencentLocPickerModal({
|
|||||||
? `${pending.latitude.toFixed(6)}, ${pending.longitude.toFixed(6)}${
|
? `${pending.latitude.toFixed(6)}, ${pending.longitude.toFixed(6)}${
|
||||||
pending.name ? ` · ${pending.name}` : ''
|
pending.name ? ` · ${pending.name}` : ''
|
||||||
}`
|
}`
|
||||||
: '在地图中点选 / 搜索后,点击确认选点'}
|
: '搜索或选择附近地点后确认'}
|
||||||
</Typography.Text>
|
</Typography.Text>
|
||||||
<Space>
|
<Space>
|
||||||
<Button onClick={onClose}>取消</Button>
|
<Button onClick={onClose}>取消</Button>
|
||||||
@@ -125,26 +164,67 @@ export default function TencentLocPickerModal({
|
|||||||
</Space>
|
</Space>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
{loading ? (
|
<Space direction="vertical" style={{ width: '100%' }} size="middle">
|
||||||
<div style={{ height: 560, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
<Space.Compact style={{ width: '100%' }}>
|
||||||
<Spin tip="加载地图…" />
|
<Input
|
||||||
|
allowClear
|
||||||
|
placeholder="输入小区 / 写字楼 / 门店名称"
|
||||||
|
value={keyword}
|
||||||
|
onChange={(e) => setKeyword(e.target.value)}
|
||||||
|
onPressEnter={() => void runSearch(keyword)}
|
||||||
|
/>
|
||||||
|
<Button type="primary" loading={loading} onClick={() => void runSearch(keyword)}>
|
||||||
|
搜索
|
||||||
|
</Button>
|
||||||
|
</Space.Compact>
|
||||||
|
<Space wrap>
|
||||||
|
<Button onClick={useBrowserLocation} disabled={loading}>
|
||||||
|
定位当前位置
|
||||||
|
</Button>
|
||||||
|
<Typography.Text type="secondary">{hint}</Typography.Text>
|
||||||
|
</Space>
|
||||||
|
<div style={{ height: 420, overflow: 'auto', border: '1px solid #f0f0f0', borderRadius: 8 }}>
|
||||||
|
{loading && !items.length ? (
|
||||||
|
<div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
||||||
|
<Spin tip="加载中…" />
|
||||||
|
</div>
|
||||||
|
) : items.length ? (
|
||||||
|
<List
|
||||||
|
size="small"
|
||||||
|
dataSource={items}
|
||||||
|
renderItem={(item) => {
|
||||||
|
const active =
|
||||||
|
pending?.latitude === item.latitude && pending?.longitude === item.longitude;
|
||||||
|
return (
|
||||||
|
<List.Item
|
||||||
|
style={{
|
||||||
|
cursor: 'pointer',
|
||||||
|
background: active ? 'rgba(22, 119, 255, 0.08)' : undefined,
|
||||||
|
paddingInline: 12,
|
||||||
|
}}
|
||||||
|
onClick={() => setPending(placeToPicked(item))}
|
||||||
|
>
|
||||||
|
<List.Item.Meta
|
||||||
|
title={item.title}
|
||||||
|
description={
|
||||||
|
<span>
|
||||||
|
{item.address}
|
||||||
|
<br />
|
||||||
|
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||||
|
{item.latitude.toFixed(6)}, {item.longitude.toFixed(6)}
|
||||||
|
</Typography.Text>
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</List.Item>
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Empty style={{ marginTop: 80 }} description={hint} />
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : error ? (
|
</Space>
|
||||||
<div style={{ padding: 24 }}>
|
|
||||||
<Typography.Text type="danger">{error}</Typography.Text>
|
|
||||||
<Typography.Paragraph type="secondary" style={{ marginTop: 12, marginBottom: 0 }}>
|
|
||||||
若地图能开但看不到附近地点列表,请在腾讯位置服务控制台为该 Key 开启
|
|
||||||
WebServiceAPI,并将白名单域名加入 apis.map.qq.com。
|
|
||||||
</Typography.Paragraph>
|
|
||||||
</div>
|
|
||||||
) : src ? (
|
|
||||||
<iframe
|
|
||||||
title="腾讯地图选点"
|
|
||||||
src={src}
|
|
||||||
allow="geolocation *"
|
|
||||||
style={{ width: '100%', height: 560, border: 0, display: 'block' }}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,75 +6,21 @@ export type TencentPickedLocation = {
|
|||||||
cityname?: string;
|
cityname?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type LocPickerMessage = {
|
export type LbsPlaceItem = {
|
||||||
module?: string;
|
id: string;
|
||||||
latlng?: { lat?: number; lng?: number };
|
title: string;
|
||||||
poiaddress?: string;
|
address: string;
|
||||||
poiname?: string;
|
latitude: number;
|
||||||
cityname?: string;
|
longitude: number;
|
||||||
|
city?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const REFERER = 'dukang';
|
export function placeToPicked(item: LbsPlaceItem): TencentPickedLocation {
|
||||||
|
|
||||||
function coerceMessageData(data: unknown): LocPickerMessage | null {
|
|
||||||
if (data == null) return null;
|
|
||||||
if (typeof data === 'string') {
|
|
||||||
const trimmed = data.trim();
|
|
||||||
if (!trimmed || (trimmed[0] !== '{' && trimmed[0] !== '[')) return null;
|
|
||||||
try {
|
|
||||||
return JSON.parse(trimmed) as LocPickerMessage;
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (typeof data === 'object') return data as LocPickerMessage;
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildTencentLocPickerUrl(
|
|
||||||
key: string,
|
|
||||||
options?: { latitude?: number; longitude?: number },
|
|
||||||
): string {
|
|
||||||
const params = new URLSearchParams({
|
|
||||||
search: '1',
|
|
||||||
type: '1',
|
|
||||||
key,
|
|
||||||
referer: REFERER,
|
|
||||||
policy: '1',
|
|
||||||
total: '20',
|
|
||||||
radius: '2000',
|
|
||||||
});
|
|
||||||
const lat = options?.latitude;
|
|
||||||
const lng = options?.longitude;
|
|
||||||
if (
|
|
||||||
lat != null &&
|
|
||||||
lng != null &&
|
|
||||||
Number.isFinite(lat) &&
|
|
||||||
Number.isFinite(lng) &&
|
|
||||||
!(lat === 0 && lng === 0)
|
|
||||||
) {
|
|
||||||
params.set('coord', `${lat},${lng}`);
|
|
||||||
params.set('coordtype', '5');
|
|
||||||
}
|
|
||||||
return `https://apis.map.qq.com/tools/locpicker?${params.toString()}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function parseTencentLocPickerMessage(data: unknown): TencentPickedLocation | null {
|
|
||||||
const loc = coerceMessageData(data);
|
|
||||||
if (!loc || loc.module !== 'locationPicker') return null;
|
|
||||||
const lat = Number(loc.latlng?.lat);
|
|
||||||
const lng = Number(loc.latlng?.lng);
|
|
||||||
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
|
|
||||||
|
|
||||||
let name = loc.poiname?.trim() || undefined;
|
|
||||||
const address = loc.poiaddress?.trim() || undefined;
|
|
||||||
if (name === '我的位置' && address) name = address;
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
latitude: lat,
|
latitude: item.latitude,
|
||||||
longitude: lng,
|
longitude: item.longitude,
|
||||||
address,
|
address: item.address || undefined,
|
||||||
name,
|
name: item.title || undefined,
|
||||||
cityname: loc.cityname?.trim() || undefined,
|
cityname: item.city || undefined,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import { useEffect, useMemo, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import type { ClientRuntimeConfig } from '@dukang/shared-types';
|
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
import {
|
import {
|
||||||
buildTencentLocPickerUrl,
|
placeToPicked,
|
||||||
parseTencentLocPickerMessage,
|
type LbsPlaceItem,
|
||||||
type TencentPickedLocation,
|
type TencentPickedLocation,
|
||||||
} from '../lib/tencentLocPicker';
|
} from '../lib/tencentLocPicker';
|
||||||
|
|
||||||
@@ -13,79 +12,117 @@ type Props = {
|
|||||||
onPick: (loc: TencentPickedLocation) => void;
|
onPick: (loc: TencentPickedLocation) => void;
|
||||||
latitude?: number | null;
|
latitude?: number | null;
|
||||||
longitude?: number | null;
|
longitude?: number | null;
|
||||||
|
region?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
let cachedKey: string | null | undefined;
|
|
||||||
|
|
||||||
async function loadTencentLbsKey(): Promise<string> {
|
|
||||||
if (cachedKey) return cachedKey;
|
|
||||||
const cfg = await request<ClientRuntimeConfig>('PARTNER_H5', '/common/client-config', {
|
|
||||||
silent: true,
|
|
||||||
});
|
|
||||||
const key = (cfg.tencentLbsKey || '').trim();
|
|
||||||
if (!key) {
|
|
||||||
throw new Error('未配置腾讯位置服务 Key,请联系管理员在系统设置中配置');
|
|
||||||
}
|
|
||||||
cachedKey = key;
|
|
||||||
return key;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function TencentLocPickerOverlay({
|
export default function TencentLocPickerOverlay({
|
||||||
open,
|
open,
|
||||||
onClose,
|
onClose,
|
||||||
onPick,
|
onPick,
|
||||||
latitude,
|
latitude,
|
||||||
longitude,
|
longitude,
|
||||||
|
region,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const [key, setKey] = useState<string | null>(cachedKey ?? null);
|
const [keyword, setKeyword] = useState('');
|
||||||
|
const [items, setItems] = useState<LbsPlaceItem[]>([]);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [pending, setPending] = useState<TencentPickedLocation | null>(null);
|
const [pending, setPending] = useState<TencentPickedLocation | null>(null);
|
||||||
|
const [hint, setHint] = useState('输入地点名称搜索');
|
||||||
|
const seqRef = useRef(0);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) {
|
if (!open) {
|
||||||
|
setKeyword('');
|
||||||
|
setItems([]);
|
||||||
setPending(null);
|
setPending(null);
|
||||||
|
setHint('输入地点名称搜索');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let cancelled = false;
|
const lat = latitude != null ? Number(latitude) : NaN;
|
||||||
setError('');
|
const lng = longitude != null ? Number(longitude) : NaN;
|
||||||
if (key) return;
|
if (Number.isFinite(lat) && Number.isFinite(lng) && !(lat === 0 && lng === 0)) {
|
||||||
setLoading(true);
|
void loadNearby(lat, lng);
|
||||||
void loadTencentLbsKey()
|
|
||||||
.then((k) => {
|
|
||||||
if (!cancelled) setKey(k);
|
|
||||||
})
|
|
||||||
.catch((e) => {
|
|
||||||
if (!cancelled) setError(e instanceof Error ? e.message : '加载地图配置失败');
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
if (!cancelled) setLoading(false);
|
|
||||||
});
|
|
||||||
return () => {
|
|
||||||
cancelled = true;
|
|
||||||
};
|
|
||||||
}, [open, key]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!open) return;
|
|
||||||
function onMessage(event: MessageEvent) {
|
|
||||||
const picked = parseTencentLocPickerMessage(event.data);
|
|
||||||
if (!picked) return;
|
|
||||||
setPending(picked);
|
|
||||||
}
|
}
|
||||||
window.addEventListener('message', onMessage);
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
return () => window.removeEventListener('message', onMessage);
|
|
||||||
}, [open]);
|
}, [open]);
|
||||||
|
|
||||||
const src = useMemo(() => {
|
async function loadNearby(lat: number, lng: number) {
|
||||||
if (!key) return '';
|
const seq = ++seqRef.current;
|
||||||
const lat = latitude != null ? Number(latitude) : undefined;
|
setLoading(true);
|
||||||
const lng = longitude != null ? Number(longitude) : undefined;
|
setHint('正在加载附近地点…');
|
||||||
return buildTencentLocPickerUrl(key, {
|
try {
|
||||||
latitude: lat != null && Number.isFinite(lat) ? lat : undefined,
|
const res = await request<{ items: LbsPlaceItem[] }>(
|
||||||
longitude: lng != null && Number.isFinite(lng) ? lng : undefined,
|
'PARTNER_H5',
|
||||||
});
|
`/common/lbs/nearby?lat=${encodeURIComponent(String(lat))}&lng=${encodeURIComponent(String(lng))}`,
|
||||||
}, [key, latitude, longitude]);
|
{ silent: true },
|
||||||
|
);
|
||||||
|
if (seq !== seqRef.current) return;
|
||||||
|
setItems(res.items ?? []);
|
||||||
|
setHint(res.items?.length ? `附近 ${res.items.length} 个地点` : '附近暂无地点,请搜索');
|
||||||
|
} catch (e) {
|
||||||
|
if (seq !== seqRef.current) return;
|
||||||
|
setItems([]);
|
||||||
|
setHint(e instanceof Error ? e.message : '加载附近地点失败');
|
||||||
|
} finally {
|
||||||
|
if (seq === seqRef.current) setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runSearch() {
|
||||||
|
const trimmed = keyword.trim();
|
||||||
|
if (!trimmed) {
|
||||||
|
setHint('请输入搜索关键词');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const seq = ++seqRef.current;
|
||||||
|
setLoading(true);
|
||||||
|
setHint('搜索中…');
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams({ keyword: trimmed });
|
||||||
|
if (region?.trim()) params.set('region', region.trim());
|
||||||
|
const lat = latitude != null ? Number(latitude) : NaN;
|
||||||
|
const lng = longitude != null ? Number(longitude) : NaN;
|
||||||
|
if (Number.isFinite(lat) && Number.isFinite(lng)) {
|
||||||
|
params.set('lat', String(lat));
|
||||||
|
params.set('lng', String(lng));
|
||||||
|
}
|
||||||
|
const res = await request<{ items: LbsPlaceItem[] }>(
|
||||||
|
'PARTNER_H5',
|
||||||
|
`/common/lbs/suggest?${params.toString()}`,
|
||||||
|
{ silent: true },
|
||||||
|
);
|
||||||
|
if (seq !== seqRef.current) return;
|
||||||
|
setItems(res.items ?? []);
|
||||||
|
setHint(res.items?.length ? `找到 ${res.items.length} 个结果` : '无匹配结果');
|
||||||
|
} catch (e) {
|
||||||
|
if (seq !== seqRef.current) return;
|
||||||
|
setItems([]);
|
||||||
|
setHint(e instanceof Error ? e.message : '搜索失败');
|
||||||
|
} finally {
|
||||||
|
if (seq === seqRef.current) setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function useBrowserLocation() {
|
||||||
|
if (!navigator.geolocation) {
|
||||||
|
setHint('当前浏览器不支持定位');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoading(true);
|
||||||
|
navigator.geolocation.getCurrentPosition(
|
||||||
|
(pos) => {
|
||||||
|
const lat = pos.coords.latitude;
|
||||||
|
const lng = pos.coords.longitude;
|
||||||
|
setPending({ latitude: lat, longitude: lng, name: '当前位置' });
|
||||||
|
void loadNearby(lat, lng);
|
||||||
|
},
|
||||||
|
() => {
|
||||||
|
setLoading(false);
|
||||||
|
setHint('定位失败,请检查定位权限');
|
||||||
|
},
|
||||||
|
{ enableHighAccuracy: true, timeout: 12000 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (!open) return null;
|
if (!open) return null;
|
||||||
|
|
||||||
@@ -114,6 +151,7 @@ export default function TencentLocPickerOverlay({
|
|||||||
padding: '12px 16px',
|
padding: '12px 16px',
|
||||||
borderBottom: '1px solid rgba(0,0,0,0.06)',
|
borderBottom: '1px solid rgba(0,0,0,0.06)',
|
||||||
flexShrink: 0,
|
flexShrink: 0,
|
||||||
|
gap: 8,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<button type="button" className="partner-btn-outline" style={{ padding: '6px 12px' }} onClick={onClose}>
|
<button type="button" className="partner-btn-outline" style={{ padding: '6px 12px' }} onClick={onClose}>
|
||||||
@@ -130,44 +168,97 @@ export default function TencentLocPickerOverlay({
|
|||||||
确认
|
确认
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{pending ? (
|
|
||||||
<p
|
<div style={{ padding: '12px 16px', borderBottom: '1px solid rgba(0,0,0,0.04)', flexShrink: 0 }}>
|
||||||
className="label-md text-muted"
|
<div style={{ display: 'flex', gap: 8 }}>
|
||||||
style={{
|
<input
|
||||||
margin: 0,
|
value={keyword}
|
||||||
padding: '8px 16px',
|
onChange={(e) => setKeyword(e.target.value)}
|
||||||
borderBottom: '1px solid rgba(0,0,0,0.04)',
|
onKeyDown={(e) => {
|
||||||
flexShrink: 0,
|
if (e.key === 'Enter') void runSearch();
|
||||||
}}
|
}}
|
||||||
>
|
placeholder="输入小区 / 写字楼 / 门店名称"
|
||||||
已选 {pending.latitude.toFixed(6)}, {pending.longitude.toFixed(6)}
|
style={{
|
||||||
{pending.name ? ` · ${pending.name}` : ''}
|
flex: 1,
|
||||||
</p>
|
padding: '10px 12px',
|
||||||
) : null}
|
border: '1px solid rgba(0,0,0,0.12)',
|
||||||
<div style={{ flex: 1, minHeight: 0, position: 'relative' }}>
|
borderRadius: 8,
|
||||||
{loading ? (
|
fontSize: 14,
|
||||||
<p className="label-md text-muted" style={{ padding: 24, textAlign: 'center' }}>
|
}}
|
||||||
加载地图…
|
|
||||||
</p>
|
|
||||||
) : error ? (
|
|
||||||
<div style={{ padding: 24 }}>
|
|
||||||
<p className="label-md" style={{ color: 'var(--color-heritage-red, #a61d24)' }}>
|
|
||||||
{error}
|
|
||||||
</p>
|
|
||||||
<p className="label-md text-muted" style={{ marginTop: 12 }}>
|
|
||||||
若地图能开但看不到附近地点列表,请确认 Key 已开启 WebServiceAPI,并白名单
|
|
||||||
apis.map.qq.com。
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
) : src ? (
|
|
||||||
<iframe
|
|
||||||
title="腾讯地图选点"
|
|
||||||
src={src}
|
|
||||||
allow="geolocation *"
|
|
||||||
style={{ width: '100%', height: '100%', border: 0, display: 'block' }}
|
|
||||||
/>
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="partner-btn-primary"
|
||||||
|
style={{ width: 'auto', padding: '8px 14px' }}
|
||||||
|
disabled={loading}
|
||||||
|
onClick={() => void runSearch()}
|
||||||
|
>
|
||||||
|
搜索
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div style={{ display: 'flex', gap: 8, marginTop: 8, alignItems: 'center' }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="partner-btn-outline"
|
||||||
|
style={{ padding: '6px 12px' }}
|
||||||
|
disabled={loading}
|
||||||
|
onClick={useBrowserLocation}
|
||||||
|
>
|
||||||
|
定位当前位置
|
||||||
|
</button>
|
||||||
|
<span className="label-md text-muted">{hint}</span>
|
||||||
|
</div>
|
||||||
|
{pending ? (
|
||||||
|
<p className="label-md text-muted" style={{ margin: '8px 0 0' }}>
|
||||||
|
已选 {pending.latitude.toFixed(6)}, {pending.longitude.toFixed(6)}
|
||||||
|
{pending.name ? ` · ${pending.name}` : ''}
|
||||||
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div style={{ flex: 1, minHeight: 0, overflow: 'auto', WebkitOverflowScrolling: 'touch' }}>
|
||||||
|
{loading && !items.length ? (
|
||||||
|
<p className="label-md text-muted" style={{ padding: 24, textAlign: 'center' }}>
|
||||||
|
加载中…
|
||||||
|
</p>
|
||||||
|
) : items.length ? (
|
||||||
|
<ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
|
||||||
|
{items.map((item) => {
|
||||||
|
const active =
|
||||||
|
pending?.latitude === item.latitude && pending?.longitude === item.longitude;
|
||||||
|
return (
|
||||||
|
<li key={`${item.id}-${item.latitude}-${item.longitude}`}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setPending(placeToPicked(item))}
|
||||||
|
style={{
|
||||||
|
width: '100%',
|
||||||
|
textAlign: 'left',
|
||||||
|
padding: '12px 16px',
|
||||||
|
border: 0,
|
||||||
|
borderBottom: '1px solid rgba(0,0,0,0.06)',
|
||||||
|
background: active ? 'rgba(166, 29, 36, 0.06)' : '#fff',
|
||||||
|
cursor: 'pointer',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ fontWeight: 600, fontSize: 15 }}>{item.title}</div>
|
||||||
|
<div className="label-md text-muted" style={{ marginTop: 4 }}>
|
||||||
|
{item.address}
|
||||||
|
</div>
|
||||||
|
<div className="label-md text-muted" style={{ marginTop: 2, fontSize: 12 }}>
|
||||||
|
{item.latitude.toFixed(6)}, {item.longitude.toFixed(6)}
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
) : (
|
||||||
|
<p className="label-md text-muted" style={{ padding: 24, textAlign: 'center' }}>
|
||||||
|
{hint}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,75 +6,21 @@ export type TencentPickedLocation = {
|
|||||||
cityname?: string;
|
cityname?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type LocPickerMessage = {
|
export type LbsPlaceItem = {
|
||||||
module?: string;
|
id: string;
|
||||||
latlng?: { lat?: number; lng?: number };
|
title: string;
|
||||||
poiaddress?: string;
|
address: string;
|
||||||
poiname?: string;
|
latitude: number;
|
||||||
cityname?: string;
|
longitude: number;
|
||||||
|
city?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const REFERER = 'dukang';
|
export function placeToPicked(item: LbsPlaceItem): TencentPickedLocation {
|
||||||
|
|
||||||
function coerceMessageData(data: unknown): LocPickerMessage | null {
|
|
||||||
if (data == null) return null;
|
|
||||||
if (typeof data === 'string') {
|
|
||||||
const trimmed = data.trim();
|
|
||||||
if (!trimmed || (trimmed[0] !== '{' && trimmed[0] !== '[')) return null;
|
|
||||||
try {
|
|
||||||
return JSON.parse(trimmed) as LocPickerMessage;
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (typeof data === 'object') return data as LocPickerMessage;
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildTencentLocPickerUrl(
|
|
||||||
key: string,
|
|
||||||
options?: { latitude?: number; longitude?: number },
|
|
||||||
): string {
|
|
||||||
const params = new URLSearchParams({
|
|
||||||
search: '1',
|
|
||||||
type: '1',
|
|
||||||
key,
|
|
||||||
referer: REFERER,
|
|
||||||
policy: '1',
|
|
||||||
total: '20',
|
|
||||||
radius: '2000',
|
|
||||||
});
|
|
||||||
const lat = options?.latitude;
|
|
||||||
const lng = options?.longitude;
|
|
||||||
if (
|
|
||||||
lat != null &&
|
|
||||||
lng != null &&
|
|
||||||
Number.isFinite(lat) &&
|
|
||||||
Number.isFinite(lng) &&
|
|
||||||
!(lat === 0 && lng === 0)
|
|
||||||
) {
|
|
||||||
params.set('coord', `${lat},${lng}`);
|
|
||||||
params.set('coordtype', '5');
|
|
||||||
}
|
|
||||||
return `https://apis.map.qq.com/tools/locpicker?${params.toString()}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function parseTencentLocPickerMessage(data: unknown): TencentPickedLocation | null {
|
|
||||||
const loc = coerceMessageData(data);
|
|
||||||
if (!loc || loc.module !== 'locationPicker') return null;
|
|
||||||
const lat = Number(loc.latlng?.lat);
|
|
||||||
const lng = Number(loc.latlng?.lng);
|
|
||||||
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
|
|
||||||
|
|
||||||
let name = loc.poiname?.trim() || undefined;
|
|
||||||
const address = loc.poiaddress?.trim() || undefined;
|
|
||||||
if (name === '我的位置' && address) name = address;
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
latitude: lat,
|
latitude: item.latitude,
|
||||||
longitude: lng,
|
longitude: item.longitude,
|
||||||
address,
|
address: item.address || undefined,
|
||||||
name,
|
name: item.title || undefined,
|
||||||
cityname: loc.cityname?.trim() || undefined,
|
cityname: item.city || undefined,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,10 +59,9 @@ WX_PAY_NOTIFY_URL=https://api.dukanghaoke.com/api/v1/callbacks/wechat/pay
|
|||||||
# 企业微信智能机器人总开关(Bot 实例在 HQ「企微机器人」模块创建)
|
# 企业微信智能机器人总开关(Bot 实例在 HQ「企微机器人」模块创建)
|
||||||
WECOM_AIBOT_ENABLED=false
|
WECOM_AIBOT_ENABLED=false
|
||||||
|
|
||||||
# 腾讯位置服务(地理编码 / 逆地理 / 地图选点组件)
|
# 腾讯位置服务(地理编码 / 逆地理 / 地点搜索选点,服务端调用)
|
||||||
# 控制台须:1) 开启 WebServiceAPI(否则选点搜不到附近列表)
|
# 控制台须开启 WebServiceAPI;服务端调用建议 Key 不设域名白名单,或改用 IP 白名单
|
||||||
# 2) WebService 域名白名单加入 apis.map.qq.com
|
# (浏览器内嵌官方选点组件已弃用,避免 mapapi.qq.com / formatted_addresses 崩溃)
|
||||||
# 3) 浏览器 Key 按管理端 / 合伙人 H5 域名限制(可选)
|
|
||||||
TENCENT_LBS_KEY=
|
TENCENT_LBS_KEY=
|
||||||
|
|
||||||
# 阿里云 OSS(ali-oss@6.x;凭证齐全时直传,缺失则服务端报错)
|
# 阿里云 OSS(ali-oss@6.x;凭证齐全时直传,缺失则服务端报错)
|
||||||
|
|||||||
@@ -107,7 +107,7 @@ export const SYSTEM_CONFIG_FIELDS: SystemConfigFieldMeta[] = [
|
|||||||
{ key: 'OSS_MAX_UPLOAD_BYTES', label: '单文件上限(字节)', group: G.oss, type: 'number', requiresRestart: false },
|
{ key: 'OSS_MAX_UPLOAD_BYTES', label: '单文件上限(字节)', group: G.oss, type: 'number', requiresRestart: false },
|
||||||
|
|
||||||
{ key: 'USER_H5_URL', label: 'C 端 H5 落地页', group: G.app, type: 'string', requiresRestart: false },
|
{ key: 'USER_H5_URL', label: 'C 端 H5 落地页', group: G.app, type: 'string', requiresRestart: false },
|
||||||
{ key: 'TENCENT_LBS_KEY', label: '腾讯位置服务 Key(须开 WebServiceAPI;白名单含 apis.map.qq.com)', group: G.app, type: 'password', secret: true, requiresRestart: false },
|
{ key: 'TENCENT_LBS_KEY', label: '腾讯位置服务 Key(须开 WebServiceAPI;服务端地点搜索/地理编码)', group: G.app, type: 'password', secret: true, requiresRestart: false },
|
||||||
|
|
||||||
{ key: 'DEPLOY_WEBHOOK_URL', label: '发布 Webhook URL', group: G.deploy, type: 'string', requiresRestart: false },
|
{ key: 'DEPLOY_WEBHOOK_URL', label: '发布 Webhook URL', group: G.deploy, type: 'string', requiresRestart: false },
|
||||||
{ key: 'DEPLOY_WEBHOOK_SECRET', label: '发布 Webhook Secret', group: G.deploy, type: 'password', secret: true, requiresRestart: false },
|
{ key: 'DEPLOY_WEBHOOK_SECRET', label: '发布 Webhook Secret', group: G.deploy, type: 'password', secret: true, requiresRestart: false },
|
||||||
|
|||||||
@@ -16,10 +16,38 @@ export type GeocodeAddressResult = {
|
|||||||
logId: bigint;
|
logId: bigint;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type PlaceSuggestItem = {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
address: string;
|
||||||
|
latitude: number;
|
||||||
|
longitude: number;
|
||||||
|
city?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ReverseGeocodeDetailResult = {
|
||||||
|
latitude: number;
|
||||||
|
longitude: number;
|
||||||
|
address: string;
|
||||||
|
name?: string;
|
||||||
|
province: string;
|
||||||
|
city: string;
|
||||||
|
district: string;
|
||||||
|
logId: bigint;
|
||||||
|
};
|
||||||
|
|
||||||
function normalizeCityName(name: string) {
|
function normalizeCityName(name: string) {
|
||||||
return name.replace(/市$/, '').trim();
|
return name.replace(/市$/, '').trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type TencentPlaceRow = {
|
||||||
|
id?: string;
|
||||||
|
title?: string;
|
||||||
|
address?: string;
|
||||||
|
city?: string;
|
||||||
|
location?: { lat?: number; lng?: number };
|
||||||
|
};
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TencentLbsProvider {
|
export class TencentLbsProvider {
|
||||||
private readonly logger = new Logger(TencentLbsProvider.name);
|
private readonly logger = new Logger(TencentLbsProvider.name);
|
||||||
@@ -203,4 +231,202 @@ export class TencentLbsProvider {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private mapPlaceRows(rows: TencentPlaceRow[] | undefined): PlaceSuggestItem[] {
|
||||||
|
if (!rows?.length) return [];
|
||||||
|
const out: PlaceSuggestItem[] = [];
|
||||||
|
for (const row of rows) {
|
||||||
|
const lat = Number(row.location?.lat);
|
||||||
|
const lng = Number(row.location?.lng);
|
||||||
|
if (!Number.isFinite(lat) || !Number.isFinite(lng)) continue;
|
||||||
|
const title = (row.title || '').trim();
|
||||||
|
const address = (row.address || '').trim();
|
||||||
|
if (!title && !address) continue;
|
||||||
|
out.push({
|
||||||
|
id: String(row.id || `${lat},${lng}`),
|
||||||
|
title: title || address,
|
||||||
|
address: address || title,
|
||||||
|
latitude: lat,
|
||||||
|
longitude: lng,
|
||||||
|
city: row.city?.trim() || undefined,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 关键词输入提示(地点搜索) */
|
||||||
|
async suggestPlaces(
|
||||||
|
keyword: string,
|
||||||
|
options?: { region?: string; latitude?: number; longitude?: number },
|
||||||
|
): Promise<{ items: PlaceSuggestItem[]; error?: string }> {
|
||||||
|
const trimmed = keyword.trim();
|
||||||
|
if (!trimmed) return { items: [] };
|
||||||
|
if (!this.isEnabled()) {
|
||||||
|
return { items: [], error: 'TENCENT_LBS_KEY 未配置' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = new URL('https://apis.map.qq.com/ws/place/v1/suggestion');
|
||||||
|
url.searchParams.set('keyword', trimmed.slice(0, 64));
|
||||||
|
url.searchParams.set('key', this.getLbsKey());
|
||||||
|
url.searchParams.set('policy', '1');
|
||||||
|
url.searchParams.set('page_index', '1');
|
||||||
|
url.searchParams.set('page_size', '20');
|
||||||
|
const region = options?.region?.trim();
|
||||||
|
if (region) url.searchParams.set('region', region);
|
||||||
|
if (
|
||||||
|
options?.latitude != null &&
|
||||||
|
options?.longitude != null &&
|
||||||
|
Number.isFinite(options.latitude) &&
|
||||||
|
Number.isFinite(options.longitude)
|
||||||
|
) {
|
||||||
|
url.searchParams.set('location', `${options.latitude},${options.longitude}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(url.toString());
|
||||||
|
const data = (await res.json()) as {
|
||||||
|
status?: number;
|
||||||
|
message?: string;
|
||||||
|
data?: TencentPlaceRow[];
|
||||||
|
};
|
||||||
|
if (data.status !== 0) {
|
||||||
|
this.logger.warn(`Tencent LBS suggest failed: ${data.message ?? data.status}`);
|
||||||
|
return { items: [], error: data.message || '地点搜索失败' };
|
||||||
|
}
|
||||||
|
return { items: this.mapPlaceRows(data.data) };
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
|
this.logger.error(`Tencent LBS suggest failed: ${message}`);
|
||||||
|
return { items: [], error: message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 周边地点(打开选点时预填附近列表) */
|
||||||
|
async exploreNearby(
|
||||||
|
latitude: number,
|
||||||
|
longitude: number,
|
||||||
|
radiusMeters = 1000,
|
||||||
|
): Promise<{ items: PlaceSuggestItem[]; error?: string }> {
|
||||||
|
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) {
|
||||||
|
return { items: [], error: '经纬度无效' };
|
||||||
|
}
|
||||||
|
if (!this.isEnabled()) {
|
||||||
|
return { items: [], error: 'TENCENT_LBS_KEY 未配置' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const radius = Math.min(5000, Math.max(200, Math.round(radiusMeters)));
|
||||||
|
const url = new URL('https://apis.map.qq.com/ws/place/v1/explore');
|
||||||
|
url.searchParams.set('boundary', `nearby(${latitude},${longitude},${radius})`);
|
||||||
|
url.searchParams.set('policy', '1');
|
||||||
|
url.searchParams.set('page_size', '20');
|
||||||
|
url.searchParams.set('key', this.getLbsKey());
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(url.toString());
|
||||||
|
const data = (await res.json()) as {
|
||||||
|
status?: number;
|
||||||
|
message?: string;
|
||||||
|
data?: TencentPlaceRow[];
|
||||||
|
};
|
||||||
|
if (data.status !== 0) {
|
||||||
|
this.logger.warn(`Tencent LBS explore failed: ${data.message ?? data.status}`);
|
||||||
|
return { items: [], error: data.message || '周边检索失败' };
|
||||||
|
}
|
||||||
|
return { items: this.mapPlaceRows(data.data) };
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
|
this.logger.error(`Tencent LBS explore failed: ${message}`);
|
||||||
|
return { items: [], error: message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 逆地理(含地址文案,供选点回填) */
|
||||||
|
async reverseGeocodeDetail(
|
||||||
|
latitude: number,
|
||||||
|
longitude: number,
|
||||||
|
): Promise<{ item: ReverseGeocodeDetailResult | null; error?: string }> {
|
||||||
|
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) {
|
||||||
|
return { item: null, error: '经纬度无效' };
|
||||||
|
}
|
||||||
|
if (!this.isEnabled()) {
|
||||||
|
return { item: null, error: 'TENCENT_LBS_KEY 未配置' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = new URL('https://apis.map.qq.com/ws/geocoder/v1/');
|
||||||
|
url.searchParams.set('location', `${latitude},${longitude}`);
|
||||||
|
url.searchParams.set('key', this.getLbsKey());
|
||||||
|
url.searchParams.set('get_poi', '1');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(url.toString());
|
||||||
|
const data = (await res.json()) as {
|
||||||
|
status?: number;
|
||||||
|
message?: string;
|
||||||
|
result?: {
|
||||||
|
address?: string;
|
||||||
|
formatted_addresses?: { recommend?: string; rough?: string };
|
||||||
|
address_component?: {
|
||||||
|
province?: string;
|
||||||
|
city?: string;
|
||||||
|
district?: string;
|
||||||
|
street?: string;
|
||||||
|
street_number?: string;
|
||||||
|
};
|
||||||
|
ad_info?: {
|
||||||
|
province?: string;
|
||||||
|
city?: string;
|
||||||
|
district?: string;
|
||||||
|
};
|
||||||
|
pois?: Array<{ title?: string; address?: string }>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
if (data.status !== 0 || !data.result) {
|
||||||
|
return { item: null, error: data.message || '逆地理编码失败' };
|
||||||
|
}
|
||||||
|
const result = data.result;
|
||||||
|
const ad = result.ad_info ?? result.address_component;
|
||||||
|
const province = ad?.province ?? '';
|
||||||
|
const city = normalizeCityName(ad?.city ?? '');
|
||||||
|
const district = ad?.district ?? '';
|
||||||
|
const recommend =
|
||||||
|
result.formatted_addresses?.recommend?.trim() ||
|
||||||
|
result.formatted_addresses?.rough?.trim() ||
|
||||||
|
result.address?.trim() ||
|
||||||
|
'';
|
||||||
|
const poiTitle = result.pois?.[0]?.title?.trim();
|
||||||
|
if (!recommend && !poiTitle) {
|
||||||
|
return { item: null, error: '未解析到地址' };
|
||||||
|
}
|
||||||
|
const log = await this.prisma.logThirdParty.create({
|
||||||
|
data: {
|
||||||
|
provider: 'WECHAT_MAP',
|
||||||
|
scene: 'REVERSE_GEOCODE',
|
||||||
|
requestUrl: 'https://apis.map.qq.com/ws/geocoder/v1/',
|
||||||
|
requestBody: { latitude, longitude, detail: true },
|
||||||
|
responseBody: {
|
||||||
|
status: data.status,
|
||||||
|
address: recommend,
|
||||||
|
city,
|
||||||
|
},
|
||||||
|
status: 'SUCCESS',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
item: {
|
||||||
|
latitude,
|
||||||
|
longitude,
|
||||||
|
address: recommend || poiTitle || '',
|
||||||
|
name: poiTitle || recommend || undefined,
|
||||||
|
province,
|
||||||
|
city,
|
||||||
|
district,
|
||||||
|
logId: log.id,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
|
this.logger.error(`Tencent LBS reverse detail failed: ${message}`);
|
||||||
|
return { item: null, error: message };
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ export class ClientConfigController {
|
|||||||
mockSms: cfg.mockSms,
|
mockSms: cfg.mockSms,
|
||||||
mockWechat: cfg.mockWechat,
|
mockWechat: cfg.mockWechat,
|
||||||
wxAuthorize: cfg.wxAuthorize,
|
wxAuthorize: cfg.wxAuthorize,
|
||||||
/** 浏览器地图选点用;建议在腾讯控制台按域名限制 Key */
|
/** 可选暴露;选点已改为服务端 /common/lbs,前端可不依赖此字段 */
|
||||||
tencentLbsKey: cfg.tencentLbsKey || undefined,
|
tencentLbsKey: cfg.tencentLbsKey || undefined,
|
||||||
miniHome: {
|
miniHome: {
|
||||||
banners: parseMiniHomeBanners(env.MINI_HOME_BANNERS),
|
banners: parseMiniHomeBanners(env.MINI_HOME_BANNERS),
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { TicketController } from './ticket.controller';
|
|||||||
import { ThirdPartyLogController } from './third-party-log.controller';
|
import { ThirdPartyLogController } from './third-party-log.controller';
|
||||||
import { WechatController } from './wechat.controller';
|
import { WechatController } from './wechat.controller';
|
||||||
import { ClientConfigController } from './client-config.controller';
|
import { ClientConfigController } from './client-config.controller';
|
||||||
|
import { LbsController } from './lbs.controller';
|
||||||
import { WechatLocationService } from './wechat-location.service';
|
import { WechatLocationService } from './wechat-location.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
@@ -25,6 +26,7 @@ import { WechatLocationService } from './wechat-location.service';
|
|||||||
ThirdPartyLogController,
|
ThirdPartyLogController,
|
||||||
WechatController,
|
WechatController,
|
||||||
ClientConfigController,
|
ClientConfigController,
|
||||||
|
LbsController,
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
ResourceService,
|
ResourceService,
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Query,
|
||||||
|
ServiceUnavailableException,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||||
|
import { TencentLbsProvider } from '../../integrations/map/tencent-lbs.provider';
|
||||||
|
|
||||||
|
function parseCoord(raw: string | undefined, label: string): number | undefined {
|
||||||
|
if (raw == null || raw === '') return undefined;
|
||||||
|
const n = Number(raw);
|
||||||
|
if (!Number.isFinite(n)) throw new BadRequestException(`${label}无效`);
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Controller('common/lbs')
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
export class LbsController {
|
||||||
|
constructor(private readonly tencentLbs: TencentLbsProvider) {}
|
||||||
|
|
||||||
|
@Get('suggest')
|
||||||
|
async suggest(
|
||||||
|
@Query('keyword') keyword?: string,
|
||||||
|
@Query('region') region?: string,
|
||||||
|
@Query('lat') lat?: string,
|
||||||
|
@Query('lng') lng?: string,
|
||||||
|
) {
|
||||||
|
if (!this.tencentLbs.isEnabled()) {
|
||||||
|
throw new ServiceUnavailableException('未配置腾讯位置服务 Key(TENCENT_LBS_KEY)');
|
||||||
|
}
|
||||||
|
const q = (keyword ?? '').trim();
|
||||||
|
if (!q) return { items: [] };
|
||||||
|
const latitude = parseCoord(lat, '纬度');
|
||||||
|
const longitude = parseCoord(lng, '经度');
|
||||||
|
const result = await this.tencentLbs.suggestPlaces(q, {
|
||||||
|
region: region?.trim() || undefined,
|
||||||
|
latitude,
|
||||||
|
longitude,
|
||||||
|
});
|
||||||
|
if (result.error && !result.items.length) {
|
||||||
|
throw new BadRequestException(result.error);
|
||||||
|
}
|
||||||
|
return { items: result.items };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('nearby')
|
||||||
|
async nearby(@Query('lat') lat?: string, @Query('lng') lng?: string, @Query('radius') radius?: string) {
|
||||||
|
if (!this.tencentLbs.isEnabled()) {
|
||||||
|
throw new ServiceUnavailableException('未配置腾讯位置服务 Key(TENCENT_LBS_KEY)');
|
||||||
|
}
|
||||||
|
const latitude = parseCoord(lat, '纬度');
|
||||||
|
const longitude = parseCoord(lng, '经度');
|
||||||
|
if (latitude == null || longitude == null) {
|
||||||
|
throw new BadRequestException('请提供 lat、lng');
|
||||||
|
}
|
||||||
|
const r = radius != null && radius !== '' ? Number(radius) : 1000;
|
||||||
|
const result = await this.tencentLbs.exploreNearby(latitude, longitude, Number.isFinite(r) ? r : 1000);
|
||||||
|
if (result.error && !result.items.length) {
|
||||||
|
throw new BadRequestException(result.error);
|
||||||
|
}
|
||||||
|
return { items: result.items };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('reverse')
|
||||||
|
async reverse(@Query('lat') lat?: string, @Query('lng') lng?: string) {
|
||||||
|
if (!this.tencentLbs.isEnabled()) {
|
||||||
|
throw new ServiceUnavailableException('未配置腾讯位置服务 Key(TENCENT_LBS_KEY)');
|
||||||
|
}
|
||||||
|
const latitude = parseCoord(lat, '纬度');
|
||||||
|
const longitude = parseCoord(lng, '经度');
|
||||||
|
if (latitude == null || longitude == null) {
|
||||||
|
throw new BadRequestException('请提供 lat、lng');
|
||||||
|
}
|
||||||
|
const result = await this.tencentLbs.reverseGeocodeDetail(latitude, longitude);
|
||||||
|
if (!result.item) {
|
||||||
|
throw new BadRequestException(result.error || '逆地理编码失败');
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
latitude: result.item.latitude,
|
||||||
|
longitude: result.item.longitude,
|
||||||
|
address: result.item.address,
|
||||||
|
name: result.item.name,
|
||||||
|
province: result.item.province,
|
||||||
|
city: result.item.city,
|
||||||
|
district: result.item.district,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user