Skip to content

Using mapshaper programmatically

mbloch edited this page Nov 14, 2014 · 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 [, dataset ], done)

  • commands A command line string or an array of parsed command objects
  • dataset Optional dataset object (see section below on data types)
  • done A Node-style callback: function(Error, dataset)

When the dataset parameter is missing, commands should start with the -i command.

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, json, done)

  • commands A string containing command line arguments
  • json A TopoJSON or GeoJSON dataset as object or string
  • done A Node-style callback: function(Error, data)

Similar to runCommands(), but receives and returns data in GeoJSON or TopoJSON format. The data parameter of the done callback is either a single Geo/TopoJSON object or an array of objects. 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