Stay organized with collections Save and categorize content based on your preferences.
This example demonstrates adding controls that store state. It shows a map with two buttons, "Set Center" and "Center Map". The "Set Center" button can be used to store the center of the map. Pressing the "Center Map" button will pan the map to the previously stored center.
letmap:google.maps.Map;constchicago:google.maps.LatLngLiteral={lat:41.85,lng:-87.65};/** * The CenterControl adds a control to the map that recenters the map on * Chicago. */classCenterControl{privatemap_:google.maps.Map;privatecenter_:google.maps.LatLng;constructor(controlDiv:HTMLElement,map:google.maps.Map,center:google.maps.LatLngLiteral){this.map_=map;// Set the center property upon constructionthis.center_=newgoogle.maps.LatLng(center);controlDiv.style.clear="both";// Set CSS for the control borderconstgoCenterUI=document.createElement("button");goCenterUI.id="goCenterUI";goCenterUI.title="Click to recenter the map";controlDiv.appendChild(goCenterUI);// Set CSS for the control interiorconstgoCenterText=document.createElement("div");goCenterText.id="goCenterText";goCenterText.innerHTML="Center Map";goCenterUI.appendChild(goCenterText);// Set CSS for the setCenter control borderconstsetCenterUI=document.createElement("button");setCenterUI.id="setCenterUI";setCenterUI.title="Click to change the center of the map";controlDiv.appendChild(setCenterUI);// Set CSS for the control interiorconstsetCenterText=document.createElement("div");setCenterText.id="setCenterText";setCenterText.innerHTML="Set Center";setCenterUI.appendChild(setCenterText);// Set up the click event listener for 'Center Map': Set the center of// the map// to the current center of the control.goCenterUI.addEventListener("click",()=>{constcurrentCenter=this.center_;this.map_.setCenter(currentCenter);});// Set up the click event listener for 'Set Center': Set the center of// the control to the current center of the map.setCenterUI.addEventListener("click",()=>{constnewCenter=this.map_.getCenter()!;if(newCenter){this.center_=newCenter;}});}}functioninitMap():void{map=newgoogle.maps.Map(document.getElementById("map")asHTMLElement,{zoom:12,center:chicago,});// Create the DIV to hold the control and call the CenterControl()// constructor passing in this DIV.constcenterControlDiv=document.createElement("div");constcontrol=newCenterControl(centerControlDiv,map,chicago);// @ts-ignorecenterControlDiv.index=1;centerControlDiv.style.paddingTop="10px";map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);}declareglobal{interfaceWindow{initMap:()=>void;}}window.initMap=initMap;
letmap;constchicago={lat:41.85,lng:-87.65};/** * The CenterControl adds a control to the map that recenters the map on * Chicago. */classCenterControl{map_;center_;constructor(controlDiv,map,center){this.map_=map;// Set the center property upon constructionthis.center_=newgoogle.maps.LatLng(center);controlDiv.style.clear="both";// Set CSS for the control borderconstgoCenterUI=document.createElement("button");goCenterUI.id="goCenterUI";goCenterUI.title="Click to recenter the map";controlDiv.appendChild(goCenterUI);// Set CSS for the control interiorconstgoCenterText=document.createElement("div");goCenterText.id="goCenterText";goCenterText.innerHTML="Center Map";goCenterUI.appendChild(goCenterText);// Set CSS for the setCenter control borderconstsetCenterUI=document.createElement("button");setCenterUI.id="setCenterUI";setCenterUI.title="Click to change the center of the map";controlDiv.appendChild(setCenterUI);// Set CSS for the control interiorconstsetCenterText=document.createElement("div");setCenterText.id="setCenterText";setCenterText.innerHTML="Set Center";setCenterUI.appendChild(setCenterText);// Set up the click event listener for 'Center Map': Set the center of// the map// to the current center of the control.goCenterUI.addEventListener("click",()=>{constcurrentCenter=this.center_;this.map_.setCenter(currentCenter);});// Set up the click event listener for 'Set Center': Set the center of// the control to the current center of the map.setCenterUI.addEventListener("click",()=>{constnewCenter=this.map_.getCenter();if(newCenter){this.center_=newCenter;}});}}functioninitMap(){map=newgoogle.maps.Map(document.getElementById("map"),{zoom:12,center:chicago,});// Create the DIV to hold the control and call the CenterControl()// constructor passing in this DIV.constcenterControlDiv=document.createElement("div");constcontrol=newCenterControl(centerControlDiv,map,chicago);// @ts-ignorecenterControlDiv.index=1;centerControlDiv.style.paddingTop="10px";map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);}window.initMap=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;}#goCenterUI,#setCenterUI{background-color:#fff;border:2pxsolid#fff;border-radius:3px;box-shadow:02px6pxrgba(0,0,0,0.3);cursor:pointer;float:left;margin-bottom:22px;text-align:center;}#goCenterText,#setCenterText{color:rgb(25,25,25);font-family:Roboto,Arial,sans-serif;font-size:15px;line-height:25px;padding-left:5px;padding-right:5px;}#setCenterUI{margin-left:12px;}
<html> <head> <title>Adding State to Controls</title> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <div id="map"></div> <!-- The `defer` attribute causes the script to execute after the full HTML document has been parsed. For non-blocking uses, avoiding race conditions, and consistent behavior across browsers, consider loading using Promises. See https://developers.google.com/maps/documentation/javascript/load-maps-js-api for more information. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly" defer ></script> </body> </html>
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 controls to a Google Map that can store and utilize state.\u003c/p\u003e\n"],["\u003cp\u003eIt features two buttons: "Set Center" which stores the current map center, and "Center Map" which recenters the map to the stored location.\u003c/p\u003e\n"],["\u003cp\u003eThe sample code showcases the implementation using TypeScript and JavaScript, along with HTML and CSS for styling.\u003c/p\u003e\n"],["\u003cp\u003eUsers can interact with a live demo through provided links to JSFiddle and Google Cloud Shell.\u003c/p\u003e\n"],["\u003cp\u003eDevelopers can clone and run the sample locally using Git and Node.js following the instructions provided.\u003c/p\u003e\n"]]],["This code implements two custom buttons, \"Set Center\" and \"Center Map,\" on a Google Map. \"Set Center\" stores the map's current center coordinates when clicked. \"Center Map,\" when clicked, pans the map to the previously stored center. The `CenterControl` class manages these buttons and their actions, updating and retrieving the stored map center. These buttons are added to the map's control interface and can be tested on local or online platforms.\n"],null,["This example demonstrates adding controls that store state. It shows a map with\ntwo buttons, \"Set Center\" and \"Center Map\". The \"Set Center\" button can be used\nto store the center of the map. Pressing the \"Center Map\" button will pan the\nmap to the previously stored center.\n\nRead the [documentation](/maps/documentation/javascript/controls#ControlState). \n\nTypeScript \n\n```typescript\nlet map: google.maps.Map;\n\nconst chicago: google.maps.LatLngLiteral = { lat: 41.85, lng: -87.65 };\n\n/**\n * The CenterControl adds a control to the map that recenters the map on\n * Chicago.\n */\nclass CenterControl {\n private map_: google.maps.Map;\n private center_: google.maps.LatLng;\n constructor(\n controlDiv: HTMLElement,\n map: google.maps.Map,\n center: google.maps.LatLngLiteral\n ) {\n this.map_ = map;\n // Set the center property upon construction\n this.center_ = new google.maps.LatLng(center);\n controlDiv.style.clear = \"both\";\n\n // Set CSS for the control border\n const goCenterUI = document.createElement(\"button\");\n\n goCenterUI.id = \"goCenterUI\";\n goCenterUI.title = \"Click to recenter the map\";\n controlDiv.appendChild(goCenterUI);\n\n // Set CSS for the control interior\n const goCenterText = document.createElement(\"div\");\n\n goCenterText.id = \"goCenterText\";\n goCenterText.innerHTML = \"Center Map\";\n goCenterUI.appendChild(goCenterText);\n\n // Set CSS for the setCenter control border\n const setCenterUI = document.createElement(\"button\");\n\n setCenterUI.id = \"setCenterUI\";\n setCenterUI.title = \"Click to change the center of the map\";\n controlDiv.appendChild(setCenterUI);\n\n // Set CSS for the control interior\n const setCenterText = document.createElement(\"div\");\n\n setCenterText.id = \"setCenterText\";\n setCenterText.innerHTML = \"Set Center\";\n setCenterUI.appendChild(setCenterText);\n\n // Set up the click event listener for 'Center Map': Set the center of\n // the map\n // to the current center of the control.\n goCenterUI.addEventListener(\"click\", () =\u003e {\n const currentCenter = this.center_;\n\n this.map_.setCenter(currentCenter);\n });\n\n // Set up the click event listener for 'Set Center': Set the center of\n // the control to the current center of the map.\n setCenterUI.addEventListener(\"click\", () =\u003e {\n const newCenter = this.map_.getCenter()!;\n\n if (newCenter) {\n this.center_ = newCenter;\n }\n });\n }\n}\n\nfunction initMap(): void {\n map = new google.maps.Map(document.getElementById(\"map\") as HTMLElement, {\n zoom: 12,\n center: chicago,\n });\n\n // Create the DIV to hold the control and call the CenterControl()\n // constructor passing in this DIV.\n const centerControlDiv = document.createElement(\"div\");\n const control = new CenterControl(centerControlDiv, map, chicago);\n\n // @ts-ignore\n centerControlDiv.index = 1;\n centerControlDiv.style.paddingTop = \"10px\";\n map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);\n}\n\ndeclare global {\n interface Window {\n initMap: () =\u003e void;\n }\n}\nwindow.initMap = initMap;https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/samples/control-custom-state/index.ts#L8-L100\n```\n| **Note:** Read the [guide](/maps/documentation/javascript/using-typescript) on using TypeScript and Google Maps.\n\nJavaScript \n\n```javascript\nlet map;\nconst chicago = { lat: 41.85, lng: -87.65 };\n\n/**\n * The CenterControl adds a control to the map that recenters the map on\n * Chicago.\n */\nclass CenterControl {\n map_;\n center_;\n constructor(controlDiv, map, center) {\n this.map_ = map;\n // Set the center property upon construction\n this.center_ = new google.maps.LatLng(center);\n controlDiv.style.clear = \"both\";\n\n // Set CSS for the control border\n const goCenterUI = document.createElement(\"button\");\n\n goCenterUI.id = \"goCenterUI\";\n goCenterUI.title = \"Click to recenter the map\";\n controlDiv.appendChild(goCenterUI);\n\n // Set CSS for the control interior\n const goCenterText = document.createElement(\"div\");\n\n goCenterText.id = \"goCenterText\";\n goCenterText.innerHTML = \"Center Map\";\n goCenterUI.appendChild(goCenterText);\n\n // Set CSS for the setCenter control border\n const setCenterUI = document.createElement(\"button\");\n\n setCenterUI.id = \"setCenterUI\";\n setCenterUI.title = \"Click to change the center of the map\";\n controlDiv.appendChild(setCenterUI);\n\n // Set CSS for the control interior\n const setCenterText = document.createElement(\"div\");\n\n setCenterText.id = \"setCenterText\";\n setCenterText.innerHTML = \"Set Center\";\n setCenterUI.appendChild(setCenterText);\n // Set up the click event listener for 'Center Map': Set the center of\n // the map\n // to the current center of the control.\n goCenterUI.addEventListener(\"click\", () =\u003e {\n const currentCenter = this.center_;\n\n this.map_.setCenter(currentCenter);\n });\n // Set up the click event listener for 'Set Center': Set the center of\n // the control to the current center of the map.\n setCenterUI.addEventListener(\"click\", () =\u003e {\n const newCenter = this.map_.getCenter();\n\n if (newCenter) {\n this.center_ = newCenter;\n }\n });\n }\n}\n\nfunction initMap() {\n map = new google.maps.Map(document.getElementById(\"map\"), {\n zoom: 12,\n center: chicago,\n });\n\n // Create the DIV to hold the control and call the CenterControl()\n // constructor passing in this DIV.\n const centerControlDiv = document.createElement(\"div\");\n const control = new CenterControl(centerControlDiv, map, chicago);\n\n // @ts-ignore\n centerControlDiv.index = 1;\n centerControlDiv.style.paddingTop = \"10px\";\n map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);\n}\n\nwindow.initMap = initMap;https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/control-custom-state/docs/index.js#L7-L87\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\n#goCenterUI,\n#setCenterUI {\n background-color: #fff;\n border: 2px solid #fff;\n border-radius: 3px;\n box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);\n cursor: pointer;\n float: left;\n margin-bottom: 22px;\n text-align: center;\n}\n\n#goCenterText,\n#setCenterText {\n color: rgb(25, 25, 25);\n font-family: Roboto, Arial, sans-serif;\n font-size: 15px;\n line-height: 25px;\n padding-left: 5px;\n padding-right: 5px;\n}\n\n#setCenterUI {\n margin-left: 12px;\n}\nhttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/control-custom-state/docs/style.css#L7-L50\n```\n\nHTML \n\n```html\n\u003chtml\u003e\n \u003chead\u003e\n \u003ctitle\u003eAdding State to Controls\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!-- \n The `defer` attribute causes the script to execute after the full HTML\n document has been parsed. For non-blocking uses, avoiding race conditions,\n and consistent behavior across browsers, consider loading using Promises. See\n https://developers.google.com/maps/documentation/javascript/load-maps-js-api\n for more information.\n --\u003e\n \u003cscript\n src=\"https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly\"\n defer\n \u003e\u003c/script\u003e\n \u003c/body\u003e\n\u003c/html\u003ehttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/control-custom-state/docs/index.html#L8-L30\n```\n\nTry Sample \n[JSFiddle.net](https://jsfiddle.net/gh/get/library/pure/googlemaps/js-samples/tree/master/dist/samples/control-custom-state/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-control-custom-state&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-control-custom-state 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"]]