Data Layer: Drag and Drop GeoJSON Stay organized with collections Save and categorize content based on your preferences.
Page Summary
This example demonstrates how to drag and drop GeoJSON data onto a Google Map to display it.
Users can drag sample GeoJSON files or their own files representing polygons, points, or polylines.
The map automatically adjusts its viewport to fit the bounds of the loaded GeoJSON data.
The sample utilizes the google.maps.Data class for managing and displaying geographical data on the map.
You can download a sample GeoJSON file or clone the entire example code to test it locally.
This example allows you to drag and drop GeoJSON onto the map. Downloadasample GeoJSON file to test dragging from the device.
For more information about how to work with the map data layer, see thegoogle.maps.Data class.
TypeScript
letmap:google.maps.Map;functioninitMap():void{// set up the mapmap=newgoogle.maps.Map(document.getElementById("map")asHTMLElement,{center:newgoogle.maps.LatLng(0,0),zoom:4,});}functionloadGeoJsonString(geoString:string){try{constgeojson=JSON.parse(geoString)asany;map.data.addGeoJson(geojson);}catch(e){alert("Not a GeoJSON file!");}zoom(map);}/** * Update a map's viewport to fit each geometry in a dataset */functionzoom(map:google.maps.Map){constbounds=newgoogle.maps.LatLngBounds();map.data.forEach((feature)=>{constgeometry=feature.getGeometry();if(geometry){processPoints(geometry,bounds.extend,bounds);}});map.fitBounds(bounds);}/** * Process each point in a Geometry, regardless of how deep the points may lie. */functionprocessPoints(geometry:google.maps.LatLng|google.maps.Data.Geometry,callback:any,thisArg:google.maps.LatLngBounds){if(geometryinstanceofgoogle.maps.LatLng){callback.call(thisArg,geometry);}elseif(geometryinstanceofgoogle.maps.Data.Point){callback.call(thisArg,geometry.get());}else{// @ts-ignoregeometry.getArray().forEach((g)=>{processPoints(g,callback,thisArg);});}}/* DOM (drag/drop) functions */functioninitEvents(){[...document.getElementsByClassName("file")].forEach((fileElement)=>{fileElement.addEventListener("dragstart",(e:Event)=>{// @ts-ignoree.dataTransfer.setData("text/plain",JSON.stringify(files[Number((e.targetasHTMLElement).dataset.value)]));console.log(e);},false);});// set up the drag & drop eventsconstmapContainer=document.getElementById("map")asHTMLElement;mapContainer.addEventListener("dragenter",addClassToDropTarget,false);mapContainer.addEventListener("dragover",addClassToDropTarget,false);mapContainer.addEventListener("drop",handleDrop,false);mapContainer.addEventListener("dragleave",removeClassFromDropTarget,false);}functionaddClassToDropTarget(e:Event){e.stopPropagation();e.preventDefault();document.getElementById("map")!.classList.add("over");returnfalse;}functionremoveClassFromDropTarget(e:Event){document.getElementById("map")!.classList.remove("over");}functionhandleDrop(e:DragEvent){e.preventDefault();e.stopPropagation();removeClassFromDropTarget(e);constfiles=(e.dataTransferasDataTransfer).files;if(files.length){// process file(s) being dropped// grab the file data from each filefor(leti=0,file;(file=files[i]);i++){constreader=newFileReader();reader.onload=function(e){loadGeoJsonString(reader.resultasstring);};reader.onerror=function(e){console.error("reading failed");};reader.readAsText(file);}}else{// process non-file (e.g. text or html) content being dropped// grab the plain text version of the dataconstplainText=(e.dataTransferasDataTransfer).getData("text/plain");console.log(plainText);if(plainText){loadGeoJsonString(plainText);}}// prevent drag event from bubbling furtherreturnfalse;}functioninitialize(){initMap();initEvents();}constfiles=[{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:{type:"Polygon",coordinates:[[[-99.49218749999999,-11.867350911459294],[24.960937499999996,-11.867350911459294],[24.960937499999996,47.517200697839414],[-99.49218749999999,47.517200697839414],[-99.49218749999999,-11.867350911459294],],],},},],},{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:{type:"Point",coordinates:[81.2109375,50.064191736659104],},},{type:"Feature",properties:{},geometry:{type:"Point",coordinates:[103.35937499999999,-47.98992166741417],},},{type:"Feature",properties:{},geometry:{type:"Point",coordinates:[-46.05468749999999,64.01449619484472],},},{type:"Feature",properties:{},geometry:{type:"Point",coordinates:[-113.203125,37.996162679728116],},},{type:"Feature",properties:{},geometry:{type:"Point",coordinates:[-73.828125,-32.249974455863295],},},],},{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:{type:"LineString",coordinates:[[147.65625,-5.266007882805485],[118.47656249999999,43.83452678223682],[80.85937499999999,-30.145127183376115],[35.15625,51.83577752045248],[-15.468749999999998,-23.563987128451217],[-29.53125,44.33956524809713],[-73.47656249999999,-32.842673631954305],[-104.765625,35.460669951495305],],},},],},];declareglobal{interfaceWindow{initialize:()=>void;}}window.initialize=initialize;
JavaScript
letmap;functioninitMap(){// set up the mapmap=newgoogle.maps.Map(document.getElementById("map"),{center:newgoogle.maps.LatLng(0,0),zoom:4,});}functionloadGeoJsonString(geoString){try{constgeojson=JSON.parse(geoString);map.data.addGeoJson(geojson);}catch(e){alert("Not a GeoJSON file!");}zoom(map);}/** * Update a map's viewport to fit each geometry in a dataset */functionzoom(map){constbounds=newgoogle.maps.LatLngBounds();map.data.forEach((feature)=>{constgeometry=feature.getGeometry();if(geometry){processPoints(geometry,bounds.extend,bounds);}});map.fitBounds(bounds);}/** * Process each point in a Geometry, regardless of how deep the points may lie. */functionprocessPoints(geometry,callback,thisArg){if(geometryinstanceofgoogle.maps.LatLng){callback.call(thisArg,geometry);}elseif(geometryinstanceofgoogle.maps.Data.Point){callback.call(thisArg,geometry.get());}else{// @ts-ignoregeometry.getArray().forEach((g)=>{processPoints(g,callback,thisArg);});}}/* DOM (drag/drop) functions */functioninitEvents(){[...document.getElementsByClassName("file")].forEach((fileElement)=>{fileElement.addEventListener("dragstart",(e)=>{// @ts-ignoree.dataTransfer.setData("text/plain",JSON.stringify(files[Number(e.target.dataset.value)]),);console.log(e);},false,);});// set up the drag & drop eventsconstmapContainer=document.getElementById("map");mapContainer.addEventListener("dragenter",addClassToDropTarget,false);mapContainer.addEventListener("dragover",addClassToDropTarget,false);mapContainer.addEventListener("drop",handleDrop,false);mapContainer.addEventListener("dragleave",removeClassFromDropTarget,false);}functionaddClassToDropTarget(e){e.stopPropagation();e.preventDefault();document.getElementById("map").classList.add("over");returnfalse;}functionremoveClassFromDropTarget(e){document.getElementById("map").classList.remove("over");}functionhandleDrop(e){e.preventDefault();e.stopPropagation();removeClassFromDropTarget(e);constfiles=e.dataTransfer.files;if(files.length){// process file(s) being dropped// grab the file data from each filefor(leti=0,file;(file=files[i]);i++){constreader=newFileReader();reader.onload=function(e){loadGeoJsonString(reader.result);};reader.onerror=function(e){console.error("reading failed");};reader.readAsText(file);}}else{// process non-file (e.g. text or html) content being dropped// grab the plain text version of the dataconstplainText=e.dataTransfer.getData("text/plain");console.log(plainText);if(plainText){loadGeoJsonString(plainText);}}// prevent drag event from bubbling furtherreturnfalse;}functioninitialize(){initMap();initEvents();}constfiles=[{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:{type:"Polygon",coordinates:[[[-99.49218749999999,-11.867350911459294],[24.960937499999996,-11.867350911459294],[24.960937499999996,47.517200697839414],[-99.49218749999999,47.517200697839414],[-99.49218749999999,-11.867350911459294],],],},},],},{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:{type:"Point",coordinates:[81.2109375,50.064191736659104],},},{type:"Feature",properties:{},geometry:{type:"Point",coordinates:[103.35937499999999,-47.98992166741417],},},{type:"Feature",properties:{},geometry:{type:"Point",coordinates:[-46.05468749999999,64.01449619484472],},},{type:"Feature",properties:{},geometry:{type:"Point",coordinates:[-113.203125,37.996162679728116],},},{type:"Feature",properties:{},geometry:{type:"Point",coordinates:[-73.828125,-32.249974455863295],},},],},{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:{type:"LineString",coordinates:[[147.65625,-5.266007882805485],[118.47656249999999,43.83452678223682],[80.85937499999999,-30.145127183376115],[35.15625,51.83577752045248],[-15.468749999999998,-23.563987128451217],[-29.53125,44.33956524809713],[-73.47656249999999,-32.842673631954305],[-104.765625,35.460669951495305],],},},],},];window.initialize=initialize;
CSS
html{height:100%;}body{height:100%;margin:0;padding:0;overflow:hidden;}#map{height:100%;}#map.over{opacity:0.5;background-color:rgba(100,100,100,0.5);}#sidebar{flex-direction:column;align-items:center;justify-content:center;overflow:auto;}.file{display:flex;flex-flow:column;margin-top:1em;cursor:move;text-align:center;}.file:hover.material-icons{color:darkorange;}.file:hover.filename{font-weight:bold;}.file.material-icons{font-size:50px;color:orange;}.file.material-icons:hover{color:darkorange;}.file.filename{margin-top:0.5em;font-size:20px;color:#333333;}/* Optional: Makes the sample page fill the window. */html,body{height:100%;margin:0;padding:0;}#container{height:100%;display:flex;}#sidebar{flex-basis:15rem;flex-grow:1;padding:1rem;max-width:30rem;height:100%;box-sizing:border-box;overflow:auto;}#map{flex-basis:0;flex-grow:4;height:100%;}
HTML
<html> <head> <title>Data Layer: Drag and Drop GeoJSON</title> <link href="https://unpkg.com/material-components-web@6.0.0/dist/material-components-web.css" rel="stylesheet" /> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" /> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <div> <div></div> <div> <div draggable="true" data-value="0"> <span>text_snippet</span> <div>polygons.geojson</div> </div> <div draggable="true" data-value="1"> <span>text_snippet</span> <div>points.geojson</div> </div> <div draggable="true" data-value="2"> <span>text_snippet</span> <div>polyline.geojson</div> </div> </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=initialize&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-layer-data-dragndrophttps://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-12-18 UTC.