Load the Maps JavaScript API Stay organized with collections Save and categorize content based on your preferences.
This guide shows you how to load the Maps JavaScript API. Thereare 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, ratherthan all at once at load time. It also protects your page from loading theMaps JavaScript API multiple times.
Load the Maps JavaScript API by adding the inline bootstraploader to your application code, as shown in the following snippet:
<script>(g=>{varh,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});vard=b.maps||(b.maps={}),r=newSet,e=newURLSearchParams,u=()=>h||(h=newPromise(async(f,n)=>{await(a=m.createElement("script"));e.set("libraries",[...r]+"");for(king)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",v:"weekly",// Use the 'v' parameter to indicate theversion to use (weekly, beta, alpha, etc.).// Add otherbootstrap 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 theawait
operator to callimportLibrary()
from within anasync
function. Declaring variables for the needed classes letsyou skip using a qualified path (e.g.google.maps.Map
), as shown in thefollowing code example:
letmap;asyncfunctioninitMap(){const{Map}=awaitgoogle.maps.importLibrary("maps");map=newMap(document.getElementById("map"),{center:{lat:-34.397,lng:150.644},zoom:8,});}initMap();
Your function can also load libraries without declaring a variablefor the needed classes, which is especially useful if you added a map using thegmp-map
element. Without the variable you must use qualified paths, forexamplegoogle.maps.Map
:
letmap;letcenter={lat:-34.397,lng:150.644};asyncfunctioninitMap(){awaitgoogle.maps.importLibrary("maps");awaitgoogle.maps.importLibrary("marker");map=newgoogle.maps.Map(document.getElementById("map"),{center,zoom:8,mapId:"DEMO_MAP_ID",});addMarker();}asyncfunctionaddMarker(){constmarker=newgoogle.maps.marker.AdvancedMarkerElement({map,position:center,});}initMap();
Alternatively, you can load the libraries directly in HTML as shown here:
<script>google.maps.importLibrary("maps");google.maps.importLibrary("marker");</script>
Learn how tomigrate to the Dynamic Library Loading API.
Required parameters
key
: YourAPI key.The Maps JavaScript API won't load unless a valid API key isspecified.
Optional parameters
v
: Theversion of theMaps JavaScript API to load.libraries
: An array of additional Maps JavaScript APIlibraries to load. Specifying afixed set of libraries is not generally recommended, but is available fordevelopers who want to finely tune the caching behavior on their website.language
: Thelanguage touse. This affects the names of controls, copyright notices, drivingdirections, and control labels, and the responses to service requests. See thelist of supported languages.region
: Theregioncode to use. This alters the API's behavior based on a given country orterritory.authReferrerPolicy
: Maps JS customers can configure HTTP ReferrerRestrictions in the Cloud Console to limit which URLs are allowed to use aparticular API Key. By default, these restrictions can be configured to allowonly certain paths to use an API Key. If any URL on the same domain or originmay use the API Key, you can setauthReferrerPolicy: "origin"
to limit theamount of data sent when authorizing requests from the Maps JavaScript API. Whenthis parameter is specified and HTTP Referrer Restrictions are enabled onCloud Console, Maps JavaScript API will only be able to load ifthere is anHTTP Referrer Restrictionthat matches the current website's domain without a path specified.mapIds
: An array of map IDs. Causes the configuration for the specifiedmap IDs to be preloaded. Specifying map IDs here is not required for map IDsusage, but is available for developers who want to finely tune networkperformance.channel
: SeeUsage tracking per channel.solutionChannel
: Google Maps Platform provides many types of sample codeto help you get up and running quickly. To track adoption of our more complexcode samples and improve solution quality, Google includes thesolutionChannel
query parameter in API calls in our sample code.
Use the direct script loading tag
This section shows how to use the direct script loading tag. Because the directscript loads libraries when the map loads, it can simplify maps created usingagmp-map
element by removing the need to explicitly request libraries atruntime. Since the direct script loading tag loads all requested libraries atonce when the script is loaded, performance may be impacted for someapplications. Only include the direct script loading tag once per page load.
importLibrary
once the direct script loading tag hasfinished loading.Add a script tag
To load the Maps JavaScript API inline in an HTML file, add ascript
tag as shown below.
<script async src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&loading=async&callback=initMap"></script>
Direct script loading URL Parameters
This section discusses all of the parameters you can specify in the querystring of the script loading URL when loading theMaps JavaScript API. Certain parameters are required while othersare optional. As is standard inURLs, 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"®ion="REGION"&auth_referrer_policy="AUTH_REFERRER_POLICY"&map_ids="MAP_IDS"&channel="CHANNEL"&solution_channel="SOLUTION_IDENTIFIER"
The URL in the following examplescript
tag loads theMaps JavaScript API:
<script async src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&loading=async&callback=initMap"></script>
Required parameters (direct)
The following parameters are required when loading theMaps JavaScript API.
key
: YourAPI key. TheMaps JavaScript API won't load unless a valid API key isspecified.
Optional parameters (direct)
Use these parameters to request a specific version of theMaps JavaScript API, load additional libraries, localize yourmap or specify the HTTP referrer check policy
loading
: The code loading strategy that theMaps JavaScript API can use. Set toasync
to indicate thatthe Maps JavaScript API has not been loaded synchronously andthat no JavaScript code is triggered by the script'sload
event. It ishighly recommended to set this toasync
whenever possible, for improvedperformance. (Use thecallback
parameter instead to perform actions whenthe Maps JavaScript API is available.) Available starting withversion 3.55.callback
: The name of a global function to be called once theMaps JavaScript API loads completely.v
: Theversion of theMaps JavaScript API to use.libraries
: A comma-separated list of additionalMaps JavaScript APIlibraries to load.language
: Thelanguage touse. This affects the names of controls, copyright notices, drivingdirections, and control labels, as well as the responses to servicerequests. See thelist of supported languages.region
: Theregioncode to use. This alters the API's behavior based on a given country orterritory.auth_referrer_policy
: Customers can configure HTTP Referrer Restrictionsin the Cloud Console to limit which URLs are allowed to use a particular APIKey. By default, these restrictions can be configured to allow only certainpaths to use an API Key. If any URL on the same domain or origin may use theAPI Key, you can setauth_referrer_policy=origin
to limit the amount ofdata sent when authorizing requests from the Maps JavaScript API. This isavailable starting in version 3.46. When this parameter is specified andHTTP Referrer Restrictions are enabled on Cloud Console,Maps JavaScript API will only be able to load if there is anHTTP Referrer Restriction that matches the current website's domain withouta path specified.mapIds
: A comma-separated list of map IDs. Causes the configuration forthe specified map IDs to be preloaded. Specifying map IDs here is notrequired for map IDs usage, but is available for developers who want tofinely tune network performance.channel
: SeeUsage tracking perchannel.
Note: This query parameter is for use by Google. SeeGoogle Maps Platform solutions parameterfor more information.solution_channel
: Google Maps Platform provides many types of sample codeto help you get up and running quickly. To track adoption of our more complexcode samples and improve solution quality, Google includes thesolution_channel
query parameter in API calls in our sample code.
Use the NPM js-api-loader package
The@googlemaps/js-api-loaderpackage is available, for loading using the NPM package manager. Install itusing the following command:
npminstall@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 demonstratesusage of the default Promise methodload()
.
TypeScript
constloader=newLoader({apiKey:"YOUR_API_KEY",version:"weekly",...additionalOptions,});loader.load().then(async()=>{const{Map}=awaitgoogle.maps.importLibrary("maps")asgoogle.maps.MapsLibrary;map=newMap(document.getElementById("map")asHTMLElement,{center:{lat:-34.397,lng:150.644},zoom:8,});});
JavaScript
constloader=newLoader({apiKey:"YOUR_API_KEY",version:"weekly",...additionalOptions,});loader.load().then(async()=>{const{Map}=awaitgoogle.maps.importLibrary("maps");map=newMap(document.getElementById("map"),{center:{lat:-34.397,lng:150.644},zoom:8,});});
See a sample featuring js-api-loader.
The following example shows usingloader.importLibrary()
to load libraries:
constloader=newLoader({apiKey:"YOUR_API_KEY",version:"weekly",...additionalOptions,});loader.importLibrary('maps').then(({Map})=>{newMap(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 usethe Dynamic Library Import API.
Migration steps
First, replace the direct script loading tag with the inline bootstrap loadertag.
Before
<script async src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&loading=async&libraries=maps&callback=initMap"></script>
After
<script>(g=>{varh,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});vard=b.maps||(b.maps={}),r=newSet,e=newURLSearchParams,u=()=>h||(h=newPromise(async(f,n)=>{await(a=m.createElement("script"));e.set("libraries",[...r]+"");for(king)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",v:"weekly",// Use the 'v' parameter to indicate theversion to use (weekly, beta, alpha, etc.).// Add otherbootstrap 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
letmap;functioninitMap(){map=newgoogle.maps.Map(document.getElementById("map"),{center:{lat:-34.397,lng:150.644},zoom:8,});}window.initMap=initMap;
After
letmap;// initMap is now asyncasyncfunctioninitMap(){// Request libraries when needed, not in the script tag.const{Map}=awaitgoogle.maps.importLibrary("maps");// Short namespaces can be used.map=newMap(document.getElementById("map"),{center:{lat:-34.397,lng:150.644},zoom:8,});}initMap();
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-07-18 UTC.