Skip to content

Command Reference

Matthew Bloch edited this page Dec 24, 2018 · 76 revisions

This documentation applies to version 0.4.100 of mapshaper's command line program. Run mapshaper -v to check your version. For an introduction to the command line tool, read this page first.

Command line syntax

Mapshaper takes a list of commands and runs them in sequence. A command consists of the name of a command, prefixed by a hyphen, followed by options for the command. The initial import command -i can be omitted. Example:

# Read a Shapefile, simplify using Douglas-Peucker, output as GeoJSON
mapshaper provinces.shp -simplify dp 20% -o format=geojson out.json

Command options can take three forms:

  • Values, like provinces.shp and 20% in the above example

  • Flags, like dp

  • Name/value pairs, like format=geojson

Index of commands

File I/O

-i (input) -o (output)

Editing

-affine -clean -clip -colorizer -dissolve -dissolve2 -drop -each -erase -explode -filter -filter-fields -filter-islands -filter-slivers -graticule -include -innerlines -join -lines -merge-layers -point-grid -points -polygons -proj -rectangle -rename-fields -rename-layers -require -run -shape -simplify -sort -split -split-on-grid -subdivide -style -target -uniq

Information

-calc -encodings -help -info -inspect -projections -quiet -verbose -version

Common options

These options are used by multiple commands

name= Rename the layer (or layers) modified by a command.

target= Specify the layer or layers targeted by a command. Takes the name of a layer, the number of a layer (first layer is 1), or a comma-separated list of layer names or numbers. Names may contain the * wildcard.

+ Use the output of a command to create a new layer or layers instead of replacing the target layer(s). Use together with the name= option to assign a name to the new layer(s).

-i (input)

Input one or more files in Shapefile, JSON, DBF or delimited text format.

The -i command is assumed if mapshaper is followed by an input filename.

JSON files can be GeoJSON, TopoJSON, or an array of data records.

Each named geometry object of a TopoJSON input file is imported as a separate layer.

Mapshaper does not fully support M and Z type Shapefiles. The M and Z data is lost when these files are imported.

By default, multiple input files are processed separately, as if running mapshaper multiple times with the same set of commands. combine-files and merge-files change this behavior.

Options

<files> or files= File(s) to input (space-separated list). Use - to import TopoJSON or GeoJSON from /dev/stdin.

combine-files Import multiple files to separate layers with shared topology. Useful for generating a single TopoJSON file containing multiple geometry objects.

merge-files (Deprecated) Merge features from multiple input files into as few layers as possible. Preferred method: import files to separate layers using -i combine-files, then use the -merge-layers command to merge layers.

snap Snap together vertices within a small distance threshold. This option is intended to fix minor coordinate misalignments in adjacent polygons. The snapping distance is 0.0025 of the average segment length.

snap-interval= Specify snapping distance in source units.

precision= (Deprecated) Round all coordinates to a specified precision, e.g. 0.001. It is recommended to set coordinate precision on export, using -o precision=.

no-topology Skip topology identification to speed up processing of large files. For use with commands like -filter that don't require topology.

encoding= Specify encoding used for reading .dbf files and delimited text files. If the encoding option is missing, mapshaper will try to detect the encoding of .dbf files. Dbf encoding can also be set using a .cpg file.

id-field= (Topo/GeoJSON) Import values of "id" property to this data field.

field-types= Type hints for importing delimited text. Takes a comma-separated list of field names with type hints appended; e.g. FIPS:str,zipcode:str. Recognized type hints include :str or :string, :num or :number. Without a type hint, fields containing text data that looks like numeric data, like ZIP Codes, will be converted to numbers.

csv-fields= Comma-sep. list of fields to import from a CSV-formatted input file. Fields are filtered as the file is read, which reduces the memory needed to import very large CSV files.

csv-filter= A JavaScript expression for importing a subset of the records in a CSV file. Records are filtered as the file is read, which reduces the memory needed to import very large CSV files.

name= Rename the imported layer (or layers).

Example

# Input a Shapefile with text data in the latin1 encoding and see what kind of data it contains
mapshaper countries_wgs84.shp encoding=latin1 -info

-o (output)

Save edited content to a file or files. By default, Mapshaper appends a suffix to output files if it detects a naming conflict, to avoid overwriting existing files.

Options

<file>|<directory>|- Name of output file or directory. Use - to export text-based formats to /dev/stdout.

format=shapefile|geojson|topojson|json|dbf|csv|tsv|svg Specify output format. If the format= option is missing, Mapshaper tries to infer the format from the output filename. If no filename is given, Mapshaper uses the input format. The json format is an array of objects containing data properties for each feature.

