Skip to content

Instantly share code, notes, and snippets.

@chriswhong
Last active March 9, 2021 19:46
Show Gist options
  • Save chriswhong/ee6a44f8c0b7c3706d4161a408c8ac4f to your computer and use it in GitHub Desktop.
Save chriswhong/ee6a44f8c0b7c3706d4161a408c8ac4f to your computer and use it in GitHub Desktop.
Using mapshaper.js to convert geojson in memory into shapefile download

include zip.js and mapshaper.js

<script src="js/zip.js"></script>
<script src="js/mapshaper.js"></script>

serve deflate.js, inflate.js, and z-worker.js somewhere, and reference them in your code with zip.workerScriptsPath = '{path}', make sure the path ends with a slash!


  //create a mapshaper dataset from geojson FeatureCollection
  var msDataset = mapshaper.internal.importGeoJSON(isochroneFC, {
    auto_snap:false,
    files:['input.json'],
    no_repair:false
  })

  //create an array of ArrayBuffers (one per file in the shapefile)
  var files = mapshaper.internal.exportShapefile(msDataset, {
    format: "shapefile"
  })

  //manually create a .prj file for WGS84
  var crsString = 'GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]'
 
  var buf = new ArrayBuffer(crsString.length*2)
  var bufView = new Uint16Array(buf);

  for (var i=0, strLen=crsString.length; i<strLen; i++) {
    bufView[i] = crsString.charCodeAt(i);
  }

  files.push({
    content: buf,
    filename: '.prj'
  })
  

  saveZipFile('travelsheds.zip',files, function(){
  })

  //combine all files into a zip archive
  //from mapshaper-gui.js
 function saveZipFile(zipfileName, files, done) {
    var toAdd = files;
    try {
      zip.createWriter(new zip.BlobWriter("application/zip"), addFile, zipError);
    } catch(e) {
      // TODO: show proper error message, not alert
      done("This browser doesn't support Zip file creation.");
    }

    function zipError(msg) {
      var str = "Error creating Zip file";
      if (msg) {
        str += ": " + (msg.message || msg);
      }
      done(str);
    }

    function addFile(archive) {
      if (toAdd.length === 0) {
        archive.close(function(blob) {
          saveBlob(zipfileName, blob, done);
        });
      } else {
        var obj = toAdd.pop(),
            blob = new Blob([obj.content], { type: "text/plain" });
        archive.add('travelsheds' + obj.filename, new zip.BlobReader(blob), function() {addFile(archive);});
      }
    }
  }

  //start the download
  function saveBlob(filename, blob, done) {
    //IE11 & Edge
    if (navigator.msSaveBlob) {
        navigator.msSaveBlob(csvData, exportFilename);
    } else {
        //In FF link must be added to DOM to be clicked
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.setAttribute('download', filename);
        document.body.appendChild(link);    
        link.click();
        //document.body.removeChild(link);    
    }
    done();
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment