This guide shows you how to load the Maps JavaScript API. There are three ways to do this:
- Use Dynamic Library Import (Recommended)
- Use the NPM js-api-loader package
- Use the legacy script loading tag
Use Dynamic Library Import
Load the Maps JavaScript API by adding the inline bootstrap loader to your application code, as shown in the following snippet:
<script> (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.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."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({ key: "YOUR_API_KEY_HERE", v: "weekly", // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.). // Add other bootstrap parameters as needed, using camel case. }); </script>
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, as shown in the following code example:
TypeScript
let map: google.maps.Map; async function initMap(): Promise<void> { 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, }); } initMap();
JavaScript
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();
Required parameters
key
: Your API key. The Maps JavaScript API will not load unless a valid API key is specified.
Optional parameters
v
: The version of the Maps JavaScript API to load.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.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 thesolutionChannel
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 setauthReferrerPolicy: "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.
Use the NPM js-api-loader package
The @googlemaps/js-api-loader package is available, for loading via 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.
Use the legacy script loading tag
The legacy script loading tag is still supported. This section has been provided to support integrations using the legacy script loading tag. Google encourages migrating to the Dynamic Library Loading API.
Add a script tag
To load the Maps JavaScript API inline in an HTML file, add a
script
tag as shown below.
<script async
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
Legacy 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
&callback=FUNCTION_NAME
&v=VERSION
&libraries="LIBRARIES"
&language="LANGUAGE"
®ion="REGION"
&solution_channel="SOLUTION_IDENTIFIER"
&auth_referrer_policy="AUTH_REFERRER_POLICY"
The URL in the following example script
tag loads the Maps JavaScript API:
<script async
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
Required parameters (legacy)
The following parameters are required when loading the Maps JavaScript API.
key
: Your API key. The Maps JavaScript API will not load unless a valid API key is specified.callback
: The name of a global function to be called once the Maps JavaScript API loads completely.
Optional parameters (legacy)
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
v
: The version of the Maps JavaScript API to use.libraries
: A comma-separated list of additional Maps JavaScript API libraries to load.language
: The language to use. This affects the names of controls, copyright notices, driving directions, and control labels, as well as 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.solution_channel
: 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 thesolution_channel
query parameter in API calls in our sample code.auth_referrer_policy
: 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 setauth_referrer_policy=origin
to limit the amount of data sent when authorizing requests from the Maps JavaScript API. This is available starting in version 3.46. 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.
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 legacy script loading tag with the inline bootstrap loader tag.
Before
<script async
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
After
<script> (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.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."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({ key: "YOUR_API_KEY_HERE", v: "weekly", // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.). // Add other bootstrap parameters as needed, using camel case. }); </script>
Next, update your application code:
- Change your
initMap()
function to be asynchronous. - Call
importLibrary()
to load and access the libraries you need.
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();