target= Specify layer(s) to export (comma-separated list). The default target is the output layer(s) of the previous command. Use target=* to select all layers.

force Allow output files to overwrite input files (without this option, overwriting input files is not allowed).

cut-table Detach attribute data from shapes and save as a JSON file.

drop-table Remove attribute data from output.

precision= Round all coordinates to a specified precision, e.g. precision=0.001. Useful for reducing the size of GeoJSON files.

bbox-index Export a JSON file containing bounding boxes of each output layer.

encoding= (Shapefile/CSV) Encoding of input text (by default, Shapefile encoding is auto-detected and CSV files are assumed to be UTF-8).

field-order= (Shapefile/CSV) field-order=ascending sorts data fields in alphabetical order of field names (A-Z, case-insensitive).

id-field= (Topo/GeoJSON/SVG) Specify one or more data fields to use as the "id" property of GeoJSON, TopoJSON or SVG features (comma-separated list). When exporting multiple layers, you can pass a list of field names. The first listed name that is present in a layer's attribute table will be used as the id field for that layer.

bbox (Topo/GeoJSON) Add bbox property to the top-level object.

extension= (Topo/GeoJSON) set file extension (default is ".json").

prettify (Topo/GeoJSON) Format output for readability.

singles (TopoJSON) Save each output layer as a separate file. Each output file and the TopoJSON object that it contains are named after the corresponding data layer.

quantization= (TopoJSON) Specify quantization as the maximum number of differentiable points along either dimension. Equivalent to the --q1/--post-quantization option of Mike Bostock's topojson program. By default, mapshaper applies quantization equivalent to 0.02 of the average segment length.

no-quantization (TopoJSON) Arc coordinates are encoded at full precision and without delta-encoding.

presimplify (TopoJSON) Add a threshold value to each arc vertex in the z position (i.e. [x, y, z]). Useful for dynamically simplifying paths using vertex filtering. Given W as the width of the map viewport in pixels, S as the ratio of content width to viewport width, and pz as the presimplify value of a point, the following expression tests if the point should be excluded from the output path: pz > 0 && pz < 10000 / (W * S).

topojson-precision= (TopoJSON) Set quantization as a fraction of the average segment length.

rfc7946 (GeoJSON) Generate RFC 7946-compatible GeoJSON: default 6-decimal precision, CCW outer-ring winding order, antimeridian-spanning bbox. A warning is printed if the output CRS is not WGS84.

combine-layers (GeoJSON) Combine multiple output layers into a single GeoJSON file.

geojson-type= (GeoJSON) Overrides the default output type. Possible values: "FeatureCollection", "GeometryCollection", "Feature" (for a single feature).

width= (SVG/TopoJSON) Set the width of the output dataset in pixels. When used with TopoJSON output, this option switches the output coordinates from geographic units to pixels and flips the Y axis. SVG output is always in pixels (default SVG width is 800).

height= (SVG/TopoJSON) Similar to the width option. If both height and width are set, content is centered inside the [0, 0, width, height] bounding box.

max-height= (SVG/TopoJSON) Limit output height (units: pixels).

margin= (SVG/TopoJSON) Set the margin between coordinate data and the edge of the viewport (default is 1). To assign different margins to each side, pass a list of values in the order <left,bottom,right,top> (similar to the bbox= option found in other commands).

pixels= (SVG/TopoJSON) Output area in pixels (alternative to width=).

id-prefix= Prefix for namespacing layer and feature ids.

svg-scale= (SVG) Scale SVG output using geographical units per pixel (an alternative to the width= option).

point-symbol=square (SVG) Use squares instead of circles to symbolize point data.

delimiter= (CSV) Set the field delimiter for CSV/delimited text output; e.g. delimiter=|.

Example

