Load the Maps JavaScript API (original) (raw)

This guide shows you how to load the Maps JavaScript API. There are three ways to do this:

Use Dynamic Library Import

Dynamic library import provides the capability to load libraries at runtime. This lets you request needed libraries at the point when you need them, rather than all at once at load time. It also protects your page from loading the Maps JavaScript API multiple times.

Load the Maps JavaScript API by adding the inline bootstrap loader to your application code, as shown in the following snippet:

You can also add the bootstrap loader code directly to your JavaScript code.

To load libraries at runtime, use the await operator to call importLibrary()from within an async function. Declaring variables for the needed classes lets you skip using a qualified path (e.g. google.maps.Map), as shown in the following code example:

let map;

async function initMap() { const { Map } = await google.maps.importLibrary("maps");

map = new Map(document.getElementById("map"), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); }

initMap();

Your function can also load libraries without declaring a variable for the needed classes, which is especially useful if you added a map using thegmp-map element. Without the variable you must use qualified paths, for example google.maps.Map:

let map; let center = { lat: -34.397, lng: 150.644 };

async function initMap() { await google.maps.importLibrary("maps"); await google.maps.importLibrary("marker");

map = new google.maps.Map(document.getElementById("map"), { center, zoom: 8, mapId: "DEMO_MAP_ID", });

addMarker(); }

async function addMarker() { const marker = new google.maps.marker.AdvancedMarkerElement({ map, position: center, }); }

initMap();

Alternatively, you can load the libraries directly in HTML as shown here:

Learn how to migrate to the Dynamic Library Loading API.

Required parameters

Optional parameters

Use the direct script loading tag

This section shows how to use the direct script loading tag. Because the direct script loads libraries when the map loads, it can simplify maps created using a gmp-map element by removing the need to explicitly request libraries at runtime. Since the direct script loading tag loads all requested libraries at once when the script is loaded, performance may be impacted for some applications. Only include the direct script loading tag once per page load.

Add a script tag

To load the Maps JavaScript API inline in an HTML file, add ascript tag as shown below.

Direct script loading URL Parameters

This section discusses all of the parameters you can specify in the query string of the script loading URL when loading the Maps JavaScript API. Certain parameters are required while others are optional. As is standard in URLs, all parameters are separated using the ampersand (&) character.

The following example URL has placeholders for all possible parameters:

https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY
&loading=async
&callback=FUNCTION_NAME
&v=VERSION
&libraries="LIBRARIES"
&language="LANGUAGE"
&region="REGION"
&auth_referrer_policy="AUTH_REFERRER_POLICY"
&map_ids="MAP_IDS"
&channel="CHANNEL"
&solution_channel="SOLUTION_IDENTIFIER"

The URL in the following example script tag loads the Maps JavaScript API:

Required parameters (direct)

The following parameters are required when loading the Maps JavaScript API.

Optional parameters (direct)

Use these parameters to request a specific version of the Maps JavaScript API, load additional libraries, localize your map or specify the HTTP referrer check policy

Use the NPM js-api-loader package

The @googlemaps/js-api-loaderpackage is available, for loading using the NPM package manager. Install it using the following command:

npm install @googlemaps/js-api-loader

This package can be imported into the application with:

import { Loader } from "@googlemaps/js-api-loader"

The loader exposes a Promise and callback interface. The following demonstrates usage of the default Promise method load().

TypeScript

const loader = new Loader({ apiKey: "YOUR_API_KEY", version: "weekly", ...additionalOptions, });

loader.load().then(async () => { const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary; map = new Map(document.getElementById("map") as HTMLElement, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); });

JavaScript

const loader = new Loader({ apiKey: "YOUR_API_KEY", version: "weekly", ...additionalOptions, });

loader.load().then(async () => { const { Map } = await google.maps.importLibrary("maps");

map = new Map(document.getElementById("map"), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); });

See a sample featuring js-api-loader.

The following example shows using loader.importLibrary() to load libraries:

const loader = new Loader({
  apiKey: "YOUR_API_KEY",
  version: "weekly",
  ...additionalOptions,
});

loader
  .importLibrary('maps')
  .then(({Map}) => {
    new Map(document.getElementById("map"), mapOptions);
  })
  .catch((e) => {
    // do something
});

Migrate to the Dynamic Library Import API

This section covers the steps required to migrate your integration to use the Dynamic Library Import API.

Migration steps

First, replace the direct script loading tag with the inline bootstrap loader tag.

Before

After

Next, update your application code:

Before

let map;

function initMap() { map = new google.maps.Map(document.getElementById("map"), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); }

window.initMap = initMap;

After

let map; // initMap is now async async function initMap() { // Request libraries when needed, not in the script tag. const { Map } = await google.maps.importLibrary("maps"); // Short namespaces can be used. map = new Map(document.getElementById("map"), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); }

initMap();