-
Notifications
You must be signed in to change notification settings - Fork 540
Using mapshaper programmatically
This page is for developers who want to use mapshaper's geoprocessing functions in their own Node applications. Updated for version 0.4.0
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 $@
mapshaper.runCommands(commands, done)
-
commands A command line string or an array of parsed command objects, starting with the
-i
command - done A Node-style callback: function(Error)
// Example: converting a directory of Shapefiles to GeoJSON
var mapshaper = require('mapshaper');
mapshaper.runCommands('-i shapefiles/*.shp -o geojson/ format=geojson');
mapshaper.applyCommands(commands, input, done)
- commands A string containing command line arguments or an array of parsed commands.
-
input JS object containing contents of files referenced by
-i
commands, indexed by file name. - done A Node-style callback: function(Error, output). Output is a JS object containing the contents of generated files, indexed by file name.
applyCommands is similar to runCommands(), but it sends output to a callback instead of writing output files to the filesystem. The content of input files can be passed via the input
parameter. Files not contained in the input
object will be read from the filesystem.
// Example: converting a CSV string to GeoJSON
var csv = 'lat,lng,value\n40.3,-72.3,1000';
var cmd = '-i input.csv -points x=lng y=lat -o output.geojson';
mapshaper.applyCommands(cmd, {'input.csv': csv}, function(err, output) {
var geojson = JSON.parse(output['output.geojson']);
});
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.