// Place names to coordinates with Photon (photon.komoot.io), OpenStreetMap // data under the ODbL. Not Nominatim: its usage policy forbids the public API // being offered through or generated by AI coding tools, which is exactly how // Map's place names arrive. Photon asks for fair use; we keep to one request // a second (see lookups.ts), identify ourselves and cache every answer. import { z } from "zod"; export const locatedSchema = z.object({ lat: z.number().min(-90).max(90), lng: z.number().min(-180).max(180) }); export type Located = z.infer; const API = "https://photon.komoot.io/api/"; /** The request for `name`, nudged toward `near` (the places already on the map) when given. */ export function geocodeUrl(name: string, near: Located | null): string { const params = new URLSearchParams({ q: name, limit: "1" }); if (near !== null) { params.set("lat", near.lat.toFixed(3)); params.set("lon", near.lng.toFixed(3)); // A regional nudge: it breaks ties between same-named places without // overriding a clearly named one far away. params.set("zoom", "8"); params.set("location_bias_scale", "0.3"); } return `${API}?${params}`; } const photonResponse = z.object({ features: z .array(z.object({ geometry: z.object({ coordinates: z.tuple([z.number(), z.number()]).rest(z.number()) }) })) .min(1), }); /** The first feature's position in a Photon GeoJSON response, or null. */ export function pickLocation(response: unknown): Located | null { const parsed = photonResponse.safeParse(response); if (!parsed.success) return null; const [lng, lat] = parsed.data.features[0].geometry.coordinates; return Math.abs(lat) > 90 || Math.abs(lng) > 180 ? null : { lat, lng }; }