// This example adds a map using web components.asyncfunctioninitMap():Promise<void>{const{Map}=awaitgoogle.maps.importLibrary("maps")asgoogle.maps.MapsLibrary;const{AdvancedMarkerElement}=awaitgoogle.maps.importLibrary("marker")asgoogle.maps.MarkerLibrary;console.log('Maps JavaScript API loaded.');constadvancedMarkers=document.querySelectorAll("#marker-click-event-example gmp-advanced-marker");for(constadvancedMarkerofadvancedMarkers){customElements.whenDefined(advancedMarker.localName).then(async()=>{advancedMarker.addEventListener('gmp-click',async()=>{constinfoWindow=newgoogle.maps.InfoWindow({//@ts-ignorecontent:advancedMarker.title,});infoWindow.open({//@ts-ignoreanchor:advancedMarker});});});}}initMap();
// This example adds a map using web components.asyncfunctioninitMap(){const{Map}=awaitgoogle.maps.importLibrary("maps");const{AdvancedMarkerElement}=awaitgoogle.maps.importLibrary("marker");console.log("Maps JavaScript API loaded.");constadvancedMarkers=document.querySelectorAll("#marker-click-event-example gmp-advanced-marker",);for(constadvancedMarkerofadvancedMarkers){customElements.whenDefined(advancedMarker.localName).then(async()=>{advancedMarker.addEventListener("gmp-click",async()=>{constinfoWindow=newgoogle.maps.InfoWindow({//@ts-ignorecontent:advancedMarker.title,});infoWindow.open({//@ts-ignoreanchor:advancedMarker,});});});}}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;}gmp-map{height:400px;}
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 how to add event handling to \u003ccode\u003egmp-advanced-marker\u003c/code\u003e elements using the Google Maps JavaScript API.\u003c/p\u003e\n"],["\u003cp\u003eClicking a marker on the map triggers a 'gmp-click' event, opening an \u003ccode\u003eInfoWindow\u003c/code\u003e displaying the marker's title.\u003c/p\u003e\n"],["\u003cp\u003eThe provided code snippets showcase the implementation in both TypeScript and JavaScript, along with HTML and CSS for styling and structure.\u003c/p\u003e\n"],["\u003cp\u003eThe sample utilizes Google Maps Web Components for creating interactive map elements.\u003c/p\u003e\n"],["\u003cp\u003eYou can interact with the live sample via JSFiddle or Google Cloud Shell, and clone the code for local execution using Git and Node.js.\u003c/p\u003e\n"]]],["The code adds click event handling to `gmp-advanced-marker` elements on a map. When a marker is clicked, an `InfoWindow` is displayed. This is achieved by querying all `gmp-advanced-marker` elements, adding a 'gmp-click' event listener to each. On click, a new `InfoWindow` with the marker's title is created and opened, anchored to the clicked marker. The HTML sets up a map with two markers using `gmp-map` and `gmp-advanced-marker`. CSS styles the map.\n"],null,["This example demonstrates adding event handling to some `gmp-advanced-marker`\nelements, to show an `InfoWindow` when a marker is clicked.\n\nRead the\n[documentation](/maps/documentation/javascript/web-components/overview#add_markers_to_the_map). \n\nTypeScript \n\n```typescript\n// This example adds a map using web components.\nasync function initMap(): Promise\u003cvoid\u003e {\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 console.log('Maps JavaScript API loaded.');\n\n const advancedMarkers = document.querySelectorAll(\"#marker-click-event-example gmp-advanced-marker\");\n\n for (const advancedMarker of advancedMarkers) {\n\n customElements.whenDefined(advancedMarker.localName).then(async () =\u003e {\n advancedMarker.addEventListener('gmp-click', async () =\u003e {\n\n const infoWindow = new google.maps.InfoWindow({\n //@ts-ignore\n content: advancedMarker.title,\n });\n infoWindow.open({\n //@ts-ignore\n anchor: advancedMarker\n });\n });\n });\n }\n}\n\ninitMap();https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/samples/web-components-events/index.ts#L8-L35\n```\n| **Note:** Read the [guide](/maps/documentation/javascript/using-typescript) on using TypeScript and Google Maps.\n\nJavaScript \n\n```javascript\n// This example adds a map using web components.\nasync function initMap() {\n const { Map } = await google.maps.importLibrary(\"maps\");\n const { AdvancedMarkerElement } = await google.maps.importLibrary(\"marker\");\n\n console.log(\"Maps JavaScript API loaded.\");\n\n const advancedMarkers = document.querySelectorAll(\n \"#marker-click-event-example gmp-advanced-marker\",\n );\n\n for (const advancedMarker of advancedMarkers) {\n customElements.whenDefined(advancedMarker.localName).then(async () =\u003e {\n advancedMarker.addEventListener(\"gmp-click\", async () =\u003e {\n const infoWindow = new google.maps.InfoWindow({\n //@ts-ignore\n content: advancedMarker.title,\n });\n\n infoWindow.open({\n //@ts-ignore\n anchor: advancedMarker,\n });\n });\n });\n }\n}\n\ninitMap();https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/web-components-events/docs/index.js#L7-L35\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}\n\ngmp-map {\n height: 400px;\n}\nhttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/web-components-events/docs/style.css#L7-L28\n```\n\nHTML \n\n```html\n\u003chtml\u003e\n \u003chead\u003e\n \u003ctitle\u003eAdd a Map Web Component with Events\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 \u003cgmp-map\n id=\"marker-click-event-example\"\n center=\"43.4142989,-124.2301242\"\n zoom=\"4\"\n map-id=\"DEMO_MAP_ID\"\n \u003e\n \u003cgmp-advanced-marker\n position=\"37.4220656,-122.0840897\"\n title=\"Mountain View, CA\"\n gmp-clickable\n \u003e\u003c/gmp-advanced-marker\u003e\n \u003cgmp-advanced-marker\n position=\"47.648994,-122.3503845\"\n title=\"Seattle, WA\"\n gmp-clickable\n \u003e\u003c/gmp-advanced-marker\u003e\n \u003c/gmp-map\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: \"beta\"});\u003c/script\u003e\n \u003c/body\u003e\n\u003c/html\u003ehttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/web-components-events/docs/index.html#L8-L38\n```\n\nTry Sample \n[JSFiddle.net](https://jsfiddle.net/gh/get/library/pure/googlemaps/js-samples/tree/master/dist/samples/web-components-events/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-web-components-events&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-web-components-events 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"]]