asyncfunctioninitMap(){// Request needed libraries.const{Map}=awaitgoogle.maps.importLibrary("maps")asgoogle.maps.MapsLibrary;const{AdvancedMarkerElement}=awaitgoogle.maps.importLibrary("marker")asgoogle.maps.MarkerLibrary;constmap=newgoogle.maps.Map(document.getElementById("map")asHTMLElement,{zoom:4,center:{lat:-25.363882,lng:131.044922},mapId:"DEMO_MAP_ID",});constbounds: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.constsecretMessages=["This","is","the","secret","message"];constlngSpan=bounds.east-bounds.west;constlatSpan=bounds.north-bounds.south;for(leti=0;i < secretMessages.length;++i){constmarker=newgoogle.maps.marker.AdvancedMarkerElement({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.functionattachSecretMessage(marker:google.maps.marker.AdvancedMarkerElement,secretMessage:string){constinfowindow=newgoogle.maps.InfoWindow({content:secretMessage,});marker.addListener("click",()=>{infowindow.open(marker.map,marker);});}initMap();
asyncfunctioninitMap(){// Request needed libraries.const{Map}=awaitgoogle.maps.importLibrary("maps");const{AdvancedMarkerElement}=awaitgoogle.maps.importLibrary("marker");constmap=newgoogle.maps.Map(document.getElementById("map"),{zoom:4,center:{lat:-25.363882,lng:131.044922},mapId:"DEMO_MAP_ID",});constbounds={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.constsecretMessages=["This","is","the","secret","message"];constlngSpan=bounds.east-bounds.west;constlatSpan=bounds.north-bounds.south;for(leti=0;i < secretMessages.length;++i){constmarker=newgoogle.maps.marker.AdvancedMarkerElement({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.functionattachSecretMessage(marker,secretMessage){constinfowindow=newgoogle.maps.InfoWindow({content:secretMessage,});marker.addListener("click",()=>{infowindow.open(marker.map,marker);});}initMap();
/* * 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;}
Git and Node.js are required to run this sample locally. Follow these instructions to install Node.js and NPM. The following commands clone, install dependencies and start the sample application.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-20 UTC."],[[["\u003cp\u003eThis example demonstrates creating a Google Map with 5 randomly placed markers within a defined boundary in Australia.\u003c/p\u003e\n"],["\u003cp\u003eEach marker, when clicked, reveals a part of a secret message using an info window.\u003c/p\u003e\n"],["\u003cp\u003eThe code is provided in both TypeScript and JavaScript, utilizing the Google Maps JavaScript API.\u003c/p\u003e\n"],["\u003cp\u003eThe sample can be run locally with Git and Node.js or tried online using JSFiddle or Google Cloud Shell.\u003c/p\u003e\n"],["\u003cp\u003eCSS is included to ensure the map fills the browser window and has an explicit height.\u003c/p\u003e\n"]]],[],null,["This example creates a map with tappable markers displaying a secret message.\n\nRead the [documentation](/maps/documentation/javascript/events#EventClosures). \n\nTypeScript \n\n```typescript\nasync function initMap() {\n // Request needed libraries.\n const { Map } = await google.maps.importLibrary(\"maps\") as google.maps.MapsLibrary;\n const { AdvancedMarkerElement } = await google.maps.importLibrary(\"marker\") as google.maps.MarkerLibrary;\n\n const map = new google.maps.Map(\n document.getElementById(\"map\") as HTMLElement,\n {\n zoom: 4,\n center: { lat: -25.363882, lng: 131.044922 },\n mapId: \"DEMO_MAP_ID\",\n }\n );\n\n const bounds: google.maps.LatLngBoundsLiteral = {\n north: -25.363882,\n south: -31.203405,\n east: 131.044922,\n west: 125.244141,\n };\n\n // Display the area between the location southWest and northEast.\n map.fitBounds(bounds);\n\n // Add 5 markers to map at random locations.\n // For each of these markers, give them a title with their index, and when\n // they are clicked they should open an infowindow with text from a secret\n // message.\n const secretMessages = [\"This\", \"is\", \"the\", \"secret\", \"message\"];\n const lngSpan = bounds.east - bounds.west;\n const latSpan = bounds.north - bounds.south;\n\n for (let i = 0; i \u003c secretMessages.length; ++i) {\n const marker = new google.maps.marker.AdvancedMarkerElement({\n position: {\n lat: bounds.south + latSpan * Math.random(),\n lng: bounds.west + lngSpan * Math.random(),\n },\n map: map,\n });\n\n attachSecretMessage(marker, secretMessages[i]);\n }\n}\n\n// Attaches an info window to a marker with the provided message. When the\n// marker is clicked, the info window will open with the secret message.\nfunction attachSecretMessage(\n marker: google.maps.marker.AdvancedMarkerElement,\n secretMessage: string\n) {\n const infowindow = new google.maps.InfoWindow({\n content: secretMessage,\n });\n\n marker.addListener(\"click\", () =\u003e {\n infowindow.open(marker.map, marker);\n });\n}\n\ninitMap();https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/samples/event-closure/index.ts#L8-L68\n```\n| **Note:** Read the [guide](/maps/documentation/javascript/using-typescript) on using TypeScript and Google Maps.\n\nJavaScript \n\n```javascript\nasync function initMap() {\n // Request needed libraries.\n const { Map } = await google.maps.importLibrary(\"maps\");\n const { AdvancedMarkerElement } = await google.maps.importLibrary(\"marker\");\n const map = new google.maps.Map(document.getElementById(\"map\"), {\n zoom: 4,\n center: { lat: -25.363882, lng: 131.044922 },\n mapId: \"DEMO_MAP_ID\",\n });\n const bounds = {\n north: -25.363882,\n south: -31.203405,\n east: 131.044922,\n west: 125.244141,\n };\n\n // Display the area between the location southWest and northEast.\n map.fitBounds(bounds);\n\n // Add 5 markers to map at random locations.\n // For each of these markers, give them a title with their index, and when\n // they are clicked they should open an infowindow with text from a secret\n // message.\n const secretMessages = [\"This\", \"is\", \"the\", \"secret\", \"message\"];\n const lngSpan = bounds.east - bounds.west;\n const latSpan = bounds.north - bounds.south;\n\n for (let i = 0; i \u003c secretMessages.length; ++i) {\n const marker = new google.maps.marker.AdvancedMarkerElement({\n position: {\n lat: bounds.south + latSpan * Math.random(),\n lng: bounds.west + lngSpan * Math.random(),\n },\n map: map,\n });\n\n attachSecretMessage(marker, secretMessages[i]);\n }\n}\n\n// Attaches an info window to a marker with the provided message. When the\n// marker is clicked, the info window will open with the secret message.\nfunction attachSecretMessage(marker, secretMessage) {\n const infowindow = new google.maps.InfoWindow({\n content: secretMessage,\n });\n\n marker.addListener(\"click\", () =\u003e {\n infowindow.open(marker.map, marker);\n });\n}\n\ninitMap();https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/event-closure/docs/index.js#L7-L59\n```\n| **Note:** The JavaScript is compiled from the TypeScript snippet.\n\nCSS \n\n```css\n/* \n * Always set the map height explicitly to define the size of the div element\n * that contains the map. \n */\n#map {\n height: 100%;\n}\n\n/* \n * Optional: Makes the sample page fill the window. \n */\nhtml,\nbody {\n height: 100%;\n margin: 0;\n padding: 0;\n}\nhttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/event-closure/docs/style.css#L7-L24\n```\n\nHTML \n\n```html\n\u003chtml\u003e\n \u003chead\u003e\n \u003ctitle\u003eUsing Closures in Event Listeners\u003c/title\u003e\n\n \u003clink rel=\"stylesheet\" type=\"text/css\" href=\"./style.css\" /\u003e\n \u003cscript type=\"module\" src=\"./index.js\"\u003e\u003c/script\u003e\n \u003c/head\u003e\n \u003cbody\u003e\n \u003cdiv id=\"map\"\u003e\u003c/div\u003e\n\n \u003c!-- prettier-ignore --\u003e\n \u003cscript\u003e(g=\u003e{var h,a,k,p=\"The Google Maps JavaScript API\",c=\"google\",l=\"importLibrary\",q=\"__ib__\",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=\u003eh||(h=new Promise(async(f,n)=\u003e{await (a=m.createElement(\"script\"));e.set(\"libraries\",[...r]+\"\");for(k in g)e.set(k.replace(/[A-Z]/g,t=\u003e\"_\"+t[0].toLowerCase()),g[k]);e.set(\"callback\",c+\".maps.\"+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=\u003eh=n(Error(p+\" could not load.\"));a.nonce=m.querySelector(\"script[nonce]\")?.nonce||\"\";m.head.append(a)}));d[l]?console.warn(p+\" only loads once. Ignoring:\",g):d[l]=(f,...n)=\u003er.add(f)&&u().then(()=\u003ed[l](f,...n))})\n ({key: \"AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg\", v: \"weekly\"});\u003c/script\u003e\n \u003c/body\u003e\n\u003c/html\u003ehttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/event-closure/docs/index.html#L8-L22\n```\n\nTry Sample \n[JSFiddle.net](https://jsfiddle.net/gh/get/library/pure/googlemaps/js-samples/tree/master/dist/samples/event-closure/jsfiddle) [Google Cloud Shell](https://ssh.cloud.google.com/cloudshell/editor?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Fgooglemaps%2Fjs-samples&cloudshell_git_branch=sample-event-closure&cloudshell_tutorial=cloud_shell_instructions.md&cloudshell_workspace=.)\n\nClone Sample\n\n\nGit and Node.js are required to run this sample locally. Follow these [instructions](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) to install Node.js and NPM. The following commands clone, install dependencies and start the sample application. \n\n git clone -b sample-event-closure https://github.com/googlemaps/js-samples.git\n cd js-samples\n npm i\n npm start\n\n\nOther samples can be tried by switching to any branch beginning with `sample-`\u003cvar translate=\"no\"\u003eSAMPLE_NAME\u003c/var\u003e. \n\n git checkout sample-\u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-nx\"\u003eSAMPLE_NAME\u003c/span\u003e\u003c/var\u003e\n npm i\n npm start"]]