feat: 优化定位体验——反向地理编码显示地名,定位失败明确提示
- 新增 /api/location/regeo 接口,通过高德逆地理编码将 GPS 坐标转为地名 - 页面加载时自动定位,成功后显示"当前位置:浦东新区 xxx" - 定位失败/权限被拒时显示明确提示+重试按钮,不再静默默认上海 - 无可用位置时阻止创建房间,引导用户手动搜索选择地点
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const lat = searchParams.get("lat");
|
||||
const lng = searchParams.get("lng");
|
||||
|
||||
if (!lat || !lng) {
|
||||
return NextResponse.json(
|
||||
{ error: "lat and lng are required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const apiKey = process.env.AMAP_API_KEY;
|
||||
if (!apiKey) {
|
||||
return NextResponse.json(
|
||||
{ error: "AMAP_API_KEY not configured" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL("https://restapi.amap.com/v3/geocode/regeo");
|
||||
url.searchParams.set("key", apiKey);
|
||||
url.searchParams.set("location", `${lng},${lat}`);
|
||||
url.searchParams.set("extensions", "base");
|
||||
|
||||
const res = await fetch(url.toString());
|
||||
const data = await res.json();
|
||||
|
||||
if (data.status !== "1" || !data.regeocode) {
|
||||
return NextResponse.json({ name: null });
|
||||
}
|
||||
|
||||
const comp = data.regeocode.addressComponent;
|
||||
const district = comp?.district || comp?.city || "";
|
||||
const township = comp?.township || "";
|
||||
const neighborhood = comp?.neighborhood?.name || "";
|
||||
|
||||
const name = [district, township, neighborhood]
|
||||
.filter(Boolean)
|
||||
.join(" ")
|
||||
.trim();
|
||||
|
||||
return NextResponse.json({
|
||||
name: name || data.regeocode.formatted_address || null,
|
||||
formatted: data.regeocode.formatted_address || null,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("Regeo error:", e);
|
||||
return NextResponse.json({ name: null });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user