Add a Google Map to a Web Page

You can add a Google map to a web page using HTML, CSS, and JavaScript code. This page shows how to add a map to a web page in two ways: by using the gmp-mapcustom HTML element, and by using adivelement.

Overview

To load a map, your web page must do the following things:

  • 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.
  • Add the map to the HTML page, and add the needed CSS styles.
  • Load themapslibrary and initialize the map.

Add a map using agmp-mapelement

Thegmp-mapelement is a custom HTML element created using web components. To add a map to a web page using agmp-mapelement, take the following steps.

  1. On the HTML page, add ascriptelement containing the bootstrap configured with your API key and any other options. In the following example bootstrap, thecallbackparameter has been omitted, as it is not needed.

    <script
    src= "https://maps.googleapis /maps/api/js?key=YOUR_API_KEY&loading=async&libraries=maps&v=beta "defer>
    </script>
    
  2. On the HTML page, add agmp-mapelement. Specify latitude and longitude coordinates forcenter,and a zoom value forzoom.In this example the heightstyle attribute is also specified.

    <gmp-map
    center= "37.4220656,-122.0840897"
    zoom= "10"
    map-id= "DEMO_MAP_ID"
    style= "height: 400px"
    ></gmp-map>

Complete example code

<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 /maps/documentation/javascript/load-maps-js-api
for more information.
-->
<script
src= "https://maps.googleapis /maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&libraries=maps&v=beta"
defer
></script>
</body>
</html>

Add a map using adivelement and JavaScript

Thedivelement is still supported for loading maps. To add a map to a web page using adivelement, take the following steps.

  1. On the HTML page, add ascriptelement containing the bootstrap loader configured with your API key and any other options. Alternatively, add the bootstrap loader code directly to a TypeScript or JavaScript file, minus the scripttags.

    <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 /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 theversionto use (weekly, beta, Alpha, etc.).
    // Add otherbootstrap parametersas needed, using camel case.
    });
    </script>
    
  2. On the HTML page, add adivelement to contain the map.

    <div id= "map" ></div>
    
  3. In the CSS, set the map height to 100%.

    #map {
    height: 100%;
    }
    
  4. In the JavaScript file, create a function to load themapslibrary and initialize the map. Specify latitude and longitude coordinates forcenter,and the zoom level to use forzoom.

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();

Complete example code

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();

CSS

/*
* 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;
}

HTML

<html>
<head>
<title>Simple Map</title>

<link rel= "stylesheet" type= "text/css" href= "./style.css" />
<script type= "module" src= "./index.js" ></script>
</head>
<body>
<div id= "map" ></div>

<!-- prettier-ignore -->
<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 /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: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly" });</script>
</body>
</html>

Try Sample