47 lines
1.3 KiB
TypeScript
47 lines
1.3 KiB
TypeScript
/* eslint-disable @next/next/no-img-element */
|
|
import crypto from "node:crypto"
|
|
|
|
import { env } from "@/env/server"
|
|
|
|
import { StaticMapProps } from "@/types/components/maps/staticMap/staticMap"
|
|
|
|
function removeWebSafe(safeEncodedString: string) {
|
|
return safeEncodedString.replace(/-/g, "+").replace(/_/g, "/")
|
|
}
|
|
|
|
function makeWebSafe(encodedString: string) {
|
|
return encodedString.replace(/\+/g, "-").replace(/\//g, "_")
|
|
}
|
|
|
|
function decodeBase64Hash(code: string) {
|
|
return Buffer.from(code, "base64")
|
|
}
|
|
|
|
function encodeBase64Hash(key: Buffer, data: string) {
|
|
return crypto.createHmac("sha1", key).update(data).digest("base64")
|
|
}
|
|
|
|
export default function StaticMap({
|
|
city,
|
|
width,
|
|
height,
|
|
zoomLevel,
|
|
mapType,
|
|
}: StaticMapProps) {
|
|
const key = env.GOOGLE_STATIC_MAP_KEY
|
|
const secret = env.GOOGLE_STATIC_MAP_SIGNATURE_SECRET
|
|
const safeSecret = decodeBase64Hash(removeWebSafe(secret ?? ""))
|
|
|
|
const url = new URL(
|
|
`https://maps.googleapis.com/maps/api/staticmap?center=${city}&zoom=${zoomLevel}&size=${width}x${height}&maptype=${mapType}&key=${key}`
|
|
)
|
|
|
|
const hashedSignature = makeWebSafe(
|
|
encodeBase64Hash(safeSecret, url.pathname + url.search)
|
|
)
|
|
|
|
const src = url.toString() + "&signature=" + hashedSignature
|
|
|
|
return <img src={src} alt={`Map of ${city} city center`} />
|
|
}
|