Skip to content

Using mapshaper programmatically

Matthew Bloch edited this page Mar 13, 2015 · 20 revisions

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

Option one: use make (or equivalent)

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/mapshaper/bin/mapshaper.

Tip: If you use the -o force flag, mapshaper will overwrite existing files instead of generating unique filenames.

Option two: mapshaper.runCommands()

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, dataset)

Example Convert a directory of Shapefiles to GeoJSON

var mapshaper = require('mapshaper');
mapshaper.runCommands('-i shapefiles/*.shp -o geojson/ format=geojson force');

Option three: mapshaper.applyCommands()

mapshaper.applyCommands(commands, content, done)

  • commands A string containing command line arguments
  • content Contents of a data file; accepts delimited text, Geo/TopoJSON strings or Geo/TopoJSON objects.
  • done A Node-style callback: function(Error, data)

Similar to runCommands(), but receives an input dataset and returns one or more output datasets. The data parameter of the done callback is either a single dataset or an array of datasets. The output format matches the input format, unless overridden by -o format=.

Option four: call individual functions for each command

There is an API function corresponding to each of mapshaper's commands. To see how commands get mapped to functions, see the file mapshaper-run-command.js. It's recommended to use mapshaper.runCommands() or mapshaper.applyCommands() instead of calling a series of API functions.

Data types

The following data types often appear as arguments in mapshaper's API functions.

dataset

Datasets are groups of one or more layers containing arc references to a single ArcCollection. A dataset is an object with the following properties:

  • layers An array of layer objects (see below)
  • arcs (optional) ArcCollection type containing paths for all of the polygon and polygon layers in the dataset
  • info (optional) Metadata about the dataset, collected on file import

layer

Layers are objects with the following properties:

  • name (optional)
  • geometry_type supported types: "polygon", "polyline", "point"
  • shapes Array of geometry data for each feature.
  • data (optional) DataTable object containing attribute data for each feature
Clone this wiki locally