It's the 15th anniversary of Google Maps Platform - Check out the latest news and announcements

Using Closures in Event Listeners

This example creates a map with tappable markers displaying a secret message.

Read the documentation.

JavaScript

function initMap() {
  var map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: { lat: -25.363882, lng: 131.044922 }
  });

  var bounds = {
    north: -25.363882,
    south: -31.203405,
    east: 131.044922,
    west: 125.244141
  };

  // Display the area between the location southWest and northEast.
  map.fitBounds(bounds);

  // Add 5 markers to map at random locations.
  // For each of these markers, give them a title with their index, and when
  // they are clicked they should open an infowindow with text from a secret
  // message.
  var secretMessages = ["This", "is", "the", "secret", "message"];
  var lngSpan = bounds.east - bounds.west;
  var latSpan = bounds.north - bounds.south;
  for (var i = 0; i < secretMessages.length; ++i) {
    var marker = new google.maps.Marker({
      position: {
        lat: bounds.south + latSpan * Math.random(),
        lng: bounds.west + lngSpan * Math.random()
      },
      map: map
    });
    attachSecretMessage(marker, secretMessages[i]);
  }
}

// Attaches an info window to a marker with the provided message. When the
// marker is clicked, the info window will open with the secret message.
function attachSecretMessage(marker, secretMessage) {
  var infowindow = new google.maps.InfoWindow({
    content: secretMessage
  });

  marker.addListener("click", function() {
    infowindow.open(marker.get("map"), marker);
  });
}

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

<!DOCTYPE html>
<html>
  <head>
    <title>Using Closures in Event Listeners</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=&v=weekly"
      defer
    ></script>
    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script src="./app.js"></script>
  </head>
  <body>
    <div id="map"></div>
  </body>
</html>

All

<!DOCTYPE html>
<html>
  <head>
    <title>Using Closures in Event Listeners</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=&v=weekly"
      defer
    ></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;
      }
    </style>
    <script>
      (function(exports) {
        "use strict";

        function initMap() {
          var map = new google.maps.Map(document.getElementById("map"), {
            zoom: 4,
            center: {
              lat: -25.363882,
              lng: 131.044922
            }
          });
          var bounds = {
            north: -25.363882,
            south: -31.203405,
            east: 131.044922,
            west: 125.244141
          }; // Display the area between the location southWest and northEast.

          map.fitBounds(bounds); // Add 5 markers to map at random locations.
          // For each of these markers, give them a title with their index, and when
          // they are clicked they should open an infowindow with text from a secret
          // message.

          var secretMessages = ["This", "is", "the", "secret", "message"];
          var lngSpan = bounds.east - bounds.west;
          var latSpan = bounds.north - bounds.south;

          for (var i = 0; i < secretMessages.length; ++i) {
            var marker = new google.maps.Marker({
              position: {
                lat: bounds.south + latSpan * Math.random(),
                lng: bounds.west + lngSpan * Math.random()
              },
              map: map
            });
            attachSecretMessage(marker, secretMessages[i]);
          }
        } // Attaches an info window to a marker with the provided message. When the
        // marker is clicked, the info window will open with the secret message.

        function attachSecretMessage(marker, secretMessage) {
          var infowindow = new google.maps.InfoWindow({
            content: secretMessage
          });
          marker.addListener("click", function() {
            infowindow.open(marker.get("map"), marker);
          });
        }

        exports.attachSecretMessage = attachSecretMessage;
        exports.initMap = initMap;
      })((this.window = this.window || {}));
    </script>
  </head>
  <body>
    <div id="map"></div>
  </body>
</html>
(function(exports) { "use strict"; function initMap() { var map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: { lat: -25.363882, lng: 131.044922 } }); var bounds = { north: -25.363882, south: -31.203405, east: 131.044922, west: 125.244141 }; // Display the area between the location southWest and northEast. map.fitBounds(bounds); // Add 5 markers to map at random locations. // For each of these markers, give them a title with their index, and when // they are clicked they should open an infowindow with text from a secret // message. var secretMessages = ["This", "is", "the", "secret", "message"]; var lngSpan = bounds.east - bounds.west; var latSpan = bounds.north - bounds.south; for (var i = 0; i < secretMessages.length; ++i) { var marker = new google.maps.Marker({ position: { lat: bounds.south + latSpan * Math.random(), lng: bounds.west + lngSpan * Math.random() }, map: map }); attachSecretMessage(marker, secretMessages[i]); } } // Attaches an info window to a marker with the provided message. When the // marker is clicked, the info window will open with the secret message. function attachSecretMessage(marker, secretMessage) { var infowindow = new google.maps.InfoWindow({ content: secretMessage }); marker.addListener("click", function() { infowindow.open(marker.get("map"), marker); }); } exports.attachSecretMessage = attachSecretMessage; exports.initMap = initMap; })((this.window = this.window || {}));
/* 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; }
<!DOCTYPE html> <html> <head> <title>Using Closures in Event Listeners</title> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> <script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap&libraries=&v=weekly" defer ></script> <!-- jsFiddle will insert css and js --> </head> <body> <div id="map"></div> </body> </html>