How the v2.x functional API works
mainIn v2.x, the API is composed of two primary standalone functions:
setOptions(options: APIOptions): Used to configure the API loader (e.g., setting the API key and version).importLibrary(library: string): Used to load specific libraries (e.g.,'maps','places'). This function returns a Promise that resolves to the requested library object and also populates the globalgoogle.mapsnamespace.
This approach aligns with the recommended way to load the Google Maps JavaScript API by loading libraries only when they are needed.
import { setOptions, importLibrary } from "@googlemaps/js-api-loader";
setOptions({
key: "YOUR_API_KEY",
v: "weekly",
});
try {
const { Map } = await importLibrary("maps");
const map = new Map(document.getElementById("map"), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
});
} catch (e) {
// handle error
}