Skip to content

Using mapshaper programmatically

Matthew Bloch edited this page Jul 31, 2019 · 20 revisions

This page is for developers who want to use mapshaper's geoprocessing functions in their own Node applications. Updated for version 0.4.125

Option One: make

One way of scripting mapshaper is to call the mapshaper command line program from make or other build tool.

If you include mapshaper as a dependency in the package.json file of a Node.js project, the executable program can be found at this path: node_modules/.bin/mapshaper.

Here's an example Makefile target:

europe.json: shp/europe.shp
	mapshaper snap $< encoding=utf8  \
	-rename-layers countries \
	-filter "CONTINENT == 'Europe'" \
	-simplify 15% keep-shapes \
	-o format=topojson $@

Option Two: runCommands()

mapshaper.runCommands(commands[, input][, callback])

  • commands A command line string or an array of parsed command objects, starting with the -i command
  • input An optional JS object containing contents of files referenced by -i commands, indexed by file name. Input files are read from the filesystem if they are not present in the input argument.
  • callback An optional Node-style callback: function(Error). If called without a callback, runCommands() returns a Promise.
// Example: converting a directory of Shapefiles to GeoJSON
var mapshaper = require('mapshaper');
mapshaper.runCommands('-i shapefiles/*.shp -o geojson/ format=geojson');

Option Three: applyCommands()

mapshaper.applyCommands(commands[, input][, callback])

This function has the same signature as runCommands(). Instead of writing files generated by -o commands, mapshaper passes the contents of output files to the callback (or Promise if a callback is not provided). File contents are placed in a JavaScript object and indexed by filename.

// Example: converting a CSV string to GeoJSON
const input = {'input.csv': 'lat,lng,value\n40.3,-72.3,1000'};
const cmd = '-i input.csv -points x=lng y=lat -o output.geojson';

// using Promise
const output = await mapshaper.applyCommands(cmd, input);

// using callback
mapshaper.applyCommands(cmd, input, function(err, output) {
	// do something
});

Note on importing Shapefiles: To input a Shapefile using applyCommands(), in addition to passing the contents of the .shp file (as a Buffer or ArrayBuffer), you'll probably want to pass the .dbf file (as a Buffer or ArrayBuffer) and the .prj file (as a string). The .dbf file contains attribute data and the .prj file contains coordinate system data.

Clone this wiki locally