# Convert all the Shapefiles in one directory into GeoJSON files in a different directory.
mapshaper shapefiles/*.shp -o geojson/ format=geojson

-affine

Transform coordinates by shifting, scaling and rotating. Not recommended for unprojected datasets.

shift= X,Y shift in source units (e.g. 5000,-5000)

scale= Scale (default is 1)

rotate= Angle of rotation in degrees (default is 0)

anchor= Center of rotation/scaling (default is center of the bounding box of the selected content)

where= Use a JS expression to select a subset of features.

Common options: target=

-clean

Repair overlaps and fill small gaps between adjacent polygons. Only gaps that are completely enclosed can be filled. Areas that are contained by more than one polygon (overlaps) are assigned to the polygon with the largest area. Similarly, gaps are assigned to the largest-area polygon. This rule may give undesired results and will likely change in the future.

min-gap-area= Gaps smaller than this area will be filled; larger gaps will be retained as holes in the polygon mosaic. Uses projected units or square meters if the dataset is unprojected. Defaults to a small value.

snap-interval= Snap vertices within a given threshold before detecting gaps and overlaps. Defaults to a very small threshold. Uses source units.

allow-empty Allow null geometries, which are removed by default.

Common options: target=

-clip

Remove features or portions of features that fall outside a clipping area.

<source> or source= Clip to a set of polygon features. Takes the filename or layer id of the clip polygons.

bbox=<xmin,ymin,xmax,ymax> Delete features or portions of features that fall outside a bounding box.

remove-slivers Remove tiny sliver polygons created by clipping.

Common options: name + target

# Example: Clip a polygon layer using another polygon layer.
mapshaper usa_counties.shp -clip land-area.shp -o clipped.shp

-colorizer

Define a function for converting data values to colors that can be used in subsequent calls to the -style command.

name= Name of the colorizer function.

colors= List of CSS colors.

breaks= Ascending-order list of breaks (thresholds) for creating a sequential color scheme.

categories= List of data values (keys) for creating a categorical color scheme.

other= Default color for categorical scheme (defaults to nodata color).

nodata= Color to use for invalid or missing data (default is white).

precision= Rounding precision to apply to numerical data before converting to a color (e.g. 0.1).

# Example: define a function for a sequential color scheme and assign colors based on data values
mapshaper data.json \
	-colorizer name=getColor colors='#f0f9e8,#bae4bc,#7bccc4,#2b8cbe' breaks=25,50,75 \
	-each 'color = getColor(PCT)' \
	-o output.json

# Example: define a function for a categorical color scheme and use it to assign fill colors
mapshaper data.json \
	-colorizer name=calcFill colors='red,blue,green' categories='Republican,Democrat,Other' \
	-style fill='calcFill(PARTY)' \
	-o output.svg

-dissolve

Aggregate groups of features using a data field, or aggregate all features if no field is given. For polygon layers, -dissolve merges adjacent polygons by erasing shared boundaries. For point layers, -dissolve replaces a group of points with their centroid. For polyline layers, -dissolve tries to merge contiguous polylines into as few polylines as possible.

<fields> Name of a data field or fields to dissolve on. Accepts a comma-separated list of field names.

weight= [points] Name of a field or a JS expression for generating weighted centroids. For example, the following command estimates the "center of mass" of the U.S. population: mapshaper census_tracts.shp -points -dissolve weight=POPULATION -o out.shp

planar [points] Treat decimal degree coordinates as planar cartesian coordinates when calculating dissolve centroids. (By default, mapshaper calculates the centroids of lat-long point data in 3D space.)

calc= Use built-in JavaScript functions to create data fields in the dissolved layer. See example below; see -calc for a list of supported functions.

sum-fields= Fields to sum when dissolving (comma-sep. list).

copy-fields= Fields to copy when dissolving (comma-sep. list). Copies values from the first feature in each group of dissolved features.

Common options: name= + target=

# Example: Aggregate county polygons to states
mapshaper counties.shp -dissolve STATE -o states.shp

# Example: Use the calc= option to count the number of dissolved features and perform other calculations
mapshaper counties.shp -dissolve STATE calc='n = count(), total_pop = sum(POP), max_pop = max(POP), min_pop = min(POP)'

-dissolve2

(Experimental) Similar to -dissolve, but able to dissolve overlapping polygons as well as adjacent polygons.

Options: <fields> calc= sum-fields= copy-fields= name= + target=

-drop

Delete the target layer(s) or elements within the target layer(s).

fields= Delete a (comma-separated) list of attribute data fields. To delete all fields, use fields=*.

geometry Delete all geometry.

target= Layer(s) to target.

-each

Apply a JavaScript expression to each feature in a layer. Data properties are available as local variables. Additional feature-level properties are available as read-only properties of the this object.

Tip: Enclose JS expressions in single quotes when using the bash shell (Mac and Linux) to avoid shell expansion of "!" and other special characters. Using the Windows command interpreter, enclose JS expressions in double quotes.

<expression> or expression= JavaScript expression to apply to each feature.

where= Secondary boolean JS expression for targetting a subset of features.

target= Layer to target.

Properties of this Properties are read-only unless otherwise indicated.

All layer types

  • this.id Numerical id of the feature (0-based)
  • this.properties Data properties (also available as local variables) (read/write)

Point layers

  • this.coordinates An array of [x, y] coordinates with one or more members, or null (read/write)
  • this.x X-coordinate of point, or null if geometry is empty. Refers to the first point of multi-point features. (read/write)
  • this.y Y-coordinate of point or null. (read/write)

Polygon layers

  • this.area Area of polygon feature, after any simplification is applied. For lat-long datasets, returns area on a sphere in units of square meters.
  • this.planarArea Calculates the planar area of lat-long datasets, as though latitude and longitude were cartesian coordinates.
  • this.originalArea Area of polygon feature without simplification
  • this.centroidX X-coord of centroid
  • this.centroidY Y-coord of centroid
  • this.innerX X-coord of an interior point (for anchoring symbols or labels)
  • this.innerY Y-coord of an interior point

Polygon and polyline layers

  • this.partCount 1 for single-part features, >1 for multi-part features, 0 for null features
  • this.isNull True if feature has null geometry
  • this.bounds Bounding box as array [xmin, ymin, xmax, ymax]
  • this.width Width of bounding box
  • this.height Height of bounding box

Note: Centroids are calculated for the largest ring of multi-part polygons, and do not account for holes.

Note: Geometric properties are calculated using planar geometry, except for the area of unprojected polygons, which is calculated using spherical geometry in units of square meters.

Examples

# Create two fields
mapshaper counties.shp -each 'STATE_FIPS=COUNTY_FIPS.substr(0, 2), AREA=this.area' -o out.shp

# Delete two fields
mapshaper states.shp -each 'delete STATE_NAME, delete GEOID' -o out.shp

# Rename a field
mapshaper states.shp -each 'STATE_NAME=NAME, delete NAME' -o out.shp

# Print the value of a field to the console
mapshaper states.shp -each 'console.log(NAME)'

# Assign a new data record to each feature
mapshaper states.shp -each 'this.properties = {FID: this.id}' -o out.shp

-erase

Remove features or portions of features that fall inside an area.

<source> or source= File or layer containing erase polygons. Takes the filename or layer id of the erase polygons.

bbox=<xmin,ymin,xmax,ymax> Delete features or portions of features that fall inside a bounding box. Similar to -clip bbox=.

remove-slivers Remove tiny sliver polygons created by erasing.

Common options: name + target

# Example: Erase a polygon layer using another polygon layer.
mapshaper usa_counties.shp -erase lakes.shp -o out.shp

-explode

Divide each multi-part feature into several single-part features.

Common options: target=

-filter

Apply a boolean JavaScript expression to each feature, removing features that evaluate to false.

<expression> or expression= JS expression evaluating to true or false. Uses the same execution context as -each.

remove-empty Delete features with null geometry. May be used by itself or in combination with an <expression>.

Common options: name + target

# Example: Select counties from New England states
mapshaper usa_counties.shp -filter '"ME,VT,NH,MA,CT,RI".indexOf(STATE) > -1' -o ne_counties.shp

-filter-fields

Delete fields in an attribute table.

<fields> or fields= Comma-separated list of data fields to retain.

Common options: target=

# Example: Retain two fields
mapshaper states.shp -filter-fields FID,NAME -o out.shp

-filter-islands

Remove small detached polygon rings (islands).

min-area= Remove low-area islands.

min-vertices= Remove low-vertex-count islands.

remove-empty Delete features with null geometry.

target

-filter-slivers

Remove small polygon rings.

min-area= Area threshold for removal.

remove-empty Delete features with null geometry.

target

-graticule

Create a graticule layer appropriate for a world map centered on longitude 0

-include

<file> or file= Path to the external .js file to load. The file should contain a single JS object. The properties of this object are converted to variables in the JS expression used by the -each command.

-innerlines

Create a polyline layer consisting of shared boundaries with no attribute data.

where= Filter lines using a JS expression (see the -lines where= option).

Other options: name= + target=

# Example: Extract the boundary between two states.
mapshaper states.shp -filter 'STATE=="OR" || STATE=="WA"' -innerlines -o out.shp

-join

Join attribute data from a source layer or file to a target layer. If the keys= option is used, Mapshaper will join records by matching the values of key fields. If the keys= option is missing, Mapshaper will perform a point-to-polygon, polygon-to-point or point-to-point spatial join.

<file|layer> or source= File or layer containing data records to join.

keys= Names of two fields to use as join keys, separated by a comma. The key field from the destination table is followed by the key field from the source table. If the keys= option is missing, mapshaper performs a spatial join.

calc= Use JS assignments and built-in functions to convert values from the source table to (new) fields the target table. See the -calc command reference for a list of supported functions. Useful for handling many-to-one joins. See example below.

where= Use a boolean JS expression to filter records from the source table. The expression has the same syntax as the expression used by the -filter command. The functions isMax(<field>) isMin(<field>) and isMode(<field>) can be used in many-to-one joins to select among source records.

fields= A comma-separated list of fields to copy from the external table. If the fields option is absent, all fields are copied except the key field (if joining on keys). Use fields=* to copy all fields, including any key field. Use fields= (empty list) to copy no fields.

sum-fields= A comma-separated list of fields to sum when several source records match the same target record. This option is equivalent to using the sum() function inside a calc= expression like this: calc='FIELD = sum(FIELD)'.

field-types= A comma-separated list of type hints (when joining a CSV file or other delimited text file). See -i field-types= above.

force Allow values in the target data table to be overwritten by values in the source table when both tables contain identically named fields.

unjoined Copy unjoined records from the source table to a layer named "unjoined".

unmatched Copy unmatched records from the destination table to a layer named "unmatched".

Other options: encoding= target=

Examples

Join a point layer to a polygon layer (spatial join), using the calc= option to handle many-to-one matches.

mapshaper states.shp -join points.shp calc='median_score = median(SCORE), mean_score = average(SCORE), join_count = count()' -o out.shp

Copy data from a csv file to the attribute table of a Shapefile by matching values from the STATE_FIPS field of the Shapefile and the FIPS field of the csv file. (The ':str' suffix prevents FIPS codes from being converted to numbers.)

mapshaper states.shp -join demographics.txt keys=STATE_FIPS,FIPS:str -o out.shp

-lines

Convert polygons to topological boundaries. Without the <fields> argument, external (unshared) boundaries are attributed as TYPE: "outer", RANK: 0 and internal (shared) boundaries are TYPE: "inner", RANK: 1.

<fields> or fields= (Optional) comma-separated list of attribute fields. A single field name adds an intermediate level of hierarchy with attributes: TYPE: <field name>, RANK: 1, and the lowest-level internal boundaries are given attributes TYPE: "outer", RANK: 2. A comma-separated list of fields adds additional levels of hierarchy.

where= Use a JS expression for filtering lines using properties of adjacent polygons. The expression context has objects named A and B, which represent features on eather side of a path. B is null if a path only belongs to a single feature.

each= Apply a JS expression to each line (using A and B, like the where= option).

Common options: name= + target=

# Example: Classify national, state and county boundaries.
mapshaper counties.shp -lines STATE_FIPS -o boundaries.shp

-merge-layers

Merge features from several layers into a single layer. Layers can only be merged if they have compatible geometry types and attribute fields (unless the force option is used).

force Allow merging layers with inconsistent fields. When a layer is missing a particular field, the field will be added, with the values set to undefined. Using this option, you are still prevented from merging fields with different data types (e.g. a field containing numbers in one layer and strings in another). You are also still prevented from merging layers containing different geometry types. ff Common options: name= target=

# Example: Combine features from several Shapefiles into a single Shapefile.
# -i combine-files is used because files are processed separately by default.
mapshaper -i OR.shp WA.shp CA.shp AK.shp combine-files \
	-merge-layers \
	-o pacific_states.shp

-point-grid

Create a rectangular grid of points.

<cols,rows> Size of the grid, e.g. -point-grid 100,100.

interval= Distance between adjacent points, in source units (alternative to setting the number of cols and rows).

bbox= Fit the grid to a bounding box (xmin,ymin,xmax,ymax). Defaults to the bounding box of the other data layers, or of the world if no other layers are present.

name= Set the name of the point grid layer

-points

Create a point layer, either from polygon or polyline geometry or from values in the attribute table. By default, polygon features are replaced by a single point located at the centroid of the polygon ring, or the largest ring of a multipart polygon. By default, polyline features are replaced by a single point located at the polyline vertex that is closest to the center of the feature's bounding box (this can be used to join polylines to polygons using a point-to-polygon spatial join).

x= Name of field containing x coordinate values.

y= Name of field containing y coordinate values.

centroid Create points at the centroid of the largest ring of each polygon feature. Point placement is currrently not affected by holes.

inner Create points in the interior of the largest ring of each polygon feature. Inner points are located away from polygon boundaries.

vertices Convert polygon and polyline features into point features containing the unique vertices in each shape.

endpoints Capture the unique endpoints of polygon and polyline arcs.

interpolated Interpolate points along polylines. Requires the interval= option to be set. Original vertices are replaced by interpolated vertices.

interval= Distance between interpolated points (in meters if coordinates are unprojected, or projected units).

Common options: name= + target=

# Example: Create points in the interior of each polygon 
mapshaper counties.shp -points inner -o points.shp

# Example: Create points in the interior of each polygon (alternate method) 
mapshaper counties.shp -each 'cx=this.innerX, cy=this.innerY' -points x=cx y=cy -o points.shp

-polygons

Convert a polyline layer to a polygon layer by linking together intersecting polylines to form rings.

gap-tolerance= Close gaps ("undershoots") between polylines up to the distance specified by this option.

Common options: target=

-proj

Project a dataset using a Proj.4 string or alias. This command affects all layers in the dataset(s) containing the targeted layer or layers.

<crs> or crs= Target CRS, given as a Proj.4 definition or an alias. Use the -projections command to list available projections and aliases.

densify Interpolate vertices along long line segments as needed to approximate curved lines.

match= Match the projection of the given layer or .prj file.

from= Define the pre-projected coordinate system, if unknown. This option is not needed if the source coordinate system is defined by a .prj file, or if the source CS is WGS84.

target= Layer(s) to target. All layers belonging to the same dataset as a targeted layer will be reprojected. To reproject all datasets, use target=*.

Examples

# Convert a GeoJSON file to New York Long Island state plane CRS, using a Proj.4 string
mapshaper nyc.json -proj +proj=lcc +lat_1=41.03333333333333 +lat_2=40.66666666666666 \
+lat_0=40.16666666666666 +lon_0=-74 +x_0=300000 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m \
-o out.json

# Apply the same projection using an EPSG code
mapshaper nyc.json -proj +init=EPSG:2831 -o out.json

# Convert an unprojected U.S. Shapefile into a composite projection with Alaska
# and Hawaii repositioned and rescaled to fit in the lower left corner.
mapshaper us_states.shp -proj albersusa -o out.shp

# Convert a projected Shapefile to WGS84 coordinates
mapshaper area.shp -proj wgs84 -o out.shp

-rectangle

Create a new layer containing a rectangular polygon.

bbox=<xmin,ymin,xmax,ymax> Give the coordinates of the rectangle.

source= Create a bounding box around a given layer.

offset= Expand the sides of the rectangle by this amount.

name= Assign a name to the newly created layer.

-rename-fields

Rename data fields. To rename a field from A to B, use the assignment operator: B=A.

<fields> or fields= List of fields to rename as a comma-separated list.

Common options: target=

# Example: rename STATE_FIPS to FIPS and STATE_NAME to NAME
mapshaper states.shp -rename-fields FIPS=STATE_FIPS,NAME=STATE_NAME -o out.shp

-rename-layers

Assign new names to layers. If fewer names are given than there are layers, the last name in the list is repeated with numbers appended (e.g. layer1, layer2).

<names> or names= One or more layer names (comma-separated).

target= Rename a subset of all layers.

# Example: Create a TopoJSON file with sensible object names.
mapshaper ne_50m_rivers_lake_centerlines.shp ne_50m_land.shp combine-files \
  -rename-layers water,land -o target=* layers.topojson 

-require

Require a Node module for use in commands like -each and -run. Required modules are added to the expression context. Named expressions are accessed via thair names or aliases. Unnamed modules have their exported properties added to the expression context.

<module> or module= Name of a Node module or path to a module file.

alias= Use an alias for a named module or module file.

init= JS expression to run after the module loads.

# Example: use the underscore module
$ mapshaper data.json \
	-require underscore alias=_ \
	-each 'id = _.uniqueId()' \
	-o data.json force

-run

Create mapshaper commands on-the-fly and run them.

<commands> or commands= A JS expression for generating one or more mapshaper commands. The expression has access to a "target" object with information about the currently targeted layer, as well as modules loaded with the -require command.

Common options: target=

Example: Apply a custom projection based on the layer extent

$ mapshaper -i country.shp -require projection.js -run 'getProjCommand(target)' -o
// contents of projection.js file
module.exports = {
	getProjCommand: function(target) {
		var clon = (target.bbox[0] + target.bbox[2]) / 2,
			clat = (target.bbox[1] + target.bbox[3]) / 2;
		return `-proj +proj=tmerc lat_0=${clat} lon_0=${clon}`;
	}
};

-shape

Create a new layer containing a single polyline or polygon shape.

coordinates=<x,y,...> Specify vertex coordinates as a comma-separated list.

offsets=<dx,dy,...> Specify vertex coordinates as a list of offsets from the previous vertex. The first vertex in the list is offset from the last coordinate in the coordinates= list.

closed Close an open path to form a polygon shape.

name= Assign a name to the newly created layer.

-simplify

Mapshaper supports Douglas-Peucker simplification and two kinds of Visvalingam simplification.

Douglas-Peucker (a.k.a. Ramer-Douglas-Peucker) produces simplified lines that remain within a specified distance of the original line. It is effective for thinning dense vertices but tends to form spikes at high simplification.

Visvalingam simplification iteratively removes the least important point from a polyline. The importance of points is measured using a metric based on the geometry of the triangle formed by each non-endpoint vertex and the two neighboring vertices. The visvalingam option uses the "effective area" metric — points forming smaller-area triangles are removed first.

Mapshaper's default simplification method uses Visvalingam simplification but weights the effective area of each point so that smaller-angle vertices are preferentially removed, resulting in a smoother appearance.

When working with multiple polygon and polyline layers, the -simplify command is applied to all of the layers.

Options

<percentage> or percentage= Percentage of removable points to retain. Accepts values in the range 0%-100% or 0-1.

dp rdp Use Douglas-Peucker simplification.

visvalingam Use Visvalingam simplification with the "effective area" metric.

weighted Use weighted Visvalingam simplification (this is the default). Points located at the vertex of more acute angles are preferentially removed, for a smoother appearance.

weighting= Coefficient for weighting Visvalingam simplification (default is 0.7). Higher values produce smoother output. weighting=0 is equivalent to unweighted Visvalingam simplification.

resolution= Use an output resolution (e.g. 1000x800) to control the amount of simplification.

interval= Specify simplification amount in units of distance. Uses meters when simplifying unprojected datasets in 3D space (see planar option below), otherwise uses the same units as the source data.

variable Apply a variable amount of simplification to the paths in a polygon or polygon layer. This flag changes the interval=, percentage= and resolution= options to accept JavaScript expressions instead of literal values. (See the -each command for information on mapshaper JS expressions).

planar By default, mapshaper simplifies decimal degree coordinates in 3D space (using geocentric x,y,z coordinates). The planar option treats lng,lat coordinates as x,y coordinates on a Cartesian plane.

keep-shapes Prevent polygon features from disappearing at high simplification. For multipart features, mapshaper preserves the part with the largest original bounding box.

no-repair By default, mapshaper rolls back simplification along pairs of intersecting line segments by re-introducing removed points until either the intersection disappears or there are no more points to add. This option disables intersection repair.

stats Display summary statistics relating to the geometry of simplified paths.

Examples

# Simplify counties.shp using the default algorithm, retaining 10% of removable vertices.
mapshaper counties.shp -simplify 10% -o simplified.shp

# Use Douglas-Peucker simplification with a 100 meter threshold.
mapshaper states.shp -simplify dp interval=100 -o simplified/

-sort

Sort features in a data layer using a JavaScript expression.

<expression> or expression= Apply a JavaScript expression to each feature, using the resulting values for sorting the features. Uses the same execution environment as -each.

ascending Sort in ascending order (this is the default).

descending Sort in descending order.

target

-split

Distributes features in the target layer into multiple output layers based on the values in a data field. If no data field is supplied, features are split into individual layers.

<field> or field= Name of the attribute field to split on.

Common options: + target=

Examples

# Split features from a named layer into new GeoJSON files using a data field.
# Output names use the original layer name + data values,
# e.g. states-AK.json, states-AL.json, etc.
mapshaper states.shp -split STATE -o format=geojson

# Split features from an unnamed layer into new GeoJSON files using a data field.
# Output names contain data values,
# e.g. AK.json, AL.json, etc.
mapshaper states.shp name='' -split STATE -o format=geojson

# Split source features into individual GeoJSON files (no data field supplied).
# Output names use source layer name + ascending number,
# e.g. states-1.json, states-2.json, etc.
mapshaper states.shp -split -o format=geojson

-split-on-grid

Split features into separate layers using a grid of cols,rows cells. Useful for dividing a large dataset into smaller files that can be loaded dynamically into an interactive map. Use -o bbox-index to export a file containing the name and bounding box of the shapes in each file. Empty cells are removed from the output.

<cols,rows> Size of the grid, e.g. -split-on-grid 12,10

Common options: target=

-subdivide

Recursively divide a layer using a boolean JS expression. The expression is first evaluated against all features in the layer. If true, the features are spatially partitioned either vertically or horizontally, according to whether the aggregate bounding box is relatively tall or wide. See example below.

Subdivide expressions can call several functions that operate on a group of features. The sum() function takes a feature-level expression as an argument and returns the summed result after applying the expression to each feature in the group. Similar functions include min() max() average() and median().

<expression> or expression= Boolean JavaScript expression

Common options: target=

Example

# Aggregate census tracts into groups of less than 1,000,000 population and less than 100 sq km in area.
mapshaper tracts.shp
  -subdivide "sum('POPULATION') >= 1000000 && sum('this.area') > 1e8" \
  -dissolve sum-fields=POPULATION \
  -merge-layers \
  -o tract_groups.shp

-style

Add common SVG attributes for SVG export and display in the web UI. Attribute values take either a literal value or a JS expression. See the -each command for help with expressions. This command was named -svg-style in earlier versions of mapshaper.

where= Boolean JS expression for targetting a subset of features.

class= One or more CSS classes, separated by spaces (e.g. class="light semi-transparent")

fill= Fill color (e.g. #eee pink rgba(0, 0, 0, 0.2))

stroke= Stroke color

stroke-width= Stroke width

stroke-dasharray= Dashes

opacity= Symbol opacity (e.g. opacity=0.5)

r= Circle radius. Setting this exports points as SVG <circle> symbols, unless the -o point-symbol=square option is used.

label-text= Label text (set this to export points as labels). To create multiline labels, insert line delimiters into the label text. There are three possible line delimiters: the newline character, \n (underscore + "n"), and <br>.

text-anchor= Horizontal justification of label text. Possible values are: start, end or middle (the default).

dx= X offset of labels (default is 0)

dy= Y offset of labels (default is baseline-aligned)

font-size= Size of label text (default is 12)

font-family= CSS font family of labels (default is sans-serif)

font-weight= CSS font weight property of labels (e.g. bold, 700)

font-style= CSS font style property of labels (e.g. italic)

letter-spacing= CSS letter-spacing property of labels

line-height= Line spacing of multi-line labels (default is 1.1em). Lines are separated by newline characters in the label text.

Common options: target=

Example

# Apply a 2px grey stroke and no fill to a polygon layer
mapshaper polygons.geojson \
-style fill=none stroke='#aaa' stroke-width=2 \
-o out.svg

-target

Set default target layer

<target> or target= Name or id of a layer (first layer is 1).

type= Type of layer(s) to match (polygon, polyline or point). This is useful when importing GeoJSON files containing several types of geometry.

name= Rename the target layer.

-uniq

Delete features with the same id as a previous feature

<expression> or expression= JS expression to obtain the id of a feature. Uses the same expression syntax as -each.

max-count= Allow multiple features with the same id (default is 1).

verbose Print information about each removed feature.

target=

# Example: Retain only the largest parts of each multipart polygon
mapshaper polygons.shp \
	-each 'fid = this.id' \
	-explode \
	-sort 'this.area' descending \
	-uniq 'fid' \
	-o out.shp

-calc

Calculate basic descriptive statistics on a data table and display the results, using a JavaScript expression. The following functions are implemented:

  • count()
  • sum()
  • average()
  • median()
  • mode()
  • min()
  • max()
  • collect() returns array containing all values
  • first()
  • last()

count() takes no arguments. The other functions take as an argument a JS expression or field name. Argument expressions take the same form as -each expressions. If no records are processed, count() and sum() return 0, and the other functions return null.

Options

<expression> or expression= JS expression containing calls to one or more -calc functions.

where= Perform calculations on a subset of features, using a boolean JS expression as a filter (similar to -filter command).

Common options: target=

Examples

# Calculate the sum of a data field
mapshaper ny-census-blocks.shp -calc 'sum(POPULATION)'

# Count census blocks in NY with zero population
mapshaper ny-census-blocks.shp -calc 'count()' where='POPULATION == 0'

-encodings

Print list of supported text encodings (for .dbf import).

-help

Print usage tips and a list of commands.

<command> Show options for a single command, e.g. mapshaper -h join.

-info

Print information about a dataset. Useful for seeing the fields in a layer's attribute data table. Also useful for summarizing the result of a series of commands.

# Example: Get information about an unknown GeoJSON or TopoJSON dataset
mapshaper mystery_file.json -info

-inspect

Print information about the data attributes of a feature.

<expression> or expression= JS expression for selecting a feature (see the -each command for documentation about JS expressions).

Common options: target=

# Example: View attribute data for a state
mapshaper states.geojson -inspect 'NAME == "Delaware"'

-projections

Print list of supported proj4 projection ids and projection aliases.

-quiet

Inhibit console messages.

-verbose

Print verbose messages, including the time taken by each processing step.

-version

Print mapshaper version.

You can’t perform that action at this time.