Mantieni tutto organizzato con le raccolte Salva e classifica i contenuti in base alle tue preferenze.
Per caricare il codice JavaScript per l'API Maps JavaScript, includi nella pagina uno script di caricamento bootstrap del seguente tipo:
<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 the version to use (weekly, beta, alpha, etc.).// Add other bootstrap parameters as needed, using camel case.}); </script>
L'API Maps JavaScript è composta da librerie che non vengono caricate finché non le richiedi specificamente. La suddivisione dei componenti in librerie consente all'API di caricarsi (e analizzarsi) rapidamente. Devi sostenere solo il sovraccarico aggiuntivo del caricamento e dell'analisi delle librerie in base alle tue esigenze.
Carica librerie aggiuntive in fase di esecuzione utilizzando l'operatore await per chiamare importLibrary() da una funzione async. Ad esempio:
Il seguente esempio di codice mostra il caricamento sia delle librerie Map che AdvancedMarkerElement:
TypeScript
// Initialize and add the mapletmap;asyncfunctioninitMap():Promise<void>{// The location of Uluruconstposition={lat:-25.344,lng:131.031};// Request needed libraries.//@ts-ignoreconst{Map}=awaitgoogle.maps.importLibrary("maps")asgoogle.maps.MapsLibrary;const{AdvancedMarkerElement}=awaitgoogle.maps.importLibrary("marker")asgoogle.maps.MarkerLibrary;// The map, centered at Ulurumap=newMap(document.getElementById('map')asHTMLElement,{zoom:4,center:position,mapId:'DEMO_MAP_ID',});// The marker, positioned at Uluruconstmarker=newAdvancedMarkerElement({map:map,position:position,title:'Uluru'});}initMap();
// Initialize and add the mapletmap;asyncfunctioninitMap(){// The location of Uluruconstposition={lat:-25.344,lng:131.031};// Request needed libraries.//@ts-ignoreconst{Map}=awaitgoogle.maps.importLibrary("maps");const{AdvancedMarkerElement}=awaitgoogle.maps.importLibrary("marker");// The map, centered at Ulurumap=newMap(document.getElementById("map"),{zoom:4,center:position,mapId:"DEMO_MAP_ID",});// The marker, positioned at Uluruconstmarker=newAdvancedMarkerElement({map:map,position:position,title:"Uluru",});}initMap();
La seguente richiesta di bootstrap illustra come aggiungere una richiesta per la libreria google.maps.geometry dell'API Maps JavaScript al tag di caricamento diretto dello script:
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Mancano le informazioni di cui ho bisogno","missingTheInformationINeed","thumb-down"],["Troppo complicato/troppi passaggi","tooComplicatedTooManySteps","thumb-down"],["Obsoleti","outOfDate","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Problema relativo a esempi/codice","samplesCodeIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-08-06 UTC."],[[["\u003cp\u003eThe Maps JavaScript API loads quickly by using libraries that are imported as needed with \u003ccode\u003egoogle.maps.importLibrary()\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eYou can include your API key and specify the API version in a bootstrap loader script to initially load the API.\u003c/p\u003e\n"],["\u003cp\u003eDynamic Library Import offers a modular approach, letting you load specific libraries like \u003ccode\u003emaps\u003c/code\u003e, \u003ccode\u003eplaces\u003c/code\u003e, \u003ccode\u003emarker\u003c/code\u003e, etc., on demand.\u003c/p\u003e\n"],["\u003cp\u003eFor backward compatibility, a legacy bootstrap script tag is also available, supporting libraries such as \u003ccode\u003edrawing\u003c/code\u003e, \u003ccode\u003egeometry\u003c/code\u003e, and \u003ccode\u003eplaces\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eBoth methods allow customization: Dynamic Import uses \u003ccode\u003eimportLibrary()\u003c/code\u003e within an async function, while the legacy method uses the \u003ccode\u003elibraries\u003c/code\u003e parameter in the script tag's URL.\u003c/p\u003e\n"]]],[],null,["To load the JavaScript code for the Maps JavaScript API, you\ninclude a *bootstrap* loader script on your page, of the following form: \n\n```javascript\n\u003cscript\u003e\n (g=\u003e{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=()=\u003eh||(h=new Promise(async(f,n)=\u003e{await (a=m.createElement(\"script\"));e.set(\"libraries\",[...r]+\"\");for(k in g)e.set(k.replace(/[A-Z]/g,t=\u003e\"_\"+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=()=\u003eh=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)=\u003er.add(f)&&u().then(()=\u003ed[l](f,...n))})({\n key: \"YOUR_API_KEY\",\n v: \"weekly\",\n // Use the 'v' parameter to indicate the /maps/documentation/javascript/versions to use (weekly, beta, alpha, etc.).\n // Add other /maps/documentation/javascript/load-maps-js-api#required_parameters as needed, using camel case.\n });\n\u003c/script\u003e\n```\n\nThe\nMaps JavaScript API is made up of *libraries* that are not loaded until you\nspecifically request them. Breaking up components into libraries allows the\nAPI to load (and parse) quickly. You only incur the additional overhead of loading and parsing\nlibraries as you need them.\n\nLoad additional libraries at runtime, by using the `await` operator to call\n`importLibrary()` from within an `async` function. For example: \n\n```javascript\nconst { Map } = await google.maps.importLibrary(\"maps\");\n```\n\nThe following code example shows loading both the `Map` and `AdvancedMarkerElement` libraries: \n\nTypeScript \n\n```typescript\n// Initialize and add the map\nlet map;\nasync function initMap(): Promise\u003cvoid\u003e {\n // The location of Uluru\n const position = { lat: -25.344, lng: 131.031 };\n\n // Request needed libraries.\n //@ts-ignore\n const { Map } = await google.maps.importLibrary(\"maps\") as google.maps.MapsLibrary;\n const { AdvancedMarkerElement } = await google.maps.importLibrary(\"marker\") as google.maps.MarkerLibrary;\n\n // The map, centered at Uluru\n map = new Map(\n document.getElementById('map') as HTMLElement,\n {\n zoom: 4,\n center: position,\n mapId: 'DEMO_MAP_ID',\n }\n );\n\n // The marker, positioned at Uluru\n const marker = new AdvancedMarkerElement({\n map: map,\n position: position,\n title: 'Uluru'\n });\n}\n\ninitMap();https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/samples/add-map/index.ts#L8-L41\n```\n| **Note:** Read the [guide](/maps/documentation/javascript/using-typescript) on using TypeScript and Google Maps.\n\nJavaScript \n\n```javascript\n// Initialize and add the map\nlet map;\n\nasync function initMap() {\n // The location of Uluru\n const position = { lat: -25.344, lng: 131.031 };\n // Request needed libraries.\n //@ts-ignore\n const { Map } = await google.maps.importLibrary(\"maps\");\n const { AdvancedMarkerElement } = await google.maps.importLibrary(\"marker\");\n\n // The map, centered at Uluru\n map = new Map(document.getElementById(\"map\"), {\n zoom: 4,\n center: position,\n mapId: \"DEMO_MAP_ID\",\n });\n\n // The marker, positioned at Uluru\n const marker = new AdvancedMarkerElement({\n map: map,\n position: position,\n title: \"Uluru\",\n });\n}\n\ninitMap();https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/add-map/docs/index.js#L7-L37\n```\n\nAvailable Libraries\n\nThe following libraries are available for use with\n[dynamic library import](/maps/documentation/javascript/load-maps-js-api#dynamic-library-import) and [direct script loading tag](/maps/documentation/javascript/load-maps-js-api#use-legacy-tag):\n\n- `core` ([`google.maps.CoreLibrary`](/maps/documentation/javascript/reference/library-interfaces#CoreLibrary))\n- `maps` ([`google.maps.MapsLibrary`](/maps/documentation/javascript/reference/library-interfaces#MapsLibrary))\n- `maps3d` ([`google.maps.Maps3DLibrary`](/maps/documentation/javascript/reference/library-interfaces#Maps3DLibrary))\n- `places` ([`google.maps.PlacesLibrary`](/maps/documentation/javascript/reference/library-interfaces#PlacesLibrary))\n- `geocoding` ([`google.maps.GeocodingLibrary`](/maps/documentation/javascript/reference/library-interfaces#GeocodingLibrary))\n- `routes` ([`google.maps.RoutesLibrary`](/maps/documentation/javascript/reference/library-interfaces#RoutesLibrary))\n- `marker` ([`google.maps.MarkerLibrary`](/maps/documentation/javascript/reference/library-interfaces#MarkerLibrary))\n- `geometry` ([`google.maps.GeometryLibrary`](/maps/documentation/javascript/reference/library-interfaces#GeometryLibrary))\n- `elevation` ([`google.maps.ElevationLibrary`](/maps/documentation/javascript/reference/library-interfaces#ElevationLibrary))\n- `streetView` ([`google.maps.StreetViewLibrary`](/maps/documentation/javascript/reference/library-interfaces#StreetViewLibrary))\n- `journeySharing` ([`google.maps.JourneySharingLibrary`](/maps/documentation/javascript/reference/library-interfaces#JourneySharingLibrary))\n- `drawing` ([`google.maps.DrawingLibrary`](/maps/documentation/javascript/reference/library-interfaces#DrawingLibrary))\n- `visualization` ([`google.maps.VisualizationLibrary`](/maps/documentation/javascript/reference/library-interfaces#VisualizationLibrary))\n- `airQuality` ([`google.maps.AirQualityLibrary`](/maps/documentation/javascript/reference/library-interfaces#AirQualityLibrary))\n- `addressValidation` ([`google.maps.AddressValidationLibrary`](/maps/documentation/javascript/reference/library-interfaces#AddressValidationLibrary))\n\nThe following bootstrap request illustrates how to add a request for the\n`google.maps.geometry` library of the Maps JavaScript API, to the direct\nscript loading tag: \n\n```html\n\u003cscript async\n src=\"https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&loading=async&libraries=geometry&callback=initMap\"\u003e\n\u003c/script\u003e\n```\n\nTo request multiple libraries, separate them with a comma: \n\n```html\n\u003cscript async\n src=\"https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&loading=async&libraries=geometry,places&callback=initMap\"\u003e\n\u003c/script\u003e\n```"]]