Files
web/components/Maps/StaticMap/index.tsx
2024-11-29 09:56:25 +01:00

60 lines
1.4 KiB
TypeScript

/* eslint-disable @next/next/no-img-element */
import { env } from "@/env/server"
import { getUrlWithSignature } from "@/utils/map"
import { StaticMapProps } from "@/types/components/maps/staticMap"
function getCenter({
coordinates,
city,
country,
}: {
coordinates?: { lat: number; lng: number }
city?: string
country?: string
}): string | undefined {
switch (true) {
case !!coordinates:
return `${coordinates.lat},${coordinates.lng}`
case !!country:
return `${city}, ${country}`
default:
return city
}
}
export default function StaticMap({
city,
country,
coordinates,
width,
height,
zoomLevel = 14,
mapType = "roadmap",
altText,
mapId,
}: StaticMapProps) {
const key = env.GOOGLE_STATIC_MAP_KEY
const secret = env.GOOGLE_STATIC_MAP_SIGNATURE_SECRET
const baseUrl = "https://maps.googleapis.com/maps/api/staticmap"
const center = getCenter({ coordinates, city, country })
if (!center) {
return null
}
// Google Maps Static API only supports images smaller than 640x640px. Read: https://developers.google.com/maps/documentation/maps-static/start#Largerimagesizes
const url = new URL(
`${baseUrl}?center=${center}&zoom=${zoomLevel}&size=${width}x${height}&maptype=${mapType}&key=${key}`
)
if (mapId) {
url.searchParams.append("map_id", mapId)
}
const src = getUrlWithSignature(url, secret)
return <img src={src} alt={altText} />
}