Static Placeholder Map

This example demonstrates using a static map as a placeholder; the dynamic map does not load until the user clicks the map area.

Read the documentation.

TypeScript

import { setOptions, importLibrary } from '@googlemaps/js-api-loader';

const API_KEY = 'GOOGLE_MAPS_API_KEY';
const center = { lat: 41.90476224706472, lng: 12.49822074385094 };
const zoom = 14;
const url = 'https://maps.googleapis.com/maps/api/staticmap';

function init(): void {
    const wrapper = document.getElementById('wrapper') as HTMLButtonElement;

    // The Maps Static API limits size to 640x640.
    // We cap the requested dimensions and explicitly set the CSS background-size
    // to match so that POI icons and text render at the exact same physical scale
    // as the interactive map, rather than being stretched by background-size: cover.
    const reqWidth = Math.min(640, wrapper.clientWidth || 640);
    const reqHeight = Math.min(640, wrapper.clientHeight || 640);
    const scale = window.devicePixelRatio >= 2 ? 2 : 1;

    wrapper.style.backgroundImage = `url(${url}?center=${String(center.lat)},${String(center.lng)}&zoom=${String(zoom)}&scale=${String(scale)}&size=${String(reqWidth)}x${String(reqHeight)}&key=${API_KEY})`;
    wrapper.style.backgroundSize = `${String(reqWidth)}px ${String(reqHeight)}px`;
    wrapper.style.backgroundRepeat = 'no-repeat';
    wrapper.style.backgroundPosition = 'center';

    wrapper.addEventListener('click', () => {
        wrapper.remove();

        setOptions({
            key: API_KEY,
        });

        void importLibrary('maps').then(({ Map }) => {
            new Map(document.getElementById('map')!, {
                center,
                zoom,
                mapId: 'DEMO_MAP_ID',
            });
        });
    });
}

document.addEventListener('DOMContentLoaded', () => {
    init();
});
export {};

JavaScript

import { setOptions, importLibrary } from '@googlemaps/js-api-loader';

const API_KEY = 'GOOGLE_MAPS_API_KEY';
const center = { lat: 41.90476224706472, lng: 12.49822074385094 };
const zoom = 14;
const url = 'https://maps.googleapis.com/maps/api/staticmap';

function init() {
    const wrapper = document.getElementById('wrapper');

    // The Maps Static API limits size to 640x640.
    // We cap the requested dimensions and explicitly set the CSS background-size
    // to match so that POI icons and text render at the exact same physical scale
    // as the interactive map, rather than being stretched by background-size: cover.
    const reqWidth = Math.min(640, wrapper.clientWidth || 640);
    const reqHeight = Math.min(640, wrapper.clientHeight || 640);
    const scale = window.devicePixelRatio >= 2 ? 2 : 1;

    wrapper.style.backgroundImage = `url(${url}?center=${String(center.lat)},${String(center.lng)}&zoom=${String(zoom)}&scale=${String(scale)}&size=${String(reqWidth)}x${String(reqHeight)}&key=${API_KEY})`;
    wrapper.style.backgroundSize = `${String(reqWidth)}px ${String(reqHeight)}px`;
    wrapper.style.backgroundRepeat = 'no-repeat';
    wrapper.style.backgroundPosition = 'center';

    wrapper.addEventListener('click', () => {
        wrapper.remove();

        setOptions({
            key: API_KEY,
        });

        void importLibrary('maps').then(({ Map }) => {
            new Map(document.getElementById('map'), {
                center,
                zoom,
                mapId: 'DEMO_MAP_ID',
            });
        });
    });
}

document.addEventListener('DOMContentLoaded', () => {
    init();
});

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

:root {
    --mdc-theme-primary: #1a73e8;
}

#wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

HTML

<html>
    <head>
        <title>Programmatically Load Google Maps JS</title>

        <!-- Use Material Design Button CSS-->
        <link
            href="https://unpkg.com/material-components-web@6.0.0/dist/material-components-web.css"
            rel="stylesheet" />

        <link rel="stylesheet" type="text/css" href="./style.css" />
        <script type="module" src="./index.js"></script>
    </head>
    <body>
        <div id="map">
            <div id="wrapper">
                <button
                    id="load_map_button"
                    class="mdc-button mdc-button--raised">
                    Click anywhere to load the dynamic map...
                </button>
            </div>
        </div>
    </body>
</html>

Clone Sample

Git and Node.js are required to run this sample locally. Follow these instructions to install Node.js and NPM. You will also need a Google Maps API key.

The following commands clone the repository, install dependencies, and copy the environment file.

  git clone https://github.com/googlemaps-samples/js-api-samples.git
  cd js-api-samples
  npm i
  cp .env.template .env

Once you copy the environment file, make sure to open the .env file and replace <Insert your own development API key here> with your actual API key before starting the sample.

In the sample code, GOOGLE_MAPS_API_KEY is a placeholder. When you run the sample, the API key from your .env file replaces it. In your own app, read the key only from an environment variable, with no literal key as a fallback value in source code.

  cd samples/programmatic-load-button
  npm start