in genkit/postcard-generator/libs/maps/maps.ts [77:127]
export async function renderMap(
start: string,
end: string,
stops?: string[],
): Promise<string> {
// Obtain polyline for route between two points
let polyline = await route(start, end, stops);
// Maps API cannot draw a polyline greater than a certain size, if that happens simplify it
if (polyline.length > maxPolylineSize) {
const points = polylineToPoints(polyline);
// We don't know the precision ahead of time, so iterate until we find it
for (let i = 0.05; i <= 2; i += 0.05) {
const s = simplify(points, i, false);
// If we have fewer than 3000 points attempt an encoding
if (s.length < 3000) {
polyline = pointsToPolyline(s);
if (polyline.length <= maxPolylineSize) {
break;
}
}
}
// If we got this far then we cannot draw a polyline, even after simplification - error out
if (polyline.length > maxPolylineSize) {
throw new Error("Cannot render map between these two points");
}
}
// Construct Google Maps API request
const mapURL = new URL("https://maps.googleapis.com/maps/api/staticmap");
mapURL.searchParams.set("size", "640x640");
mapURL.searchParams.set("path", `enc:${polyline}`);
mapURL.searchParams.set("key", GOOGLE_MAPS_API_KEY!);
// Render a static image from the polyline
try {
const response = await fetch(mapURL);
if (response.status != 200) {
throw new Error(
`Error fetching map image. Status code: ${response.status}`,
);
}
const mapImageBuffer = await response.arrayBuffer();
// Convert the buffer to a data URL
return Buffer.from(mapImageBuffer).toString("base64");
} catch (error) {
console.error("Error fetching map image:", error);
throw error;
}
}