Using a Map Id

Sample code for Google Maps Platform JavaScript API author(s): Justin Poehnelt

by David Iglesias

HTML

<!doctype html>
<html>

  <head>
    <title>Using a Map Id</title>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&loading=async" defer></script>
  </head>

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

</html>

CSS

/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
/* 
 * 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;
}

JavaScript

// Set up a promise that resolves when initMap is called.
let _gmapsLoaded = new Promise(function(resolve, reject) {
  window.initMap = resolve;
});

// 10s timeout
let _gmapsTimeout = new Promise(function(resolve, reject) {
  // Optional...
  setTimeout(function() {
    reject(new Error('gMaps load took too long!'));
  }, 10000);
});

// A promise that fullfills when initMap is called, or fails after 10s
let _gmapsInitialized = Promise.race([_gmapsLoaded, _gmapsTimeout]);

// Do things with google.maps...
function renderMap() {
  new google.maps.Map(document.getElementById("map"), {
    mapId: "8e0a97af9386fef",
    center: {
      lat: 48.85,
      lng: 2.35
    },
    zoom: 12,
  });
}

// Call renderMap when _gmapsInitialized fulfills, or throw an error.
(async function callFnAfterPromise(fn, p) {
	await p;
  fn.call();
}(renderMap, _gmapsInitialized));