fix(partner): use server LBS search instead of locpicker iframe

Avoid Tencent locpicker _listTap crash when selecting POI in WeChat WebView.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-07-29 11:31:02 +08:00
parent c3362851ff
commit b0ff254cd8
5 changed files with 258 additions and 164 deletions
@@ -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,43 +168,96 @@ 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="输入小区 / 写字楼 / 门店名称"
style={{
flex: 1,
padding: '10px 12px',
border: '1px solid rgba(0,0,0,0.12)',
borderRadius: 8,
fontSize: 14,
}}
/>
<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.latitude.toFixed(6)}, {pending.longitude.toFixed(6)}
{pending.name ? ` · ${pending.name}` : ''} {pending.name ? ` · ${pending.name}` : ''}
</p> </p>
) : null} ) : null}
<div style={{ flex: 1, minHeight: 0, position: 'relative' }}>
{loading ? (
<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> </div>
) : src ? (
<iframe <div style={{ flex: 1, minHeight: 0, overflow: 'auto', WebkitOverflowScrolling: 'touch' }}>
title="腾讯地图选点" {loading && !items.length ? (
src={src} <p className="label-md text-muted" style={{ padding: 24, textAlign: 'center' }}>
allow="geolocation *"
style={{ width: '100%', height: '100%', border: 0, display: 'block' }} </p>
/> ) : items.length ? (
) : null} <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> </div>
); );
+13 -67
View File
@@ -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,
}; };
} }
+29 -2
View File
@@ -13,7 +13,7 @@ import { resolveRegionBinding } from '../lib/china-region';
import { checkStorePhoneAvailable } from '../lib/storePhone'; import { checkStorePhoneAvailable } from '../lib/storePhone';
import { formatStoreCoords } from '../lib/storeLocate'; import { formatStoreCoords, locateStorePosition } from '../lib/storeLocate';
import { fetchPartnerCities, type OpenCityOption } from '../lib/upload'; import { fetchPartnerCities, type OpenCityOption } from '../lib/upload';
@@ -101,6 +101,8 @@ export default function StoreCreatePage() {
const [categoryTree, setCategoryTree] = useState<StoreCategoryNode[]>([]); const [categoryTree, setCategoryTree] = useState<StoreCategoryNode[]>([]);
const [locating, setLocating] = useState(false);
const [mapPickerOpen, setMapPickerOpen] = useState(false); const [mapPickerOpen, setMapPickerOpen] = useState(false);
const draftSaveDisabledRef = useRef(false); const draftSaveDisabledRef = useRef(false);
@@ -660,6 +662,31 @@ export default function StoreCreatePage() {
<textarea rows={2} placeholder="请输入详细门牌号" value={form.address} onChange={(e) => patchForm({ address: e.target.value })} /> <textarea rows={2} placeholder="请输入详细门牌号" value={form.address} onChange={(e) => patchForm({ address: e.target.value })} />
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8, flexWrap: 'wrap' }}> <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
<button
type="button"
className="partner-btn-outline"
style={{ padding: '8px 12px', fontSize: 13 }}
disabled={locating}
onClick={() => {
void (async () => {
setLocating(true);
try {
const pos = await locateStorePosition();
patchForm({
latitude: String(pos.latitude),
longitude: String(pos.longitude),
});
toastSuccess('已获取当前坐标');
} catch (e) {
toastError(e instanceof Error ? e.message : '定位失败');
} finally {
setLocating(false);
}
})();
}}
>
{locating ? '定位中…' : '获取当前位置'}
</button>
<button <button
type="button" type="button"
className="partner-btn-outline" className="partner-btn-outline"
@@ -671,7 +698,7 @@ export default function StoreCreatePage() {
<span className="label-md text-muted"> <span className="label-md text-muted">
{formatStoreCoords(form.latitude, form.longitude) {formatStoreCoords(form.latitude, form.longitude)
? `坐标:${formatStoreCoords(form.latitude, form.longitude)}` ? `坐标:${formatStoreCoords(form.latitude, form.longitude)}`
: '未选点(可地图选点)'} : '未定位(可定位或地图选点)'}
</span> </span>
</div> </div>
+32 -2
View File
@@ -6,7 +6,7 @@ import { toastError, toastSuccess } from '../lib/toast';
import { usePartnerSession } from '../contexts/PartnerSessionContext'; import { usePartnerSession } from '../contexts/PartnerSessionContext';
import { canManagePartnerStore } from '../lib/partnerAccess'; import { canManagePartnerStore } from '../lib/partnerAccess';
import { normalizeStringArray, patchEnvPhotoAt } from '../lib/storeDraft'; import { normalizeStringArray, patchEnvPhotoAt } from '../lib/storeDraft';
import { formatStoreCoords } from '../lib/storeLocate'; import { formatStoreCoords, locateStorePosition } from '../lib/storeLocate';
import OssUploadField from '../components/OssUploadField'; import OssUploadField from '../components/OssUploadField';
import TencentLocPickerOverlay from '../components/TencentLocPickerOverlay'; import TencentLocPickerOverlay from '../components/TencentLocPickerOverlay';
import { import {
@@ -55,6 +55,7 @@ export default function StoreDetailPage() {
const [statusSaving, setStatusSaving] = useState(false); const [statusSaving, setStatusSaving] = useState(false);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [mediaSaving, setMediaSaving] = useState(false); const [mediaSaving, setMediaSaving] = useState(false);
const [locating, setLocating] = useState(false);
const [mapPickerOpen, setMapPickerOpen] = useState(false); const [mapPickerOpen, setMapPickerOpen] = useState(false);
const [actionError, setActionError] = useState(''); const [actionError, setActionError] = useState('');
const [closeConfirmOpen, setCloseConfirmOpen] = useState(false); const [closeConfirmOpen, setCloseConfirmOpen] = useState(false);
@@ -345,6 +346,35 @@ export default function StoreDetailPage() {
<textarea disabled={readOnly} rows={2} value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} /> <textarea disabled={readOnly} rows={2} value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} />
{!readOnly ? ( {!readOnly ? (
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8, flexWrap: 'wrap' }}> <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
<button
type="button"
className="partner-btn-outline"
style={{ padding: '8px 12px', fontSize: 13 }}
disabled={locating}
onClick={() => {
void (async () => {
setLocating(true);
setActionError('');
try {
const pos = await locateStorePosition();
setForm((prev) => ({
...prev,
latitude: String(pos.latitude),
longitude: String(pos.longitude),
}));
toastSuccess('已获取当前坐标');
} catch (e) {
const msg = e instanceof Error ? e.message : '定位失败';
setActionError(msg);
toastError(msg);
} finally {
setLocating(false);
}
})();
}}
>
{locating ? '定位中…' : '获取当前位置'}
</button>
<button <button
type="button" type="button"
className="partner-btn-outline" className="partner-btn-outline"
@@ -356,7 +386,7 @@ export default function StoreDetailPage() {
<span className="label-md text-muted"> <span className="label-md text-muted">
{formatStoreCoords(form.latitude, form.longitude) {formatStoreCoords(form.latitude, form.longitude)
? `坐标:${formatStoreCoords(form.latitude, form.longitude)}` ? `坐标:${formatStoreCoords(form.latitude, form.longitude)}`
: '未选点'} : '未定位'}
</span> </span>
</div> </div>
) : formatStoreCoords(form.latitude, form.longitude) ? ( ) : formatStoreCoords(form.latitude, form.longitude) ? (
@@ -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,
/** 合伙人 H5 腾讯地图 locpicker iframe 选点 */ /** 可选暴露;选点已改为服务端 /common/lbs,前端可不依赖此字段 */
tencentLbsKey: cfg.tencentLbsKey || undefined, tencentLbsKey: cfg.tencentLbsKey || undefined,
miniHome: { miniHome: {
banners: parseMiniHomeBanners(env.MINI_HOME_BANNERS), banners: parseMiniHomeBanners(env.MINI_HOME_BANNERS),