<iframe src="https://maps-docs-team.web.app/samples/map-simple/dist/" allow="fullscreen; "></iframe>

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, and then programmatically
access the map instance.

- [Add a map using a `gmp-map` element](https://developers.google.com/maps/documentation/javascript/add-google-map.md.txt#gmp-map-element)
- [Add a map using a `div` element and JavaScript](https://developers.google.com/maps/documentation/javascript/add-google-map.md.txt#div-element)
- [Set and get properties on the map instance](https://developers.google.com/maps/documentation/javascript/add-google-map.md.txt#map-instance)

## Overview

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

- [Load the Maps JavaScript API](https://developers.google.com/maps/documentation/javascript/load-maps-js-api.md.txt) using a bootstrap loader. This is where your API key is passed. It 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 the `maps` library and initialize the map.

## Add a map using a `gmp-map` element

The `gmp-map` element is the preferred way to add a Google map to a web page.
It is a custom HTML element created using web components. To add a map to a web
page using a `gmp-map` element, take the following steps.

1. Add a `script` element containing the bootstrap to an HTML page, or add it
   to a JavaScript or TypeScript source file without the `script` element.
   Configure the bootstrap with your API key and any other options. You can choose
   either dynamic library import or direct script loading. This example shows
   adding the dynamic script loading bootstrap to an HTML page:

   ```javascript
   <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",
       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>
   ```

   [Learn more about loading the Google Maps JavaScript API](https://developers.google.com/maps/documentation/javascript/load-maps-js-api.md.txt)
2. On the HTML page, add a `gmp-map` element. Specify latitude and longitude
   coordinates for `center` (required), a zoom value for `zoom` (required),
   and a `map-id` if needed (it is required for some features like Advanced
   Markers).


```html
<gmp-map center="-34.397,150.644" zoom="8" map-id="DEMO_MAP_ID">
</gmp-map>
```

<br />

### Complete example code


### TypeScript

```typescript
async function init(): Promise<void> {
    // Import the needed libraries.
    await google.maps.importLibrary('maps');

    // Access the map.
    const mapElement = document.querySelector('gmp-map')!;
    // Access the underlying map object.
    const innerMap = mapElement.innerMap;

    console.log({ mapElement, innerMap });
}

void init();
```

### JavaScript

```javascript
async function init() {
    // Import the needed libraries.
    await google.maps.importLibrary('maps');

    // Access the map.
    const mapElement = document.querySelector('gmp-map');
    // Access the underlying map object.
    const innerMap = mapElement.innerMap;

    console.log({ mapElement, innerMap });
}

void init();
```

### CSS

```css
/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
    height: 100%;
    margin: 0;
    padding: 0;
}
```

### HTML

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

        <link rel="stylesheet" type="text/css" href="./style.css" />
        <script type="module" src="./index.js"></script>
        <script>
            // prettier-ignore
            (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: "GOOGLE_MAPS_API_KEY"
            });
        </script>
    </head>

    <body>
        <gmp-map center="-34.397,150.644" zoom="8" map-id="DEMO_MAP_ID">
        </gmp-map>
    </body>
</html>
```

### Try Sample

[JSFiddle.net](https://jsfiddle.net/gh/get/library/pure/googlemaps-samples/js-api-samples/tree/main/dist/samples/map-simple/jsfiddle)

<br />

> [!NOTE]
> **Note on internal performance optimization:**
>
>
> To improve page load speeds, the Maps JavaScript API may internally defer loading interactive
> content until the element or container approaches the viewport. These internal optimizations
> are subject to change at any time, without notice. They are designed as a performance
> enhancement, and shouldn't be used as a mechanism for managing billing. To ensure billing is not
> incurred until an element is visible, defer its creation in your application code.

## Add a map using a `div` element and JavaScript

> [!NOTE]
> **Note:** While this approach remains fully supported and is preferred by some developers, we recommend considering the declarative `gmp-map` web component for new projects and modern integrations.

To add a map to a web page using a `div` element, take the following steps.

1. Add a `script` element containing the bootstrap to an HTML page, or add it
   to a JavaScript or TypeScript source file without the `script` element.
   Configure the bootstrap with your API key and any other options. You can choose
   either dynamic library import or direct script loading. This example shows
   adding the dynamic bootstrap to an HTML page:

   ```javascript
   <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",
       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>
   ```

   [Learn more about loading the Google Maps JavaScript API](https://developers.google.com/maps/documentation/javascript/load-maps-js-api.md.txt)
2. On the HTML page, add a `div` element to contain the map.

   ```javascript
   <div id="map"></div>
   ```
3. In the CSS, set the height of `html`, `body`, and `#map` to `100%`. The CSS
   `height` property is required for the map to be visible because empty `div`
   elements default to `0` height. Since percentage-based heights cascade down
   from parent elements in strict mode, setting `height: 100%` on `html` and
   `body` as well as `#map` ensures an unbroken chain of height inheritance from
   the viewport down to the map container across all browsers.

   ```javascript
   html,
   body,
   #map {
     height: 100%;
     margin: 0;
     padding: 0;
   }
   ```
4. In the JS or TS file, create a function to load the `maps` library and
   initialize the map. Specify latitude and longitude coordinates for `center`, and
   the zoom level to use for `zoom`. If needed, add a map ID using the `mapId`
   property. Since the map will default to raster, request a vector map by
   specifying the "VECTOR" map option; the vector map type is recommended for the
   best user experience, as it provides improved visual fidelity as well as the
   ability to control tilt and heading on the map.


   ### TypeScript

   ```typescript
   let map: google.maps.Map;
   async function init(): Promise<void> {
       // Import the needed libraries
       const { Map } = await google.maps.importLibrary('maps');

       // Create a new map from the div with id="map".
       map = new Map(document.getElementById('map')!, {
           center: { lat: -34.397, lng: 150.644 },
           zoom: 8,
           renderingType: 'VECTOR',
       });

       console.log(map);
   }

   void init();
   ```

   ### JavaScript

   ```javascript
   let map;
   async function init() {
       // Import the needed libraries
       const { Map } = await google.maps.importLibrary('maps');

       // Create a new map from the div with id="map".
       map = new Map(document.getElementById('map'), {
           center: { lat: -34.397, lng: 150.644 },
           zoom: 8,
           renderingType: 'VECTOR',
       });

       console.log(map);
   }

   void init();
   ```

   <br />

#### See the complete example source code

### TypeScript

```typescript
let map: google.maps.Map;
async function init(): Promise<void> {
    // Import the needed libraries
    const { Map } = await google.maps.importLibrary('maps');

    // Create a new map from the div with id="map".
    map = new Map(document.getElementById('map')!, {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 8,
        renderingType: 'VECTOR',
    });

    console.log(map);
}

void init();
```

### JavaScript

```javascript
let map;
async function init() {
    // Import the needed libraries
    const { Map } = await google.maps.importLibrary('maps');

    // Create a new map from the div with id="map".
    map = new Map(document.getElementById('map'), {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 8,
        renderingType: 'VECTOR',
    });

    console.log(map);
}

void init();
```

### CSS

```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
<html>
    <head>
        <title>Simple Map</title>

        <link rel="stylesheet" type="text/css" href="./style.css" />
        <script type="module" src="./index.js"></script>

        <script>
            // prettier-ignore
            (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: "GOOGLE_MAPS_API_KEY" 
            });
        </script>
    </head>

    <body>
        <div id="map"></div>
    </body>
</html>
```

### Try Sample

[JSFiddle.net](https://jsfiddle.net/gh/get/library/pure/googlemaps-samples/js-api-samples/tree/main/dist/samples/map-simple-js/jsfiddle)

> [!NOTE]
> **Note on internal performance optimization:**
>
>
> To improve page load speeds, the Maps JavaScript API may internally defer loading interactive
> content until the element or container approaches the viewport. These internal optimizations
> are subject to change at any time, without notice. They are designed as a performance
> enhancement, and shouldn't be used as a mechanism for managing billing. To ensure billing is not
> incurred until an element is visible, defer its creation in your application code.

## Set and get properties on the map instance

To interact with the map instance, select the containing element. The code to do
this will vary depending on whether you used the `gmp-map` element or a `div`
element.

### Get a map instance from a `gmp-map` element

To get the map instance when using a `gmp-map` element, use
`document.querySelector` to retrieve a [`mapElement`](https://developers.google.com/maps/documentation/javascript/reference/map.md.txt#MapElement)
instance, as shown here.

```javascript
const mapElement = document.querySelector('gmp-map') as google.maps.MapElement;
```

Then set properties on the `mapElement` instance:

```javascript
mapElement.zoom = 8;
```

The `MapElement` class uses the `Map` class internally; access the `Map` class
using the `MapElement.innerMap` property, as shown here:

```javascript
mapElement.innerMap.setOptions({
    mapTypeControl: false,
});
```

### Get a map instance from a `div` element

When using a `div` element, get the map instance and set options at
initialization time:

```javascript
map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
    mapTypeControl: false,
});
```

After initialization, set options on the `map` instance as shown here:

```javascript
map.setOptions({
    zoom: 8,
});
```