Files
web/components/Maps/StaticMap/index.tsx
2024-08-13 08:52:54 +02:00

52 lines
1.4 KiB
TypeScript

/* eslint-disable @next/next/no-img-element */
import crypto from "crypto"
import url from "url"
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")
}
function createRequestUrl(path: string, secret: string) {
const uri = new URL(path)
const safeSecret = decodeBase64Hash(removeWebSafe(secret))
const hashedSignature = makeWebSafe(
encodeBase64Hash(safeSecret, uri.pathname + uri.search)
)
return url.format(uri) + "&signature=" + hashedSignature
}
export default function StaticMap({
city,
width,
height,
zoomLevel,
mapType,
}: StaticMapProps) {
const key = env.GOOGLE_STATIC_MAP_KEY
const secret = env.GOOGLE_STATIC_MAP_SECRET
const url = `https://maps.googleapis.com/maps/api/staticmap?center=${city}&zoom=${zoomLevel}&size=${width}x${height}&maptype=${mapType}&key=${key}`
return (
<img
src={createRequestUrl(url, secret)}
alt={`Map of ${city} city center`}
/>
)
}