How to use Closures in Event Listeners? - WP Maps Pro

15000+ live websites are using this google maps wordpress plugin.

How to use Closures in Event Listeners?

wp google maps pro free download

Introduction:

In this tutorial, we will learn to create a map with tappable markers displaying a secret message.

It is frequently desirable to have both private and persistent data associated to an object when performing an event listener. JavaScript does not offer “private” instance data, but it does have closures, which allow inner functions to access variables in the outside world. Closures are helpful in event listeners because they provide access to variables that are not ordinarily associated with the objects on which events occur.

The following example assigns a hidden message to a group of markers using a function closure in the event listener. Each marker, when clicked, reveals a section of the hidden message that is not contained inside the marker itself.

Code:

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

  const bounds: google.maps.LatLngBoundsLiteral = {
    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.
  const secretMessages = ["This", "is", "the", "secret", "message"];
  const lngSpan = bounds.east - bounds.west;
  const latSpan = bounds.north - bounds.south;

  for (let i = 0; i < secretMessages.length; ++i) { const 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: google.maps.Marker, secretMessage: string ) { const infowindow = new google.maps.InfoWindow({ content: secretMessage, }); marker.addListener("click", () => {
    infowindow.open(marker.get("map"), marker);
  });
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;
export {};

Explanation:

  • The function initMap() is created and it consists of the map properties.
  • The ‘centre’ attribute defines where the map should be centered with the help of the latitude and longitude coordinates.
  • center: { lat: -25.363882, lng: 131.044922 },
    
  • The ‘zoom’ attribute specifies the map’s zoom level.
  • zoom: 4,
    
  • The line, “map = new google.maps.Map(document.getElementById(“map”)”; creates a new map inside the <div> element with the help of the mentioned id which is ‘map’ as an HTMLElement.
  • const map = new google.maps.Map(
        document.getElementById("map") as HTMLElement,
    
  • Next, the longitude and latitude bound literals are created. A LatLngBounds instance represents a rectangle in geographical coordinates, including one that crosses the 180 degrees longitudinal meridian.
  • const bounds: google.maps.LatLngBoundsLiteral = {
        north: -25.363882,
        south: -31.203405,
        east: 131.044922,
        west: 125.244141,
      };
    
  • Next, we 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.
  • const secretMessages = ["This", "is", "the", "secret", "message"];
      const lngSpan = bounds.east - bounds.west;
      const latSpan = bounds.north - bounds.south;
    
  • Next, we attach 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: google.maps.Marker,
      secretMessage: string
    ) {
      const infowindow = new google.maps.InfoWindow({
        content: secretMessage,
      });
    
      marker.addListener("click", () => {
        infowindow.open(marker.get("map"), marker);
      });
    }
    
  • Finally, we add the addListener().
  • Lastly, the function is called and executed.
  • window.initMap = initMap;
    

Conclusion:

Thus, in this tutorial we learned the usage of closures in Event Listeners. We saw an example of how to create a map with tappable markers displaying a secret message.

Live Example

Install Plugin Now!

Buy this plugin exclusively on CodeCanyon! You’ll get free updates, full support, and if you’re not satisfied, we’ve got you covered with a 30-day money-back guarantee.