Dynamic Library Import API

The Dynamic Library Import API is a new way to load the Maps JavaScript API, and all of the libraries that go with it. The ability to dynamically load libraries at runtime frees you from worrying about cross-component dependencies, and allows promise-based loading of libraries. It also lets you avoid the use of long namespaces when using the Maps JavaScript API (long namespaces are still populated and can still be used).

Use Dynamic Library Import

To use the Dynamic Library Import API, add a script tag for the inline bootstrap loader to your HTML page, and runtime code to call importLibrary() (you can also use the simple script loader to do this; in this case your application code must wait for the callback before using importLibrary). Copy the following code, adding your API key, and any bootstrap parameters your application needs:

<script>(g=>{var h,b,k,n="The Google Maps JavaScript API",c="google",l="importLibrary",p="__ib__",q=document,a=window;a=a[c]||(a[c]={});var d=a.maps||(a.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,m)=>{await (b=q.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+p);b.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[p]=f;b.onerror=()=>h=m(Error(n+" could not load."));q.head.append(b)}));d[l]?console.warn(n+" only loads once. Ignoring:",g):d[l]=(f,...m)=>r.add(f)&&u().then(()=>d[l](f,...m))})({
  key: "YOUR_API_KEY_HERE",
  v: "beta",
  // Add other bootstrap parameters as needed, using camel case.
});
</script>

To load libraries at runtime, use the await operator to call importLibrary() from within an async function, as shown here:

let map;

async function initMap() {
    // Create the map.
    const { Map, InfoWindow } = await google.maps.importLibrary("maps");
    map = new Map(document.getElementById("map"),{
        center: { lat: 37.4239163, lng: -122.0947209 },
        zoom: 14,
        mapId: 'DEMO_MAP_ID',
    });

    // Add an info window.
    const infoWindow = new InfoWindow({
        ariaLabel: "Googleplex",
    });

    // Add a marker.
    const {AdvancedMarkerView} = await google.maps.importLibrary("marker");
    const markerView = new AdvancedMarkerView({
        map,
        position: { lat: 37.4239163, lng: -122.0947209 },
        title: 'Googleplex, Mountain View CA'
    });

    markerView.addListener('click', () => {
        infoWindow.close();
        infoWindow.setContent('<b>Googleplex</b>, Mountain View CA');
        infoWindow.open(markerView.map, markerView);
    });
}

initMap();

Required parameters

  • key: Your API key. The Maps JavaScript API will not load unless a valid API key is specified.

  • v: "beta" For preview, you must specify the beta channel.

Optional parameters

  • libraries: A comma-separated list of additional Maps JavaScript API libraries to load. Specifying a fixed set of libraries is not generally recommended, but is available for developers who wish to finely tune the caching behavior on their website. It should be noted though that this could cause slower loading if a library is needed that is not specified.

  • language: The language to use. This affects the names of controls, copyright notices, driving directions, and control labels, and the responses to service requests. See the list of supported languages.

  • region: The region code to use. This alters the map's behavior based on a given country or territory.

  • solutionChannel: Google Maps Platform provides many types of sample code to help you get up and running quickly. To track adoption of our more complex code samples and improve solution quality, Google includes the solution_channel query parameter in API calls in our sample code.

  • authReferrerPolicy: Maps JS customers can configure HTTP Referrer Restrictions in the Cloud Console to limit which URLs are allowed to use a particular API Key. By default, these restrictions can be configured to allow only certain paths to use an API Key. If any URL on the same domain or origin may use the API Key, you can set authReferrerPolicy: "origin" to limit the amount of data sent when authorizing requests from the Maps JavaScript API. When this parameter is specified and HTTP Referrer Restrictions are enabled on Cloud Console, Maps JavaScript API will only be able to load if there is an HTTP Referrer Restriction that matches the current website's domain without a path specified.