Delay Loading Dynamic Map

This example uses a static map as a placeholder for a dynamic map. A click event handler on the placeholder and button triggers the loading of the Google Maps JavaScript API and replaces the static map with a dynamic map.

The example depends on @googlemaps/js-api-loader to dynamically append the Google Maps JavaScript script tag to the html. This can be installed with the following NPM install.

npm install @googlemaps/js-api-loader

Alternatively, the following script can be added to the HTML document.

<script src="https://unpkg.com/@googlemaps/js-api-loader@^1.2.0/dist/index.min.js"></script>

The full sample code is below.

TypeScript

let map: google.maps.Map;

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

// @ts-ignore google.maps.plugins
const loader = new google.maps.plugins.loader.Loader({
  apiKey: "YOUR_API_KEY",
  version: "weekly",
});

document.addEventListener("DOMContentLoaded", () => {
  const wrapper = document.getElementById("wrapper") as HTMLButtonElement;

  wrapper.style.backgroundImage = `url(${url}?center=${center.lat},${center.lng}&zoom=${zoom}&scale=2&size=${wrapper.clientWidth}x${wrapper.clientHeight}&key=YOUR_API_KEY)`;

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

    loader.load().then(() => {
      map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
        center,
        zoom,
      });
    });
  });
});

JavaScript

let map;
const center = { lat: 41.90476224706472, lng: 12.49822074385094 };
const zoom = 14;
const url = "https://maps.googleapis.com/maps/api/staticmap";
const loader = new google.maps.plugins.loader.Loader({
  apiKey: "YOUR_API_KEY",
  version: "weekly",
});
document.addEventListener("DOMContentLoaded", () => {
  const wrapper = document.getElementById("wrapper");
  wrapper.style.backgroundImage = `url(${url}?center=${center.lat},${center.lng}&zoom=${zoom}&scale=2&size=${wrapper.clientWidth}x${wrapper.clientHeight}&key=YOUR_API_KEY)`;
  wrapper.addEventListener("click", () => {
    wrapper.remove();
    loader.load().then(() => {
      map = new google.maps.Map(document.getElementById("map"), {
        center,
        zoom,
      });
    });
  });
});

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;
  background-size: cover;
}

HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Programmatically Load Google Maps JS</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <!-- Use Material Design Button CSS-->
    <link
      href="https://unpkg.com/material-components-web@6.0.0/dist/material-components-web.css"
      rel="stylesheet"
    />
    <script src="https://unpkg.com/@googlemaps/js-api-loader@^1.2.0/dist/index.min.js"></script>
    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script src="./index.js"></script>
  </head>
  <body>
    <div id="map">
      <div id="wrapper">
        <button id="load_map_button" class="mdc-button mdc-button--raised">
          Load Dynamic Map
        </button>
      </div>
    </div>
  </body>
</html>

All

<!DOCTYPE html>
<html>
  <head>
    <title>Programmatically Load Google Maps JS</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <!-- Use Material Design Button CSS-->
    <link
      href="https://unpkg.com/material-components-web@6.0.0/dist/material-components-web.css"
      rel="stylesheet"
    />
    <script src="https://unpkg.com/@googlemaps/js-api-loader@^1.2.0/dist/index.min.js"></script>
    <style type="text/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;
        background-size: cover;
      }
    </style>
    <script>
      let map;
      const center = { lat: 41.90476224706472, lng: 12.49822074385094 };
      const zoom = 14;
      const url = "https://maps.googleapis.com/maps/api/staticmap";
      const loader = new google.maps.plugins.loader.Loader({
        apiKey: "YOUR_API_KEY",
        version: "weekly",
      });
      document.addEventListener("DOMContentLoaded", () => {
        const wrapper = document.getElementById("wrapper");
        wrapper.style.backgroundImage = `url(${url}?center=${center.lat},${center.lng}&zoom=${zoom}&scale=2&size=${wrapper.clientWidth}x${wrapper.clientHeight}&key=YOUR_API_KEY)`;
        wrapper.addEventListener("click", () => {
          wrapper.remove();
          loader.load().then(() => {
            map = new google.maps.Map(document.getElementById("map"), {
              center,
              zoom,
            });
          });
        });
      });
    </script>
  </head>
  <body>
    <div id="map">
      <div id="wrapper">
        <button id="load_map_button" class="mdc-button mdc-button--raised">
          Load Dynamic Map
        </button>
      </div>
    </div>
  </body>
</html>
let map; const center = { lat: 41.90476224706472, lng: 12.49822074385094 }; const zoom = 14; const url = "https://maps.googleapis.com/maps/api/staticmap"; const loader = new google.maps.plugins.loader.Loader({ apiKey: "AIzaSyBIwzALxUPNbatRBj3Xi1Uhp0fFzwWNBkE", version: "weekly", }); document.addEventListener("DOMContentLoaded", () => { const wrapper = document.getElementById("wrapper"); wrapper.style.backgroundImage = `url(${url}?center=${center.lat},${center.lng}&zoom=${zoom}&scale=2&size=${wrapper.clientWidth}x${wrapper.clientHeight}&key=AIzaSyBIwzALxUPNbatRBj3Xi1Uhp0fFzwWNBkE)`; wrapper.addEventListener("click", () => { wrapper.remove(); loader.load().then(() => { map = new google.maps.Map(document.getElementById("map"), { center, 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; } :root { --mdc-theme-primary: #1a73e8; } #wrapper { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background-size: cover; }
<!DOCTYPE html> <html> <head> <title>Programmatically Load Google Maps JS</title> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> <!-- Use Material Design Button CSS--> <link href="https://unpkg.com/material-components-web@6.0.0/dist/material-components-web.css" rel="stylesheet" /> <script src="https://unpkg.com/@googlemaps/js-api-loader@^1.2.0/dist/index.min.js"></script> <!-- jsFiddle will insert css and js --> </head> <body> <div id="map"> <div id="wrapper"> <button id="load_map_button" class="mdc-button mdc-button--raised"> Load Dynamic Map </button> </div> </div> </body> </html>

Create a starter application from sample

A skeleton starter application using TypeScript, Webpack, and Babel can be generated from this sample using one of the methods below.

Run Locally

Node.js is required to run this sample locally. Follow these instructions to install Node.js and NPM.

npx @googlemaps/js-samples init programmatic-load-button DESTINATION_FOLDER

Run in Google Cloud Shell

Google Cloud Shell is an interactive shell environment for Google Cloud Platform that makes it easy for you to learn and experiment with GCP and manage your projects and resources from your web browser.

Run in Cloud Shell