Mantieni tutto organizzato con le raccolte Salva e classifica i contenuti in base alle tue preferenze.
Puoi aggiungere una mappa di Google a una pagina web utilizzando codice HTML, CSS e JavaScript. Questa pagina mostra come aggiungere una mappa a una pagina web in due modi: utilizzando l'elemento HTML personalizzato gmp-map e utilizzando un elemento div.
Carica l'API Maps JavaScript utilizzando un bootstrap loader. È qui che viene passata la chiave API, che può essere aggiunta ai file sorgente HTML o JavaScript.
Aggiungi la mappa alla pagina HTML e aggiungi gli stili CSS necessari.
Carica la libreria maps e inizializza la mappa.
Aggiungere una mappa utilizzando un elemento gmp-map
L'elemento gmp-map è un elemento HTML personalizzato creato utilizzando i componenti web. Per aggiungere una mappa a una pagina web utilizzando un elemento gmp-map:
Nella pagina HTML, aggiungi un elemento script contenente il bootstrap configurato con la tua chiave API e qualsiasi altra opzione. Nel seguente esempio di bootstrap, il parametro callback è stato omesso perché non è necessario.
Nella pagina HTML, aggiungi un elemento gmp-map. Specifica le coordinate di latitudine e longitudine per center e un valore di zoom per zoom. In questo esempio viene specificato anche l'attributo di stile height.
<html> <head> <title>Add a Map using HTML</title> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <gmp-map center="37.4220656,-122.0840897" zoom="10" map-id="DEMO_MAP_ID" style="height: 400px" ></gmp-map> <!-- The `defer` attribute causes the script to execute after the full HTML document has been parsed. For non-blocking uses, avoiding race conditions, and consistent behavior across browsers, consider loading using Promises. See https://developers.google.com/maps/documentation/javascript/load-maps-js-api for more information. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&libraries=maps&v=beta" defer ></script> </body> </html>
Aggiungere una mappa utilizzando un elemento div e JavaScript
Per aggiungere una mappa a una pagina web utilizzando un elemento div:
Nella pagina HTML, aggiungi un elemento script contenente il caricatore bootstrap configurato con la tua chiave API e altre opzioni. In alternativa, aggiungi il codice del caricatore bootstrap direttamente a un file TypeScript o JavaScript, senza i tag script.
<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>
Nella pagina HTML, aggiungi un elemento div per contenere la mappa.
<divid="map"></div>
Nel CSS, imposta l'altezza della mappa al 100%.
#map{height:100%;}
Nel file JavaScript, crea una funzione per caricare la libreria maps e inizializzare la mappa. Specifica le coordinate di latitudine e longitudine per center e il livello di zoom da utilizzare per zoom.
/* * Always set the map height explicitly to define the size of the div element * that contains the map. */#map{height:100%;}/* * Optional: Makes the sample page fill the window. */html,body{height:100%;margin:0;padding:0;}
[[["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-12 UTC."],[[["\u003cp\u003eThis documentation explains how to embed a Google map into a webpage using HTML, CSS, and JavaScript.\u003c/p\u003e\n"],["\u003cp\u003eYou can add a map using a custom HTML element (\u003ccode\u003egmp-map\u003c/code\u003e) or a standard \u003ccode\u003ediv\u003c/code\u003e element, both requiring a Google Maps API key.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves loading the Maps JavaScript API, adding the map to your HTML, and initializing it with coordinates and zoom level using JavaScript.\u003c/p\u003e\n"],["\u003cp\u003eCode examples in HTML, CSS, and JavaScript (including TypeScript) are provided for both methods, demonstrating the implementation steps.\u003c/p\u003e\n"]]],[],null,["You can add a Google map to a web page using HTML, CSS, and JavaScript code.\nThis page shows how to add a map to a web page in two ways: by using the\n`gmp-map` custom HTML element, and by using a `div` element.\n\n- [Add a map using a `gmp-map` element](#gmp-map-element)\n- [Add a map using a `div` element and JavaScript](#div-element)\n\nOverview\n\nTo load a map, your web page must do the following things:\n\n- Load the Maps JavaScript API using a bootstrap loader. This is where your API key is passed, and can be added to either the HTML or JavaScript source files.\n- Add the map to the HTML page, and add the needed CSS styles.\n- Load the `maps` library and initialize the map.\n\nAdd a map using a `gmp-map` element\n\nThe `gmp-map` element is a custom HTML element created using web components.\nTo add a map to a web page using a `gmp-map` element, take the following steps.\n\n1. On the HTML page, add a `script` element containing the bootstrap configured\n with your API key and any other options. In the following example bootstrap,\n the `callback` parameter has been omitted, as it is not needed.\n\n\n ```html\n \u003cscript\n src=\"https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&loading=async&libraries=maps&v=beta\" defer\u003e\n \u003c/script\u003e\n ```\n\n \u003cbr /\u003e\n\n2. On the HTML page, add a `gmp-map` element. Specify latitude and longitude\n coordinates for `center`, and a zoom value for `zoom`. In this example the\n `height` style attribute is also specified.\n\n\n ```html\n \u003cgmp-map\n center=\"37.4220656,-122.0840897\"\n zoom=\"10\"\n map-id=\"DEMO_MAP_ID\"\n style=\"height: 400px\"\n \u003e\u003c/gmp-map\u003ehttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/web-components-map/docs/index.html#L17-L22\n ```\n\n \u003cbr /\u003e\n\nComplete example code\n\n\n```html\n\u003chtml\u003e\n \u003chead\u003e\n \u003ctitle\u003eAdd a Map using HTML\u003c/title\u003e\n\n \u003clink rel=\"stylesheet\" type=\"text/css\" href=\"./style.css\" /\u003e\n \u003cscript type=\"module\" src=\"./index.js\"\u003e\u003c/script\u003e\n \u003c/head\u003e\n \u003cbody\u003e\n \u003cgmp-map\n center=\"37.4220656,-122.0840897\"\n zoom=\"10\"\n map-id=\"DEMO_MAP_ID\"\n style=\"height: 400px\"\n \u003e\u003c/gmp-map\u003e\n\n \u003c!-- \n The `defer` attribute causes the script to execute after the full HTML\n document has been parsed. For non-blocking uses, avoiding race conditions,\n and consistent behavior across browsers, consider loading using Promises. See\n https://developers.google.com/maps/documentation/javascript/load-maps-js-api\n for more information.\n --\u003e\n \u003cscript\n src=\"https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&libraries=maps&v=beta\"\n defer\n \u003e\u003c/script\u003e\n \u003c/body\u003e\n\u003c/html\u003ehttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/web-components-map/docs/index.html#L8-L37\n```\n\n\u003cbr /\u003e\n\nAdd a map using a `div` element and JavaScript\n\nTo add a map to a web page using a `div` element, take the following steps.\n\n1. On the HTML page, add a `script` element containing the bootstrap loader\n configured with your API key and any other options. Alternatively, add the\n bootstrap loader code directly to a TypeScript or JavaScript file, minus the\n `script` tags.\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 ```\n2. On the HTML page, add a `div` element to contain the map.\n\n ```javascript\n \u003cdiv id=\"map\"\u003e\u003c/div\u003e\n ```\n3. In the CSS, set the map height to 100%.\n\n ```javascript\n #map {\n height: 100%;\n }\n ```\n4. In the JavaScript file, create a function to load the `maps` library and\n initialize the map. Specify latitude and longitude coordinates for `center`, and\n the zoom level to use for `zoom`.\n\n\n ```javascript\n let map;\n\n async function initMap() {\n const { Map } = await google.maps.importLibrary(\"maps\");\n\n map = new Map(document.getElementById(\"map\"), {\n center: { lat: -34.397, lng: 150.644 },\n zoom: 8,\n });\n }\n\n initMap();https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/map-simple/docs/index.js#L7-L18\n ```\n\n \u003cbr /\u003e\n\nComplete example code\n\n\nTypeScript \n\n```typescript\nlet map: google.maps.Map;\nasync function initMap(): Promise\u003cvoid\u003e {\n const { Map } = await google.maps.importLibrary(\"maps\") as google.maps.MapsLibrary;\n map = new Map(document.getElementById(\"map\") as HTMLElement, {\n center: { lat: -34.397, lng: 150.644 },\n zoom: 8,\n });\n}\n\ninitMap();https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/samples/map-simple/index.ts#L8-L17\n```\n| **Note:** Read the [guide](/maps/documentation/javascript/using-typescript) on using TypeScript and Google Maps.\n\nJavaScript \n\n```javascript\nlet map;\n\nasync function initMap() {\n const { Map } = await google.maps.importLibrary(\"maps\");\n\n map = new Map(document.getElementById(\"map\"), {\n center: { lat: -34.397, lng: 150.644 },\n zoom: 8,\n });\n}\n\ninitMap();https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/map-simple/docs/index.js#L7-L18\n```\n| **Note:** The JavaScript is compiled from the TypeScript snippet.\n\nCSS \n\n```css\n/* \n * Always set the map height explicitly to define the size of the div element\n * that contains the map. \n */\n#map {\n height: 100%;\n}\n\n/* \n * Optional: Makes the sample page fill the window. \n */\nhtml,\nbody {\n height: 100%;\n margin: 0;\n padding: 0;\n}\nhttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/map-simple/docs/style.css#L7-L24\n```\n\nHTML \n\n```html\n\u003chtml\u003e\n \u003chead\u003e\n \u003ctitle\u003eSimple Map\u003c/title\u003e\n\n \u003clink rel=\"stylesheet\" type=\"text/css\" href=\"./style.css\" /\u003e\n \u003cscript type=\"module\" src=\"./index.js\"\u003e\u003c/script\u003e\n \u003c/head\u003e\n \u003cbody\u003e\n \u003cdiv id=\"map\"\u003e\u003c/div\u003e\n\n \u003c!-- prettier-ignore --\u003e\n \u003cscript\u003e(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: \"AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg\", v: \"weekly\"});\u003c/script\u003e\n \u003c/body\u003e\n\u003c/html\u003ehttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/map-simple/docs/index.html#L8-L22\n```\n\nTry Sample \n[JSFiddle.net](https://jsfiddle.net/gh/get/library/pure/googlemaps/js-samples/tree/master/dist/samples/map-simple/jsfiddle) [Google Cloud Shell](https://ssh.cloud.google.com/cloudshell/editor?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Fgooglemaps%2Fjs-samples&cloudshell_git_branch=sample-map-simple&cloudshell_tutorial=cloud_shell_instructions.md&cloudshell_workspace=.)\n\n\u003cbr /\u003e"]]