Convert Geojson to Shapefile using shp-write

by Rajkishan Rajappan

HTML

<script src="https://api.mapbox.com/mapbox.js/v2.4.0/mapbox.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox.js/v2.4.0/mapbox.css">
<link rel="stylesheet" href="https://api.mapbox.com/mapbox.js/plugins/leaflet-draw/v0.2.3/leaflet.draw.css">
<script src="https://api.mapbox.com/mapbox.js/plugins/leaflet-draw/v0.2.3/leaflet.draw.js"></script>
<script src="https://unpkg.com/shp-write@latest/shpwrite.js"></script>
<div id="map"></div>
<input type=button id="export" value="Export to Shapefile" />

CSS

/* Map */
 #map {
    height: 300px;
}

input {
  margin-top:10px;
}

JavaScript

L.mapbox.accessToken = 'pk.eyJ1IjoicnJhamFwcGFuIiwiYSI6ImNpb2Jta3prcDA0NGp2emx6M21jbWJkam4ifQ.w2R3ZlYBiKBezxUduz7vTg';
var map = L.mapbox.map('map', 'mapbox.streets')
    .setView([40, -74.50], 9);
		
var featureGroup = L.featureGroup().addTo(map);
		
var drawControl = new L.Control.Draw({
	edit: {
		featureGroup: featureGroup
	},
	draw: {
		polygon: {
			allowIntersection: false
		},
		polyline: false,
		rectangle: false,
		circle: false,
		marker: false
	}
}).addTo(map);

var polygon = new L.Polygon([
          [51.509, -0.08],
          [51.503, -0.06],
          [51.51, -0.047]
      ]);
			
featureGroup.addLayer(polygon);
map.fitBounds(featureGroup.getBounds());

map.on('draw:created', getCoordinates);
map.on('draw:edited', changeCoordinates);

function changeCoordinates(e) {
		featureGroup.eachLayer(function (layer) {
			getCoordinates({ layer: layer });
		});
}

function getCoordinates(e) {
	featureGroup.addLayer(e.layer);
}

var exportShp= function(){
  var shpwrite = require('shp-write');
  // (optional) set names for feature types and zipped folder
  var options = {
    folder: 'shapefile',
    types: {
      point: 'points',
      polygon: 'polygons'
    }
  }
  var fggeojson = featureGroup.toGeoJSON();
  shpwrite.download(fggeojson, options);
};

L.DomEvent.on(document.getElementById("export"), 'click', exportShp);