Map Puzzle Stay organized with collections Save and categorize content based on your preferences.
AI-generated Key Takeaways
This demo showcases a draggable map puzzle game where users drag polygon pieces to their correct locations on a world map.
The game features adjustable difficulty levels that alter the map's visual style and provides a timer to track the player's progress.
Users can reset the game at any time to start a new puzzle with randomized country pieces.
The demo is built using the Google Maps JavaScript API with examples provided in both TypeScript and JavaScript.
The game utilizes encoded paths to define the shapes of country pieces and their target locations on the map.
More complex demo, showing a game with draggable polygons. See the draggablepolygon demo for a simple demo with draggable polygons.
TypeScript
interfaceCountry{bounds:number[][];name:string;start:string[];end:string[];}classPuzzleDemo{privatemap_:google.maps.Map;privatepolys_:google.maps.Polygon[]=[];privatedifficulty_="Easy";privatecount_=0;privatepieceDiv_:HTMLElement;privatetimeDiv_:HTMLElement;privatedataLoaded_=false;privateNUM_PIECES_=10;privatecountries_:Country[]=[];privatetimer_=0;privateSTART_COLOR_="#3c79de";privateEND_COLOR_="#037e29";constructor(map:google.maps.Map){this.map_=map;this.pieceDiv_=document.createElement("div");this.timeDiv_=document.createElement("div");this.createMenu_();this.setDifficultyStyle_();this.loadData_();}privatecreateMenu_(){constmenuDiv=document.createElement("div");menuDiv.style.cssText="margin: 40px 10px; border-radius: 8px; height: 320px; width: 180px;"+"background-color: white; font-size: 14px; font-family: Roboto;"+"text-align: center; color: grey;line-height: 32px; overflow: hidden";consttitleDiv=document.createElement("div");titleDiv.style.cssText="width: 100%; background-color: #4285f4; color: white; font-size: 20px;"+"line-height: 40px;margin-bottom: 24px";titleDiv.innerText="Game Options";constpieceTitleDiv=document.createElement("div");pieceTitleDiv.innerText="PIECE:";pieceTitleDiv.style.fontWeight="800";constpieceDiv=this.pieceDiv_;pieceDiv.innerText="0 / "+this.NUM_PIECES_;consttimeTitleDiv=document.createElement("div");timeTitleDiv.innerText="TIME:";timeTitleDiv.style.fontWeight="800";consttimeDiv=this.timeDiv_;timeDiv.innerText="0.0 seconds";constdifficultyTitleDiv=document.createElement("div");difficultyTitleDiv.innerText="DIFFICULTY:";difficultyTitleDiv.style.fontWeight="800";constdifficultySelect=document.createElement("select");["Easy","Moderate","Hard","Extreme"].forEach((level)=>{constoption=document.createElement("option");option.value=level.toLowerCase();option.innerText=level;difficultySelect.appendChild(option);});difficultySelect.style.cssText="border: 2px solid lightgrey; background-color: white; color: #4275f4;"+"padding: 6px;";difficultySelect.onchange=()=>{this.setDifficulty_(difficultySelect.value);this.resetGame_();};constresetDiv=document.createElement("div");resetDiv.innerText="Reset";resetDiv.style.cssText="cursor: pointer; border-top: 1px solid lightgrey; margin-top: 18px;"+"color: #4275f4; line-height: 40px; font-weight: 800";resetDiv.onclick=this.resetGame_.bind(this);menuDiv.appendChild(titleDiv);menuDiv.appendChild(pieceTitleDiv);menuDiv.appendChild(pieceDiv);menuDiv.appendChild(timeTitleDiv);menuDiv.appendChild(timeDiv);menuDiv.appendChild(difficultyTitleDiv);menuDiv.appendChild(difficultySelect);menuDiv.appendChild(resetDiv);this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(menuDiv);}render(){if(!this.dataLoaded_){return;}this.start_();}privateloadData_(){constxmlhttpRequest=newXMLHttpRequest();xmlhttpRequest.onreadystatechange=()=>{if(xmlhttpRequest.status!=200||xmlhttpRequest.readyState!=XMLHttpRequest.DONE)return;this.loadDataComplete_(JSON.parse(xmlhttpRequest.responseText)asany);};xmlhttpRequest.open("GET","https://storage.googleapis.com/mapsdevsite/json/puzzle.json",true);xmlhttpRequest.send(null);}privateloadDataComplete_(data:Country[]){this.dataLoaded_=true;this.countries_=data;this.start_();}/** * @param {string} difficulty * @private */privatesetDifficulty_(difficulty:string){this.difficulty_=difficulty;if(this.map_){this.setDifficultyStyle_();}}privatesetDifficultyStyle_(){conststyles={easy:[{stylers:[{visibility:"off"}],},{featureType:"water",stylers:[{visibility:"on"},{color:"#d4d4d4"}],},{featureType:"landscape",stylers:[{visibility:"on"},{color:"#e5e3df"}],},{featureType:"administrative.country",elementType:"labels",stylers:[{visibility:"on"}],},{featureType:"administrative.country",elementType:"geometry",stylers:[{visibility:"on"},{weight:1.3}],},],moderate:[{stylers:[{visibility:"off"}],},{featureType:"water",stylers:[{visibility:"on"},{color:"#d4d4d4"}],},{featureType:"landscape",stylers:[{visibility:"on"},{color:"#e5e3df"}],},{featureType:"administrative.country",elementType:"labels",stylers:[{visibility:"on"}],},],hard:[{stylers:[{visibility:"off"}],},{featureType:"water",stylers:[{visibility:"on"},{color:"#d4d4d4"}],},{featureType:"landscape",stylers:[{visibility:"on"},{color:"#e5e3df"}],},],extreme:[{elementType:"geometry",stylers:[{visibility:"off"}],},],};this.map_.set("styles",styles[this.difficulty_]);}privateresetGame_(){this.removeCountries_();this.count_=0;this.setCount_();this.startClock_();this.addRandomCountries_();}privatesetCount_(){this.pieceDiv_.innerText=this.count_+" / "+this.NUM_PIECES_;if(this.count_==this.NUM_PIECES_){this.stopClock_();}}privatestopClock_(){window.clearInterval(this.timer_);}privatestartClock_(){this.stopClock_();consttimeDiv=this.timeDiv_;if(timeDiv)timeDiv.textContent="0.0 seconds";constt=newDate();this.timer_=window.setInterval(()=>{constdiff=newDate().getTime()-t.getTime();if(timeDiv)timeDiv.textContent=(diff/1000).toFixed(2)+" seconds";},100);}privateaddRandomCountries_(){// Shuffle countriesthis.countries_.sort(()=>{returnMath.round(Math.random())-0.5;});constcountries=this.countries_.slice(0,this.NUM_PIECES_);for(leti=0,country;(country=countries[i]);i++){this.addCountry_(country);}}privateaddCountry_(country:Country){constoptions={strokeColor:this.START_COLOR_,strokeOpacity:0.8,strokeWeight:2,fillColor:this.START_COLOR_,fillOpacity:0.35,geodesic:true,map:this.map_,draggable:true,zIndex:2,paths:country.start.map(google.maps.geometry.encoding.decodePath),};constpoly=newgoogle.maps.Polygon(options);google.maps.event.addListener(poly,"dragend",()=>{this.checkPosition_(poly,country);});this.polys_.push(poly);}/** * Checks that every point in the polygon is inside the bounds. */privateboundsContainsPoly_(bounds:number[][],poly:google.maps.Polygon):boolean{constb=newgoogle.maps.LatLngBounds(newgoogle.maps.LatLng(bounds[0][0],bounds[0][1]),newgoogle.maps.LatLng(bounds[1][0],bounds[1][1]));constpaths=poly.getPaths().getArray();for(leti=0;i <paths.length;i++){constp=paths[i].getArray();for(letj=0;j <p.length;j++){if(!b.contains(p[j])){returnfalse;}}}returntrue;}/** * Replace a poly with the correct 'end' position of the country. */privatereplacePiece_(poly:google.maps.Polygon,country:Country){constoptions={strokeColor:this.END_COLOR_,fillColor:this.END_COLOR_,draggable:false,zIndex:1,paths:country.end.map(google.maps.geometry.encoding.decodePath),};poly.setOptions(options);this.count_++;this.setCount_();}privatecheckPosition_(poly:google.maps.Polygon,country:Country){if(this.boundsContainsPoly_(country.bounds,poly)){this.replacePiece_(poly,country);}}privatestart_(){this.setDifficultyStyle_();this.resetGame_();}privateremoveCountries_(){for(leti=0,poly;(poly=this.polys_[i]);i++){poly.setMap(null);}this.polys_=[];}}functioninitMap():void{constmap=newgoogle.maps.Map(document.getElementById("map")asHTMLElement,{disableDefaultUI:true,center:{lat:10,lng:60},zoom:2,});newPuzzleDemo(map);}declareglobal{interfaceWindow{initMap:()=>void;}}window.initMap=initMap;
JavaScript
classPuzzleDemo{map_;polys_=[];difficulty_="Easy";count_=0;pieceDiv_;timeDiv_;dataLoaded_=false;NUM_PIECES_=10;countries_=[];timer_=0;START_COLOR_="#3c79de";END_COLOR_="#037e29";constructor(map){this.map_=map;this.pieceDiv_=document.createElement("div");this.timeDiv_=document.createElement("div");this.createMenu_();this.setDifficultyStyle_();this.loadData_();}createMenu_(){constmenuDiv=document.createElement("div");menuDiv.style.cssText="margin: 40px 10px; border-radius: 8px; height: 320px; width: 180px;"+"background-color: white; font-size: 14px; font-family: Roboto;"+"text-align: center; color: grey;line-height: 32px; overflow: hidden";consttitleDiv=document.createElement("div");titleDiv.style.cssText="width: 100%; background-color: #4285f4; color: white; font-size: 20px;"+"line-height: 40px;margin-bottom: 24px";titleDiv.innerText="Game Options";constpieceTitleDiv=document.createElement("div");pieceTitleDiv.innerText="PIECE:";pieceTitleDiv.style.fontWeight="800";constpieceDiv=this.pieceDiv_;pieceDiv.innerText="0 / "+this.NUM_PIECES_;consttimeTitleDiv=document.createElement("div");timeTitleDiv.innerText="TIME:";timeTitleDiv.style.fontWeight="800";consttimeDiv=this.timeDiv_;timeDiv.innerText="0.0 seconds";constdifficultyTitleDiv=document.createElement("div");difficultyTitleDiv.innerText="DIFFICULTY:";difficultyTitleDiv.style.fontWeight="800";constdifficultySelect=document.createElement("select");["Easy","Moderate","Hard","Extreme"].forEach((level)=>{constoption=document.createElement("option");option.value=level.toLowerCase();option.innerText=level;difficultySelect.appendChild(option);});difficultySelect.style.cssText="border: 2px solid lightgrey; background-color: white; color: #4275f4;"+"padding: 6px;";difficultySelect.onchange=()=>{this.setDifficulty_(difficultySelect.value);this.resetGame_();};constresetDiv=document.createElement("div");resetDiv.innerText="Reset";resetDiv.style.cssText="cursor: pointer; border-top: 1px solid lightgrey; margin-top: 18px;"+"color: #4275f4; line-height: 40px; font-weight: 800";resetDiv.onclick=this.resetGame_.bind(this);menuDiv.appendChild(titleDiv);menuDiv.appendChild(pieceTitleDiv);menuDiv.appendChild(pieceDiv);menuDiv.appendChild(timeTitleDiv);menuDiv.appendChild(timeDiv);menuDiv.appendChild(difficultyTitleDiv);menuDiv.appendChild(difficultySelect);menuDiv.appendChild(resetDiv);this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(menuDiv);}render(){if(!this.dataLoaded_){return;}this.start_();}loadData_(){constxmlhttpRequest=newXMLHttpRequest();xmlhttpRequest.onreadystatechange=()=>{if(xmlhttpRequest.status!=200||xmlhttpRequest.readyState!=XMLHttpRequest.DONE)return;this.loadDataComplete_(JSON.parse(xmlhttpRequest.responseText));};xmlhttpRequest.open("GET","https://storage.googleapis.com/mapsdevsite/json/puzzle.json",true,);xmlhttpRequest.send(null);}loadDataComplete_(data){this.dataLoaded_=true;this.countries_=data;this.start_();}/** * @param {string} difficulty * @private */setDifficulty_(difficulty){this.difficulty_=difficulty;if(this.map_){this.setDifficultyStyle_();}}setDifficultyStyle_(){conststyles={easy:[{stylers:[{visibility:"off"}],},{featureType:"water",stylers:[{visibility:"on"},{color:"#d4d4d4"}],},{featureType:"landscape",stylers:[{visibility:"on"},{color:"#e5e3df"}],},{featureType:"administrative.country",elementType:"labels",stylers:[{visibility:"on"}],},{featureType:"administrative.country",elementType:"geometry",stylers:[{visibility:"on"},{weight:1.3}],},],moderate:[{stylers:[{visibility:"off"}],},{featureType:"water",stylers:[{visibility:"on"},{color:"#d4d4d4"}],},{featureType:"landscape",stylers:[{visibility:"on"},{color:"#e5e3df"}],},{featureType:"administrative.country",elementType:"labels",stylers:[{visibility:"on"}],},],hard:[{stylers:[{visibility:"off"}],},{featureType:"water",stylers:[{visibility:"on"},{color:"#d4d4d4"}],},{featureType:"landscape",stylers:[{visibility:"on"},{color:"#e5e3df"}],},],extreme:[{elementType:"geometry",stylers:[{visibility:"off"}],},],};this.map_.set("styles",styles[this.difficulty_]);}resetGame_(){this.removeCountries_();this.count_=0;this.setCount_();this.startClock_();this.addRandomCountries_();}setCount_(){this.pieceDiv_.innerText=this.count_+" / "+this.NUM_PIECES_;if(this.count_==this.NUM_PIECES_){this.stopClock_();}}stopClock_(){window.clearInterval(this.timer_);}startClock_(){this.stopClock_();consttimeDiv=this.timeDiv_;if(timeDiv)timeDiv.textContent="0.0 seconds";constt=newDate();this.timer_=window.setInterval(()=>{constdiff=newDate().getTime()-t.getTime();if(timeDiv)timeDiv.textContent=(diff/1000).toFixed(2)+" seconds";},100);}addRandomCountries_(){// Shuffle countriesthis.countries_.sort(()=>{returnMath.round(Math.random())-0.5;});constcountries=this.countries_.slice(0,this.NUM_PIECES_);for(leti=0,country;(country=countries[i]);i++){this.addCountry_(country);}}addCountry_(country){constoptions={strokeColor:this.START_COLOR_,strokeOpacity:0.8,strokeWeight:2,fillColor:this.START_COLOR_,fillOpacity:0.35,geodesic:true,map:this.map_,draggable:true,zIndex:2,paths:country.start.map(google.maps.geometry.encoding.decodePath),};constpoly=newgoogle.maps.Polygon(options);google.maps.event.addListener(poly,"dragend",()=>{this.checkPosition_(poly,country);});this.polys_.push(poly);}/** * Checks that every point in the polygon is inside the bounds. */boundsContainsPoly_(bounds,poly){constb=newgoogle.maps.LatLngBounds(newgoogle.maps.LatLng(bounds[0][0],bounds[0][1]),newgoogle.maps.LatLng(bounds[1][0],bounds[1][1]),);constpaths=poly.getPaths().getArray();for(leti=0;i <paths.length;i++){constp=paths[i].getArray();for(letj=0;j <p.length;j++){if(!b.contains(p[j])){returnfalse;}}}returntrue;}/** * Replace a poly with the correct 'end' position of the country. */replacePiece_(poly,country){constoptions={strokeColor:this.END_COLOR_,fillColor:this.END_COLOR_,draggable:false,zIndex:1,paths:country.end.map(google.maps.geometry.encoding.decodePath),};poly.setOptions(options);this.count_++;this.setCount_();}checkPosition_(poly,country){if(this.boundsContainsPoly_(country.bounds,poly)){this.replacePiece_(poly,country);}}start_(){this.setDifficultyStyle_();this.resetGame_();}removeCountries_(){for(leti=0,poly;(poly=this.polys_[i]);i++){poly.setMap(null);}this.polys_=[];}}functioninitMap(){constmap=newgoogle.maps.Map(document.getElementById("map"),{disableDefaultUI:true,center:{lat:10,lng:60},zoom:2,});newPuzzleDemo(map);}window.initMap=initMap;
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
<html> <head> <title>Map Puzzle</title> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <div></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&libraries=geometry&v=weekly" defer ></script> </body></html>
Try Sample
Clone Sample
Git and Node.js are required to run this sample locally. Follow theseinstructions to install Node.js and NPM. The following commands clone, install dependencies and start the sample application.
gitclone-bsample-map-puzzlehttps://github.com/googlemaps/js-samples.gitcdjs-samplesnpminpmstart
Other samples can be tried by switching to any branch beginning withsample-SAMPLE_NAME.
gitcheckoutsample-SAMPLE_NAMEnpminpmstart
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-11-21 UTC.