This is how I did it. I don't know how correct is it but it works for me. Let me know if this helps.
import { AppleMapToken } from "@/types/global";
const APPLE_MAPKIT_JS_TOKEN = process.env.APPLE_MAPKIT_JS_TOKEN!;
async function getToken(): Promise<AppleMapToken> {
if (global.AppleMapToken && global.AppleMapToken.expiresAt > Date.now()) {
return global.AppleMapToken;
}
const token = await fetchAppleMapsToken();
return token;
}
async function fetchAppleMapsToken(): Promise<AppleMapToken> {
const response = await fetch("https://maps-api.apple.com/v1/token", {
headers: {
Authorization: `Bearer ${APPLE_MAPKIT_JS_TOKEN}`,
"Content-Type": "application/json",
},
});
if (!response.ok) {
throw new Error("Failed to fetch Apple Maps token");
}
const data = (await response.json()) as AppleMapToken;
global.AppleMapToken = {
accessToken: data.accessToken,
expiresInSeconds: data.expiresInSeconds,
expiresAt: Date.now() + data.expiresInSeconds * 1000,
};
return global.AppleMapToken;
}
export async function getNearbyPois(lat: string, lng: string) {
const limit = 5;
const offset = 0;
const radius = 10000;
const mkjsVersion = "5.78.112";
const url = `https://api.apple-mapkit.com/v1/nearbyPoi?center=${lat}%2C${lng}&radius=${radius}&lang=en&limit=${limit}&offset=${offset}&mkjsVersion=${mkjsVersion}`;
const token = await getToken();
try {
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${token.accessToken}`,
"Content-Type": "application/json",
},
});
if (!response.ok) {
throw new Error("Failed to fetch POIs from Apple Maps API");
}
const data = await response.json();
return data.results;
} catch (error) {
console.error("Error fetching POIs:", error);
return [];
}
}