@googlemaps/js-api-loader

repository·main·Indexed 19 days ago

https://github.com/googlemaps/js-api-loader

A lightweight npm package for dynamically loading the Google Maps JavaScript API in the browser. It provides a modern, Promise-based functional interface using setOptions() for configuration and importLibrary() to load specific libraries such as maps, places, and geocoding. Version 2.1.1 moves from a class-based Loader approach to a functional API to align with recommended loading patterns.

Tokens
3.8K
Snippets
17
Records
19
Agent score
65%

What's inside @googlemaps/js-api-loader

  1. How the v2.x functional API works

    main

    In v2.x, the API is composed of two primary standalone functions:

    1. setOptions(options: APIOptions): Used to configure the API loader (e.g., setting the API key and version).
    2. 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 global google.maps namespace.

    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
    }
  2. How to use custom HTML elements (Web Components)

    main

    If you are using custom Google Maps HTML elements like <gmp-map> or <gmp-advanced-marker>, you must call importLibrary() for the required libraries (e.g., maps and marker). You do not need to await the importLibrary() call; instead, use customElements.whenDefined() to wait for the element to upgrade before interacting with it.

    import { setOptions, importLibrary } from "@googlemaps/js-api-loader";
    
    // Set the options for loading the API.
    setOptions({ key: "your-api-key-here" });
    
    // Start loading the libraries needed for custom elements.
    importLibrary("maps"); // needed for <gmp-map>
    importLibrary("marker"); // needed for <gmp-advanced-marker>
    
    // Wait for gmp-map to be upgraded and interact with it.
    await customElements.whenDefined("gmp-map");
    const map = document.querySelector("gmp-map");
  3. Run individual bundler tests for Vite

    main

    To run the integration tests specifically for Vite, navigate to the vite-test directory, install dependencies, install the local version of the @googlemaps/js-api-loader package, and run the build command. This test verifies that Vite's built-in define configuration correctly replaces process.env.NODE_ENV.

    cd vite-test
    npm install
    npm install $(npm pack --silent ../../)
    npm run build
  4. Run bundler integration tests

    main

    To verify that @googlemaps/js-api-loader works correctly with various JavaScript bundlers (Vite, Webpack, and Rollup) without additional configuration, you can run the integrated test suite. This ensures that the library's development-mode warnings (toggled via process.env.NODE_ENV) are correctly handled by the bundler's environment variable replacement mechanisms.

    ./test-all.sh
  5. Migrate from v1.x to v2.x

    main

    Version 2.x of @googlemaps/js-api-loader moves from a class-based approach (Loader) to a functional approach.

    Key Changes

    Featurev1.x (Loader class)v2.x (functions)
    Initializationnew Loader({ apiKey: '...', ... })setOptions({ key: '...', ... })
    Loading Librarieslibraries option or loader.importLibrary('maps')importLibrary('maps')
    Legacy Loadingloader.load()Removed. Use importLibrary() instead.
    API Key ParameterapiKeykey
    Version Parameterversionv

    Migration Strategy

    • Replace the Loader constructor with setOptions().
    • Replace loader.load() or loader.loadCallback() with importLibrary() calls.
    • Update configuration keys: rename apiKey to key and version to v.
  6. Install @googlemaps/js-api-loader

    main

    Install the loader using your preferred package manager. If you are using TypeScript, you should also install the Google Maps JavaScript API type definitions to ensure type safety.

    # Install the loader
    npm install --save @googlemaps/js-api-loader
    
    # or
    yarn add @googlemaps/js-api-loader
    
    # or
    pnpm add @googlemaps/js-api-loader
    
    # For TypeScript users, install types
    npm install --save-dev @types/google.maps
  7. Configure Content Security Policy (CSP) for Trusted Types

    main

    If your application enforces require-trusted-types-for 'script', you must allow the following policy names in your CSP directive to prevent the loader from being blocked:

    • @googlemaps/js-api-loader (used by this package)
    • google-maps-api-loader (used internally by the Maps API)
    • google-maps-api#html (used internally by the Maps API)
    • lit-html (used internally by the Maps API)
    Content-Security-Policy: require-trusted-types-for 'script'; trusted-types @googlemaps/js-api-loader google-maps-api-loader google-maps-api#html lit-html
  8. Basic usage of @googlemaps/js-api-loader

    main

    To use the loader, first call setOptions with your API key, then use importLibrary to load specific libraries. Once a library is loaded, its components are available via the returned promise and are also attached to the global google.maps namespace.

    import { setOptions, importLibrary } from "@googlemaps/js-api-loader";
    
    // Set the options for loading the API.
    setOptions({ key: "your-api-key-here" });
    
    // Load the needed APIs.
    const { Map } = await importLibrary("maps");
    const map = new Map(mapEl, mapOptions);
  9. Imitate v1.x behavior in v2.x

    main

    If you prefer using the global google.maps namespace instead of importing specific classes, you can still do so in v2.x. You must call importLibrary() for each required library to ensure they are loaded. You can use Promise.all() to load multiple libraries in parallel.

    Note: Specifying libraries in setOptions only preloads them; you still must call importLibrary to fully load them and resolve the promise.

    import { setOptions, importLibrary } from "@googlemaps/js-api-loader";
    
    setOptions({
      key: "YOUR_API_KEY",
      v: "weekly",
      libraries: ["places"],
    });
    
    // load all required libraries in parallel
    const librariesPromise = Promise.all([
      importLibrary("maps"),
      importLibrary("places"),
    ]);
    
    await librariesPromise;
    
    function initMap() {
      // Use the global google.maps namespace once loading is complete
      const map = new google.maps.Map(document.getElementById("map"), {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 8,
      });
    }
    
    initMap();
  10. Configure API loading with setOptions()

    main

    The setOptions(options: APIOptions): void function configures how the Google Maps JavaScript API is loaded. It should be called as early as possible in your application and only once. Subsequent calls will be ignored and a warning will be logged.

    setOptions({
      key: "YOUR_API_KEY",
      v: "version",
      language: "en",
      region: "US",
      libraries: ["places"],
      authReferrerPolicy: "strict-origin-when-cross-origin",
      mapIds: ["MAP_ID"],
      channel: "channel_name",
      solutionChannel: "solution_name"
    });
  11. Load libraries with importLibrary()

    main

    The importLibrary(library: string): Promise function loads a specific Google Maps library. The first call to this function triggers the loading of the main Google Maps JavaScript API. The promise resolves with the library object.

    // Example: loading the 'maps' library
    const { Map } = await importLibrary("maps");
  12. Reference: Available libraries for importLibrary()

    main

    The following library strings can be passed to importLibrary():

    • core
    • maps
    • maps3d
    • places
    • geocoding
    • routes
    • marker
    • geometry
    • elevation
    • streetView
    • journeySharing
    • visualization
    • airQuality
    • addressValidation
    • drawing (deprecated)