70 lines
3.1 KiB
TypeScript
70 lines
3.1 KiB
TypeScript
import type { Cinema } from "@/lib/cinemas";
|
|
import type { Locale } from "@/lib/i18n/messages";
|
|
|
|
/**
|
|
* URL สำหรับฝังแผนที่ Google Maps ในหน้าเว็บ (ไม่ต้องใช้ API key)
|
|
*
|
|
* ลำดับการเลือกตำแหน่ง:
|
|
* 1. `map_url` ของโรงหนัง — ดึงค่า q / ll / พิกัดในลิงก์มาใช้
|
|
* 2. `coordinates` ที่กรอกในหลังบ้าน
|
|
* 3. ไม่มีทั้งคู่ → null (ให้ UI แสดง "ไม่มีข้อมูล")
|
|
*/
|
|
|
|
/** แกะคำค้น/พิกัดออกจากลิงก์ Google Maps ที่ผู้ใช้กรอก */
|
|
export function mapQueryFromUrl(url: string | null | undefined): string | null {
|
|
const value = (url ?? "").trim();
|
|
if (!value) return null;
|
|
|
|
// ลิงก์ย่อ (maps.app.goo.gl / goo.gl/maps) แกะพิกัดไม่ได้ → ปล่อยให้ไปใช้พิกัดในหลังบ้าน
|
|
if (/(?:maps\.app\.goo\.gl|goo\.gl\/maps)/i.test(value)) return null;
|
|
|
|
try {
|
|
const parsed = new URL(value);
|
|
const query =
|
|
parsed.searchParams.get("q") ??
|
|
parsed.searchParams.get("query") ??
|
|
parsed.searchParams.get("ll");
|
|
if (query && query.trim()) return query.trim();
|
|
} catch {
|
|
// ไม่ใช่ URL เต็ม — ลองใช้ regex ด้านล่างต่อ
|
|
}
|
|
|
|
const at = value.match(/@(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)/);
|
|
if (at) return `${at[1]},${at[2]}`;
|
|
|
|
const place = value.match(/\/place\/(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)/);
|
|
if (place) return `${place[1]},${place[2]}`;
|
|
|
|
return null;
|
|
}
|
|
|
|
/** คำค้นจากพิกัดในหลังบ้าน (null ถ้ายังไม่กรอก) */
|
|
export function coordinatesQuery(
|
|
cinema: Pick<Cinema, "coordinates">,
|
|
): string | null {
|
|
const coords = cinema.coordinates;
|
|
if (!coords) return null;
|
|
const { latitude, longitude } = coords;
|
|
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
|
|
// 0,0 คือค่าเริ่มต้นที่ยังไม่ได้กรอกจริง
|
|
if (latitude === 0 && longitude === 0) return null;
|
|
return `${latitude},${longitude}`;
|
|
}
|
|
|
|
/** URL ฝังแผนที่ หรือ null เมื่อไม่มีข้อมูลตำแหน่งเลย */
|
|
export function mapEmbedUrl(
|
|
cinema: Cinema,
|
|
locale: Locale = "th",
|
|
): string | null {
|
|
const query = mapQueryFromUrl(cinema.map_url) ?? coordinatesQuery(cinema);
|
|
if (!query) return null;
|
|
return `https://maps.google.com/maps?q=${encodeURIComponent(query)}&z=16&hl=${locale}&output=embed`;
|
|
}
|
|
|
|
/** ลิงก์เปิดใน Google Maps (ให้ผู้ใช้กดดูเต็มจอ) */
|
|
export function mapOpenUrl(cinema: Cinema): string | null {
|
|
const query = mapQueryFromUrl(cinema.map_url) ?? coordinatesQuery(cinema);
|
|
if (!query) return null;
|
|
return `https://maps.google.com/?q=${encodeURIComponent(query)}`;
|
|
}
|