# Mapshaper > Mapshaper is a command-line tool and in-browser editor for geographic vector and raster data. It reads and writes Shapefile, GeoJSON, TopoJSON, GeoPackage, FlatGeobuf, GeoParquet, GeoTIFF, KML/KMZ, CSV/TSV, DBF, JSON records and SVG, and can simplify, clip, dissolve, join, project and otherwise transform layers. The CLI and web app share the same command language, so commands written interactively in the browser console run unchanged in scripts. These docs cover the same material in two forms: - **Markdown mirrors** of every page (this file links to them) for use by language models and other tools. - **HTML pages** at the same paths without the trailing `.md`, with navigation, search and syntax highlighting, intended for humans. When in doubt about a command's behavior, the [command reference](https://mapshaper.org/docs/reference.html.md) is the source of truth. The Node.js source code lives at . --- # Mapshaper documentation

Mapshaper is a tool for editing Shapefile, GeoJSON, TopoJSON, GeoPackage, FlatGeobuf, GeoParquet, GeoTIFF, KML and CSV data — available as a command-line program and as a web app at mapshaper.org.

Command reference

Every command and option, with examples.

What's new

A curated log of recently added features.

Getting started

Introductions to the CLI and the web app.

Guides

In-depth coverage of key topics.

File formats

Read/write details for all of Mapshaper's supported data formats.

Examples

Short recipes for common editing tasks, plus a collection of full map recipes.

## Featured examples ## Help and feedback - Found a bug or want to request a feature? [Open an issue on GitHub](https://github.com/mbloch/mapshaper/issues). - Mapshaper is free software. If it's useful to you, please consider [supporting its development](/sponsor.html). --- # What's new This is a curated list of recently added features. For the full list of changes, including bug fixes and internal work, see the [changelog](https://github.com/mbloch/mapshaper/blob/master/CHANGELOG.md) on GitHub. ## September 2026
**Pie and donut symbols.** The `-symbols` command has a new `pie` type. A `values=` list sets the size of each wedge from numbers, field names or expressions, and a `fills=` list sets their colors. Adding `hole=` makes the symbol a donut, either as a radius or, if negative, as a distance inward from the edge. → See [`-symbols`](/docs/reference.html.md#-symbols) and the [styles and symbols guide](/docs/guides/styles-and-symbols.html.md).
## August 2026
**Repel command.** The `-repel` command removes or reduces overlaps between circle symbols. A `max-shift=` option keeps symbols within a given distance of their true positions. A `polygons=` option constrains symbols to polygon boundaries. → See [`-repel`](/docs/reference.html.md#-repel).
**Isobands.** The `-contours` command has a new `closed` flag for creating polygon bands.
**Clean command improvements.** - A new `close-outer-gaps` option closes cracks that open onto the outside of a polygon mosaic. - The `gap-width=` option is now the preferred way to set the threshold for filling gaps. Gap artifacts tend to be long and thin slivers, so a width parameter is more suitable than the now-deprecated `gap-fill-area=` and `sliver-control=` options.
**Snip tool.** The web UI has a snip mode for cutting polyline features apart. Hover over a line to see its vertices, then click a vertex or a point along a segment to divide it in two. The shorter piece becomes a new feature, so on a multipart feature the rest stays connected. Rings take two clicks, since one cut leaves them in one piece.
## July 2026
**Saving rasters as GeoTIFF files.** Raster layers can now be exported to a `.tif` GeoTIFF file. Files are compressed by default. → See [File formats](/docs/formats/overview.html.md) and [`-o`](/docs/reference.html.md#-o).
**Contour lines from rasters.** The `-contours` command traces contour lines from a raster layer — typically elevation contours from a digital elevation model. Mapshaper picks a sensible spacing between lines from the data itself, or you can set your own with `interval=` or a list of `levels=`. Add `+` to keep the raster layer. → See [`-contours`](/docs/reference.html.md#-contours).
**Blur command.** The `-blur` command takes a radius either in pixels (`-blur 5px`) or as a real-world distance (`-blur 500m`). Slightly blurring an elevation model before running `-contours` is an effective way to get smoother, more generalized contour lines. → See [`-blur`](/docs/reference.html.md#-blur).
**Interrupted and polyhedral world projections.** The `-proj` command supports Interrupted Goode Homolosine (`igh`, `igh_o`), Interrupted Mollweide (`imoll`, `imoll_o`), Buckminster Fuller's Dymaxion map (`dymaxion`, `dymaxion2`), two octahedral butterfly maps (`butterfly`, `butterfly2`), the Cahill-Keyes projection (`cahill_keyes`), Hajime Narukawa's 2022 update to the AuthaGraph projection (`narukawa2022`), and two rectangular world maps using tetrahedral geometry (`markley`, `calm`). The `-graticule` command can generate graticules, polygon footprints and neatlines for all of these projections. → See [Interrupted and polyhedral world projections](/docs/guides/projections.html.md#interrupted-and-polyhedral-world-projections).
**Ruler tool.** The web UI has a ruler mode for measuring distances on the map. It supports great-circle measurements, projected distance readouts, basemap view, and draggable ruler endpoints.
## June 2026
**Smooth command.** The `-smooth` command smooths the geometry of polygon and polyline features to a given resolution. - Sharp corners where straight-line segments meet are preserved by default instead of being rounded. - By default, a pre-filter is applied to remove intricate sub-scale detail (jetties, narrow inlets, spikes). - The `gain` option controls the amplitude of output curves. - The `max-bend-angle` option trades output vertex count against join smoothness. → See [`-smooth`](/docs/reference.html.md#-smooth).
**Buffer command.** The `-buffer` command makes buffers around points, lines and polygons. - The command uses geodesic distance on lat-long datasets and on projected datasets with the `geodesic` option. - Negative `radius` parameters shrink polygons (positive distances expand them). - The `topological` option prevents buffers from overlapping nearby polygons. - The `fill-gaps` option fills enclosed holes and narrow-mouthed inlets (like a river up to its mouth) without growing the outer boundary. → See [`-buffer`](/docs/reference.html.md#-buffer).
## May 2026
**Raster layer support.** Mapshaper can now import GeoTIFF rasters, plus PNG and JPEG images with world-file georeferencing, preview them in the web UI, clip them with the rectangle tool, and export as images embedded in SVG. Mapshaper's default options for raster importing and projecting rasters should work well for typical image layers. When importing rasters containing data, you may need to set additional options, which are documented in the command reference. → See [`-i`](/docs/reference.html.md#-i-input).
**Point icons with `-style`.** The `-style` command has new `icon=`, `icon-size=` and `icon-color=` options for drawing simple point icons, including circles, squares, rings and stars. Icons can be combined with labels on the same point layer. → See [`-style`](/docs/reference.html.md#-style).
**Undo/redo for web UI commands.** The web UI can now save temporary restore data while you work, so console commands and other data edits can be undone and redone from a pop-up toolbar. **This feature is very new and may have bugs, please report any problems that you encounter**. Undo is on by default and can be turned off from the new History menu.
**More grid options.** The `-grid` command can now create rhombus and triangle grids. There are new `cols=`, `rows=` and `cells=` options for controlling the size of the grid cells, as alternatives to the original `interval=` option. A new `cell-scale=` option lets you scale each cell within the grid (creating gaps or overlaps between adjacent cells). → See [`-grid`](/docs/reference.html.md#-grid).
**GeoParquet support.** Mapshaper reads and writes GeoParquet (`.parquet`) files. To use ZSTD compression (instead of the default Snappy compression), add `compression=zstd` to the output options. → See [GeoParquet](/docs/formats/geoparquet.html.md).
## April 2026
**Messages panel.** Warnings and informational messages are now collected in a messages panel. When new messages are available, an icon with a count appears in the header bar; clicking it opens the panel. This keeps important information accessible without interrupting your session with a modal popup.
**Command files.** A sequence of Mapshaper commands can be written to a `.txt` file with `#` comments and no shell quoting, and run with `-run ` (or just `mapshaper commands.txt`). Command files can also be written in a shell-compatible way, if you want to be able to paste the commands into the terminal or add them to a shell script. **Update:** these files can also be imported and run in the browser UI. ```bash mapshaper build.txt ``` → See [Command files](/docs/essentials/command-line.html.md#command-files) in the reference.
**Variable interpolation in commands.** Command files and command lines support `{{VAR}}` placeholders, resolved at run time against environment variables (`{{env.HOME}}`), values set with the new `-vars` and `-defaults` commands, and variables defined dynamically by `-calc`, `-define` and `-each` expressions. ```bash mapshaper -vars YEAR=2030 PCT=5 -run build.txt ``` → See [Variable interpolation](/docs/essentials/command-line.html.md#variable-interpolation), [`-vars`](/docs/reference.html.md#-vars) and [`-defaults`](/docs/reference.html.md#-defaults).
**Farewell to dissolve2.** The `-dissolve` command now uses Mapshaper's most robust dissolve function, which can handle overlaps, gaps and other topology errors. The legacy faster algorithm is still available as `-dissolve no-repair`. (The old `-dissolve2` is now just an alias for `-dissolve`.) → See [`-dissolve`](/docs/reference.html.md#-dissolve).
**FlatGeobuf and GeoPackage support.** Mapshaper reads and writes FlatGeobuf (`.fgb`) and GeoPackage (`.gpkg`) files. → See [FlatGeobuf](/docs/formats/flatgeobuf.html.md), [GeoPackage](/docs/formats/geopackage.html.md) and [`-i layers=`](/docs/reference.html.md#-i-input).
**SVG import.** SVG files exported by Mapshaper can be re-imported — useful for making stylistic edits. → See [SVG](/docs/formats/svg.html.md).
--- # Command reference ## Command line syntax Mapshaper takes a list of commands and runs them in sequence, from left to right. A command consists of the name of a command prefixed by a hyphen, followed by options for the command. If the first token is not a command, Mapshaper infers one: most file paths are treated as `-i`, while `.txt` command files are treated as `-run`. #### Example ```bash # Read a Shapefile, # simplify using Douglas-Peucker, # output as GeoJSON. mapshaper provinces.shp \ -simplify dp 20% \ -o precision=0.00001 output.geojson ``` ### Command options can take three forms: - Values, like `provinces.shp` and `output.geojson` in the above example - Flags, like `dp` - Name/value pairs, like `precision=0.00001` ### Common options The following options are documented here, because they are used by many 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). #### Example ```bash # Make a derived layer containing a subset of features # while retaining the original layer mapshaper states.geojson \ -filter 'ST == "AK"' + name=alaska \ -o output/ target=* ``` ## Index of commands **File I/O** [-i (input)](#-i-input) [-o (output)](#-o-output) **Editing** [-affine](#-affine) [-buffer](#-buffer) [-classify](#-classify) [-clean](#-clean) [-clip](#-clip) [-colorizer](#-colorizer) [-dashlines](#-dashlines) [-densify](#-densify) [-dissolve](#-dissolve) [-dissolve2](#-dissolve2) [-divide](#-divide) [-dots](#-dots) [-drop](#-drop) [-each](#-each) [-erase](#-erase) [-explode](#-explode) [-filter](#-filter) [-filter-fields](#-filter-fields) [-filter-islands](#-filter-islands) [-filter-slivers](#-filter-slivers) [-frame](#-frame) [-graticule](#-graticule) [-grid](#-grid) [-include](#-include) [-inlay](#-inlay) [-innerlines](#-innerlines) [-join](#-join) [-lines](#-lines) [-merge-layers](#-merge-layers) [-mosaic](#-mosaic) [-point-grid](#-point-grid) [-points](#-points) [-polygons](#-polygons) [-proj](#-proj) [-rectangle](#-rectangle) [-rectangles](#-rectangles) [-rename-fields](#-rename-fields) [-rename-layers](#-rename-layers) [-repel](#-repel) [-require](#-require) [-run](#-run) [-scalebar](#-scalebar) [-shape](#-shape) [-simplify](#-simplify) [-smooth](#-smooth) [-snap](#-snap) [-sort](#-sort) [-split](#-split) [-split-on-grid](#-split-on-grid) [-subdivide](#-subdivide) [-style](#-style) [-symbols](#-symbols) [-union](#-union) [-uniq](#-uniq) **Control Flow** [-if](#-if) [-elif](#-elif) [-else](#-else) [-endif](#-endif) [-stop](#-stop) [-target](#-target) **Information** [-calc](#-calc) [-colors](#-colors) [-comment](#-comment) [-defaults](#-defaults) [-encodings](#-encodings) [-help](#-help) [-info](#-info) [-inspect](#-inspect) [-print](#-print) [-projections](#-projections) [-quiet](#-quiet) [-vars](#-vars) [-verbose](#-verbose) [-version](#-version) ## I/O Commands ### -i (input) Input one or more files in a supported vector, table, or raster data format. Supported file types include: Shapefile, GeoJSON, TopoJSON, GeoPackage, FlatGeobuf, GeoParquet, KML, JSON data records, DBF, CSV/TSV, GeoTIFF, PNG and JPEG images with world files. The `-i` command is assumed if `mapshaper` is followed by the path of an input data file. Mapshaper does not fully support M and Z type Shapefiles. The M and Z data is lost when these files are imported. When multiple input files are given, they can either be processed together (as a group of layers with shared topology) or separately (as a sequence of independent runs). Use `combine-files` to process them together, or `batch-mode` to process them separately. For backward compatibility, multiple input files are currently processed in batch mode by default; this default will change in a future release. Mapshaper prints a deprecation notice when batch mode is triggered implicitly. Existing scripts that rely on batch processing should add the `batch-mode` flag. **Options** `` or `files=` File(s) to input (space-separated list). Use `-` to import from `/dev/stdin`. In place of a file name, you can also pass data inline: - **JSON.** A string starting with `{` or `[` is treated as a literal JSON object or array. - **CSV.** A comma-delimited string is treated as inline CSV when it contains a newline (a real one or the literal escape sequence `\n`) and both the first and second lines contain at least one comma. ```bash mapshaper -i 'lat,lon,label\n48.86,2.35,Paris\n51.51,-0.13,London' \ -o cities.json ``` `combine-files` Import multiple files to separate layers with shared topology. `batch-mode` Apply subsequent commands separately to each input file, as if running mapshaper multiple times with the same set of commands. Used together with `-o` to transform a directory of files. Required (in a future release) to use this batch-processing behavior. `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. `string-fields=` (CSV) List of fields to import as strings (e.g. FIPS,ZIPCODE). Using `string-fields=*` imports all fields as strings. `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-skip-lines=` Number of lines to skip at the beginning of a CSV file. Useful when a CSV has been exported from a spreadsheet and there are rows of notes above the data section of the worksheet. `csv-lines=` Number of data records to import from a CSV file (default is all). `csv-field-names=` Comma-sep. list of names to assign each field. Can be used in conjunction with `csv-skip-lines=1` to replace names from an existing set of field headers. `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. `decimal-comma` Import numbers formatted with decimal commas, not decimal points. Accepted formats: `1.000,01` `1 000,01` (both imported as as 1000.01). `csv-dedup-fields` Assign unique names to CSV fields with duplicate names. `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. `json-path=` [JSON] Path to an array of data records or a GeoJSON object. For example, `json-path=data/counties` expects a JSON object with the following structure `{"data": {"counties": []}}`. `layers=` [GeoPackage] Comma-separated list of layer names to import from a GeoPackage file. If omitted, all layers are imported. `scaling=none|minmax|percentile` [Raster] Display scaling method for raster imports. The default is `none` for 8-bit rasters and `percentile` for non-8-bit rasters. `scale-range=` [Raster] Output intensity range for raster display scaling, as normalized percentages. The default is `0,100`. `percentile-range=` [Raster] Input percentile range used with `scaling=percentile`. The default is `2,98`. `raster-type=image|categorical|continuous` [Raster] Semantic raster type. This sets the default resampling method for later raster reprojection, and how uncovered pixels are filled. `image` (the default) uses bilinear resampling and fills with a color. `categorical` uses nearest-neighbor resampling to preserve class/code values, and fills with the source nodata value. `continuous` is for measurement rasters such as elevation models: it uses bilinear resampling like `image` but fills with the source nodata value like `categorical`, so uncovered pixels do not become a color value mixed in with the data. `rendition=` [GeoTIFF] Import a specific GeoTIFF rendition, using a slug such as `full` or `overview-1`. When a GeoTIFF has internal overviews, Mapshaper lists the available slugs during import. By default, large GeoTIFFs are imported from the best available reduced-resolution overview under Mapshaper's import size limit, or resampled during import if no suitable overview is available. Use `rendition=full` to force full-resolution import. `name=` Rename the imported layer (or layers). **Example** ```bash # 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 content of the target layer(s) to a file or files. **Options** `||-` Name of output file or directory. Use `-` to export text-based formats to `/dev/stdout`. `format=shapefile|geojson|topojson|flatgeobuf|geopackage|geoparquet|geotiff|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 exports to the same format as the input format. The `json` format is an array of objects containing data properties for each feature. The `geotiff` format takes raster layers only; every other format takes vector or table layers only, apart from `svg` and `msx`, which accept both. `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). `gzip` Apply gzip compression to output files. `zip` Save output files in a single .zip archive. `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. `fix-geometry` Remove segment intersections caused by rounding (via the `precision=` option) or TopoJSON quantization, by reverting intersecting areas to the original coordinates. In the case of quantized TopoJSON output, this option produces delta-encoded arcs that contain some decimal numbers. Be sure to test your software for compatibility. Note that this option is only applied if the original paths are free of intersections. Also, some kinds of invalid geometry, like spikes, do not get fixed. `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 quantization parameter used by the [topoquantize](https://github.com/topojson/topojson-client#topoquantize) command line 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. `ndjson` (GeoJSON/JSON) Output newline-delimited records. `gj2008` (GeoJSON) Generate output that is consistent with the pre-RFC 7946 GeoJSON spec (dating to 2008). `reverse-winding` (GeoJSON) Reverse the winding order of GeoJSON polygon rings on export, so outer rings have clockwise order and holes have counter-clockwise order. This option will usually generate d3-compatible GeoJSON files, but it doesn't apply special spherical-geometry rules for very large polygons or ocean polygons. `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). `no-null-props` (GeoJSON) use `"properties": {}` instead of `"properties": null` when outputting a Feature with no attribute data. `hoist=` (GeoJSON) Move one or more properties to the root level of each Feature. Hoisting a field named "id" creates an id for each Feature. This option can also be used to create non-standard Feature attributes (as used by the tippecanoe program). `metadata` (SVG/TopoJSON/GeoJSON) Include metadata in output. In the case of SVG output, CRS and bbox data is embedded in the file, so when the SVG is re-imported the original geographic coordinates can be recovered. For GeoJSON output, this option re-emits non-structural top-level members that were present in the imported GeoJSON file, such as a legacy `crs` object, a top-level `id`, or non-standard members like `metadata`. Preserved members are passed through unchanged, so values that describe the data (e.g. a feature count) may become stale after editing. A preserved `crs` member is dropped if the dataset is reprojected with `-proj`. `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 `` (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-data=` (SVG) Export a comma-seperated list of data fields as SVG data-* attributes. Attribute names should match the following regex pattern: `/^[a-z_][a-z0-9_-]*$/`. Non-conforming fields are skipped. `svg-scale=` (SVG) Scale SVG output using geographical units per pixel (an alternative to the `width=` option). `svg-bbox=` (SVG) Bounding box of SVG map in projected map units. By default, the extent of SVG output fits the content; this option lets you provide a custom extent. This could be useful when aligning the SVG output with other content layers, such as images or videos. `raster-res=` (SVG) Resolution of embedded raster images, in raster pixels per SVG pixel. The default is `1`; larger values produce higher-resolution embedded images, up to the resolution of the source raster. `linked-images` (SVG) Output raster images as separate JPEG or PNG files and link to them from SVG `` elements instead of embedding them as data URIs. `jpeg-quality=` (SVG) JPEG quality for embedded or linked raster images, from `1` to `100`. The default is `85`. `fit-extent=` (SVG) Use a layer (typically a layer containing a single rectangle) to set the extent of the map. Paths that overflow this extent are retained in the SVG output. `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=|`. `decimal-comma` (CSV) Export numbers with decimal commas instead of decimal points (common in Europe and elsewhere). `compression=` (GeoParquet) Select Parquet column compression. One of: `snappy` `zstd` `none`. The default is `snappy`. (GeoTIFF) One of: `deflate` `none`. The default is `deflate`. `level=` (GeoParquet) Set the ZSTD compression level when using `compression=zstd`. Valid values are integers from 1 to 22. `rowgroup=` (GeoParquet) Set the number of rows in each row group. By default Mapshaper sizes row groups by their estimated size in bytes rather than by a fixed row count, aiming for around 16MB of uncompressed data per group, so that a layer of points and a layer of detailed polygons both produce groups of a similar size. Set this only if you know the access pattern you are writing for. `show-all` [Snapshot] All layers of the exported snapshot will be displayed when opened in the web UI. **Example** ```bash # Convert all the Shapefiles in one directory into GeoJSON # files in a different directory. mapshaper -i shapefiles/*.shp batch-mode -o geojson/ format=geojson ``` ## Editing Commands ### -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=` ### -blur Apply a Gaussian-like blur to raster layers. The command only works on projected rasters; unprojected lat-long rasters should be reprojected first with `-proj`. `` Blur amount, given either in pixels or as a real-world distance. This value corresponds to `2 * sigma` of a Gaussian curve. Pixels can be written as plain numbers or with a `px` suffix (`radius=10`, `radius=10px`); distances carry units (`radius=500m`, `radius=2km`) and are converted using the size of a pixel on the ground, so the same command gives a comparable amount of blur on rasters of differing resolution. The radius can be given without the `radius=` prefix, for example `-blur 5px` or `-blur 500m`. Common options: `target=` ### -buffer Create buffer polygons around point, polyline or polygon features. The buffer distance is given by the `` parameter. For layers in longitude/latitude coordinates, distances such as `2km` or `500m` are measured over the earth, so a one-kilometer buffer is approximately one kilometer on the ground. For projected layers, distances are measured in the layer's flat, projected coordinate system, so be aware that results can be distorted if the layer is in a projection that does not preserve distances well across the data area. For point layers, `-buffer` creates circular polygons. For polyline layers, it creates rounded or flat-ended line buffers. For polygon layers, positive buffers expand polygons and shrink holes; negative buffers shrink polygons and expand holes. Negative buffers are only supported for polygon layers. `` or `radius=` Buffer distance, as a constant or JavaScript expression. Distance units may be included in the radius value, for example `500m`, `2km`, `1mi` or `1000ft`. If no units are given, meters are assumed when the dataset has a known CRS. For datasets without CRS information, unitless radius values are interpreted in source coordinate units. `tolerance=` Acceptable radius error for line and polygon buffers. Values may be distances, such as `20m`, or percentages of the buffer radius, such as `1%`. The default is `1%`. Buffer generation is faster using a small tolerance, but you can disable this optimization by setting `tolerance=0`. `vertices=` [points] Number of vertices used to approximate each point buffer circle. The default is 72. `quad-segs=` [lines, polygons] Number of segments per quarter-circle in joins and caps. The default is 8. `cap-style=flat|round` [lines] End cap style for line buffers. The default is `round`. `topological` [polygons] Buffer only unshared polygon boundaries, such as coastlines and empty holes. Buffer areas do not cover any original polygon areas, and overlapping buffer areas are partitioned between features by proximity, so each point in a contested area is assigned to the nearest source polygon. `fill-gaps` [polygons] Fill enclosed holes and narrow-mouthed inlets — gaps whose opening is narrower than the buffer distance — without growing the outer boundary (a river is filled up to its mouth, but the open coastline is left in place). The filled area is partitioned among the adjacent features by proximity. `max-widening=` [polygons, with `fill-gaps`] Fill interior gaps up to this multiple of the buffer distance wide; wider gaps are kept open. The default is 5. For example, with a 1km buffer distance and the default `max-widening` value, an interior gap is filled if it is narrower than 5km and left open otherwise. `merge-islands` [polygons, with `fill-gaps`] Also bridge a small isolated island to a neighboring landmass when the gap between them is narrower than the buffer distance. By default such islands are left separate (only a landmass smaller than a disk of the mouth radius is treated as an island; gaps between larger landmasses, such as a river between two states, are filled either way). `geodesic` [projected data] Buffer using geodesic distances instead of projected planar distances. Common options: `name=` `+` `target=` ```bash # Buffer a line layer by 2 km mapshaper roads.shp -buffer 2km -o roads_buffer.geojson # Create a topological coastline-style buffer around polygons mapshaper counties.shp -buffer 100m topological -o counties_buffer.geojson # Fill inlets and enclosed holes up to 500m wide without growing the coastline mapshaper land.shp -buffer 500m fill-gaps -o land_filled.geojson ``` ### -classify Assign colors or data values to each feature using one of several classification methods. Methods for sequential data include `quantile`, `equal-interval`, `hybrid` and `nice` or categorical classification to a data field. `` or `field=` Name of the data field to classify. `save-as=` Name of a (new or existing) field to receive the output of classification. The default output field for colors is `fill` or `stroke` (depending on geometry type) and `class` for non-color output. `values=` List of values to assign to data classes. If the number of values differs from the number of classes given by the (optional) `classes` or `breaks` option, then interpolated values will be calculated. Mapshaper uses d3 for interpolation. `colors=` Takes a list of CSS colors, the name of a predefined color scheme, or `random`. Run the [-colors](#-colors) command to list all of the built-in color schemes. Similar to the `values=` option, if the number of listed colors is different from the number of requested classes, interpolated colors are calculated. `non-adjacent` Assign colors to a polygon layer in a randomish pattern, trying not to assign the same color to adjacent polygons. Mapshaper's algorithm balances performance and quality. Usually it can find a solution with four or five colors. If mapshaper is unable to avoid giving the same color to neighboring polygons, it will print a warning. You can resolve the problem by increasing the number of colors. `stops=` A pair of comma-separated numbers (0-100) for limiting the output range of a color ramp. `null-value=` Value (or color) to use for invalid or missing data. `classes=` Number of data classes. This number can also be inferred from the `breaks=` or `values=` options. `breaks=` Specify user-defined sequential class breaks (an alternative to automatic classification using `quantile`, `equal-interval`, etc.). `outer-breaks=` A pair of comma-separated numbers setting min and max breakpoints to use when computing class breaks. This setting overrides the default behavior, which is to use the min and max values of the data field being classified. This setting can be used to prevent extreme data values (outliers) from affecting equal-interval classification. Also useful for setting outside breakpoints for continuous color ramps (when using the `continuous` option). `method=` Classification method. One of: `quantile`, `equal-interval`, `nice`, `hybrid` (sequential data), `categorical`, `non-adjacent` and `indexed`. This parameter is not required if the classification method can be inferred from other options. For example, the `index-field=` parameter implies indexed classification, the `categories=` parameter implies categorical classification. `quantile` Use quantile classification. Shortcut for `method=quantile`. `equal-interval` Use equal interval classification. Shortcut for `method=equal-interval`. `nice` Same as `method=nice`. This scheme finds equally spaced, round breakpoints that roughly divide the dataset into equal parts (similar to quantile classification). `invert` Reverse the order of colors/values. `continuous` Output continuously interpolated values (experimental). Uses linear interpolation between class breaks, which may give poor results with some distributions of data. This option is for creating unclassed/continuous-color maps. `index-field=` Use class ids that have been precalculated and assigned to this field. Values should be integers from `0 ... n-1` (where n is the number of classes). `-1` is the null value. `precision=` Round data values before classification (e.g. `precision=0.1`). `categories=` List of values in the source data field. Using this option triggers categorical classification. `other=` Default value for categorical classification. This value is used when the value of the source data field is not present in the list of values given by `categories=`. Defaults to `null-value=` or null. **Options for generating SVG keys** `key-style=` One of: simple, gradient, dataviz `key-name= ` Name of output SVG file `key-width=` Width of key in pixels `key-font-size=` Font size of tic labels in pixels `key-tile-height=` Height of color tiles in pixels `key-tic-length=` Length of tic mark in pixels `key-label-suffix=` String to append to each label `key-last-suffix=` String to append to the last label **Examples** ```bash # Apply a sequential color ramp to a polygon dataset using quantiles. mapshaper covid_cases.geojson \ -classify save-as=fill quantile color-scheme=Oranges classes=6 \ -o out.geojson ``` ### -clean This command attempts to repair various kinds of abnormal geometry that might cause problems when running other mapshaper commands or when using other software. Features with null geometries are deleted, unless the `allow-empty` flag is used. Polygon features are cleaned by removing overlaps and filling small gaps between adjacent polygons. Areas that are contained by more than one polygon (overlaps) are assigned to the polygon with the largest area. A filled gap goes to the feature it shares the longest boundary with, except where it borders three or more features: such a gap is divided between them, each receiving the part of it that lies nearest, so that a crack running past several features does not become a spur on whichever one claimed it. A gap narrower than the detail of the data around it is given whole to one feature instead — that moves a boundary by less than the width of the gap, where dividing it would give several features a hair-thin sliver each. A boundary that two neighboring features each carry their own copy of, differing only in the last digits of its coordinates, is merged into one shared boundary. Left alone, the hair-thin gap between the two copies would be filled like any other gap, and awarded to one of the features, which would then carry a zero-width spike along a boundary it shares with its neighbors — visible as a stray line as soon as that feature is drawn with an outline. Only gaps that are completely enclosed by polygons can be filled. Use `close-outer-gaps` to reach a crack that opens onto the outside instead. Line features are cleaned by removing self-intersections within the same path. Self-intersecting paths are split at the point of intersection and converted into multiple paths within the same feature. When two separate paths intersect in-between segment endpoints, new vertices are inserted at the point of intersection. Point features are cleaned by removing duplicate coordinates within the same feature. `gap-width=` (polygons) Fill gaps narrower than this width (e.g. `2m`, `0`). Each gap’s width is estimated from its area and perimeter (roughly, how wide a long thin shape would be if straightened out), so slender cracks are filled while more compact holes of similar area, such as small lakes, are more likely to be kept. Defaults to an automatic value based on the median segment length of the layer. The same width applies to the cracks that `close-outer-gaps` reaches. `close-outer-gaps` (polygons) Close cracks that open onto the outside of the mosaic, up to the width set by `gap-width=`. Such a crack is not enclosed by polygons, so there is no gap for the ordinary filling to find. Its mouth is pinched shut where the two sides come within that width of each other, which encloses it, and it is then filled — or divided between its neighbors, where it borders three or more of them — like any other gap. Only the pinched pair of vertices moves, half the width of the mouth each, and interior gaps are filled exactly as they are without this option. It is opt-in because it seals off narrow openings in a coverage, which are not always mistakes. `gap-fill-area=` (polygons, deprecated) Use `gap-width=` instead. Gaps smaller than this area will be filled; larger gaps will be retained as holes in the polygon mosaic. Example values: 2km2 500m2 0. `sliver-control=` (polygons, deprecated) Use `gap-width=` instead. Preferentially remove slivers (polygons with a high perimeter-area ratio). Accepts values from 0-1, default is 1. Implementation: multiplies the area of gap areas by the "Polsby Popper" compactness metric before applying area threshold. `overlap-rule=` (polygons) Assign overlapping polygon areas to one of the overlapping features based on this rule. Possible options are: min-id, max-id, min-area, max-area (default is max-area). `allow-overlaps` Allow features to overlap each other. The default behavior is to remove overlaps. `snap-interval=` Snap vertices within a given threshold before performing other kinds of geometry repair. Defaults to a very small threshold. Uses source units. `rewind` Fix errors in the winding order of polygon rings. `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. `` or `source=` Clip to a set of polygon features. Takes the filename or layer id of the clip polygons. `bbox=` Delete features or portions of features that fall outside a bounding box. `bbox2=` Faster bounding box clipping than `bbox=` (experimental). `remove-slivers` Remove tiny sliver polygons created by clipping. Common options: [`name=` `+` `target=`](#common-options) ```bash # 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. `random` Randomly assign colors. Uses `colors=` list if given. `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). ```bash # 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 ``` ### -contours Convert a raster layer to a polyline layer of contour lines (isolines). Add `closed` to create polygon bands between the contour lines instead. This is most often used with a digital elevation model, but it works on any continuous raster. Running `-blur` before `-contours` produces smoother lines than contouring the raw data. Values are read at pixel centers, so ordinary contour lines span from the center of the first pixel to the center of the last, half a pixel inside the raster's bounds. Closed bands extend lines that reach this outer lattice to the raster bounds and use the bounds as a fixed outer frame. `-contours` finishes by smoothing the lines, using an interval of a quarter of a pixel. Where smoothing causes lines to cross, the intersecting lines are left unsmoothed. Use `no-smoothing` to skip the step and keep the raw traced geometry, which you can then smooth yourself with `-smooth`. By default the contour layer replaces the raster layer. Use `+` to keep the raster as well. `interval=` Spacing between contour levels. Levels are multiples of this value, so `interval=100` gives levels at 100, 200, 300 and so on. If neither `interval=` nor `levels=` is given, mapshaper picks a round interval that divides the raster's value range into roughly fifteen steps. `levels=` Explicit comma-separated list of contour levels, for example `levels=0,100,500,1000`. Overrides `interval=`. `base=` Value to align `interval=` to (the default is 0). For example `interval=100 base=50` gives levels at 50, 150, 250 and so on. `band=` Index of the band to read values from (the default is 0). Elevation models normally have a single band. `field=` Name of the output field holding each line's contour value. The default is `value`. This option applies to line output, not `closed` output. `closed` Create polygon bands instead of contour lines. Each feature has `lower` and `upper` fields. Interior bands are lower-inclusive and upper-exclusive; the highest band includes the raster maximum. The lowest and highest bounds are the minimum and maximum valid raster values, while interior bounds come from `interval=` or `levels=`. `no-smoothing` Skip contour smoothing. With `closed`, the contour boundaries are smoothed by default but the raster and nodata closure boundaries are not. Common options: `name=`, `no-replace`, `target=` ```bash # Trace 100-meter contours from an elevation model mapshaper dem.tif -contours interval=100 -o contours.json # Blur the data first, then label the output field ELEV mapshaper dem.tif raster-type=continuous \ -proj webmercator \ -blur radius=3 \ -contours interval=50 field=ELEV \ -o contours.json # Keep the raster and draw specific contours over it mapshaper dem.tif -contours levels=500,1000,1500 + name=contours \ -o output.svg # Create smoothed, closed elevation bands mapshaper dem.tif -contours interval=100 closed -o bands.json # Trace raw lines, then smooth them by hand mapshaper dem.tif -contours interval=100 no-smoothing \ -smooth 40 no-corners no-prefilter \ -o contours.json ``` ### -dashlines Split lines into sections, with or without a gap. `dash-length=` Length of split-apart lines (e.g. 200km) `gap-length=` Length of gaps between dashes (default is 0) `scaled` Scale dashes and gaps to prevent partial dashes `planar` Use planar geometry `where=` Use a JS expression to select a subset of features. ### -densify Add vertices along the segments of polyline and polygon features, so that no segment is longer than a given interval. Densifying before reprojecting allows long straight segments to follow a curved path. Densifying can also improve the quality of geodesic buffers. New vertices are interpolated along one of three paths. For lat-long datasets the default is `geodesic`; for projected datasets the only supported mode is `planar`. `` or `interval=` Maximum segment length. For `geodesic` and `rhumb` interpolation this is a ground distance and may include units, for example `100km`, `500m`, `50mi` or `1000ft` (a value without units is interpreted as meters). For `planar` interpolation of a lat-long dataset the interval is in decimal degrees (for example `2` or `0.5deg`); for `planar` interpolation of a projected dataset it is in the layer's coordinate units. `geodesic` [lat-long, default] Interpolate along the ellipsoidal shortest path between two vertices. `rhumb` [lat-long] Interpolate along a rhumb line (a line of constant compass bearing). `planar` [default for projected data] Interpolate along a straight line in the layer's coordinate space. ### -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. For polygon layers, `-dissolve` repairs topology before dissolving, so it produces correct results on inputs that contain overlaps, gaps or other topology errors. The `no-repair` option skips this step for a faster (but less robust) dissolve. `` or `fields=` (optional) Name of a data field or fields to dissolve on. Accepts a comma-separated list of field names. `group-points` [points] Group the points from each dissolved group of features into a multi-point feature instead of converting multiple points into a single-point centroid feature. `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.) `gap-width=` [polygons] Fill gaps narrower than this width (e.g. `2m`, `0`). Each gap’s width is estimated from its area and perimeter (roughly, how wide a long thin shape would be if straightened out), so slender cracks are filled while more compact holes of similar area, such as small lakes, are more likely to be kept. Defaults to an automatic value based on the median segment length when gap filling is enabled. `gap-fill-area=` [polygons, deprecated] Use `gap-width=` instead. Gaps smaller than this area will be filled; larger gaps will be retained as holes in the polygon mosaic. Example values: 2km2 500m2 0. `sliver-control=` [polygons, deprecated] Use `gap-width=` instead. Preferentially remove slivers (polygons with a high perimeter-area ratio). Accepts values from 0-1, default is 1. Implementation: multiplies the area of gap areas by the "Polsby Popper" compactness metric before applying area threshold. `allow-overlaps` [polygons] Allow dissolved groups of features to overlap each other. The default behavior is to remove overlaps. `no-repair` [polygons] Skip topology repair before dissolving. Use when the input is known to be clean and you want a faster dissolve. Mapshaper checks for segment intersections and prints a warning if the assumption appears to be wrong, but it still performs the dissolve. Incompatible with `gap-width=`, `gap-fill-area=`, `sliver-control=` and `allow-overlaps`. `calc=` Use built-in JavaScript functions to create data fields in the dissolved layer. See example below; see [-calc](#-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. `multipart` Group features from the target layer into multipart features, without otherwise modifying geometry. `where=` Use a JS expression to select a subset of features to dissolve. Common options: `name=` `+` `target=` ```bash # 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 Deprecated alias for [`-dissolve`](#-dissolve). The topology-repairing behavior of `-dissolve2` has been promoted to be the default behavior of `-dissolve`. Existing scripts that use `-dissolve2` will continue to work but print a deprecation notice. ### -divide Divide a polyline layer by a polygon layer. Line features that cross polygon boundaries are divided into separate features. Data fields from the polygon layer are copied to the line layer, as in the `-join` command. `` or `source=` File or layer containing polygon features. `fields=` A comma-separated list of fields to copy from the polygon layer (see `-join` command). `calc=` Use JS assignments and built-in functions to convert values from the polygon layer to (new) fields the target table (see `-join` command). Other options: `target=` ### -dots Fill polygons with random points, for making dot density maps. This command should be applied to projected layers. `` or `fields=` List of one or more data fields containing data for the number of dots to place in each polygon. `colors=` List of dot colors (one color for each field in the `fields=` parameter). Dots of different colors are placed in random sequence, so dots of one color do not consistently cover up dots of other colors in the densest areas. `values=` List of values to assign to dots (alternative to `colors=`). `save-as=` Name of a (new or existing) field to receive the assigned colors or values. (By default, colors are assigned to the `fill` field.) `r=` Dot radius in pixels. `evenness=` A value from 0-1. 0 corresponds to purely random placement, 1 maintains (fairly) even spacing between the dots within each polygon. The default is 1. `per-dot=` A number for scaling data values. For example, use `per-dot=100` to make a map that displays one dot per 100 people (or whatever entity is being visualized). `copy-fields=` List of fields to copy from the original polygon layer to each dot feature. `multipart` Combine groups of same-color dots into multi-part features. Other options: `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. `holes` Delete any holes from a polygon layer. `target=` Layer(s) to target. ### -each Apply a JavaScript expression to each feature in a layer. Data properties are available as local variables; the feature's geometry-derived properties are available on the `this` object (e.g. `this.area`, `this.centroidX`, `this.bbox`). **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. `` or `expression=` JavaScript expression to apply to each feature. `where=` Secondary boolean JS expression for targetting a subset of features. `target=` Layer to target. The same expression syntax and execution context are used by all commands that support expressions. See [JavaScript expressions](/docs/guides/expressions.html.md) for the full reference. The [Basics](/docs/examples/basics.html.md) page has practical recipes that put expressions to work. **Examples** ```bash # 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. `` or `source=` File or layer containing erase polygons. Takes the filename or layer id of the erase polygons. `bbox=` Delete features or portions of features that fall inside a bounding box. Similar to `-clip bbox=`. `bbox2=` Faster bounding box erasing than `bbox=` (experimental). `remove-slivers` Remove tiny sliver polygons created by erasing. Common options: [`name=` `+` `target=`](#common-options) ```bash # 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. `` or `expression=` JS expression evaluating to `true` or `false`. Uses the same execution context as [`-each`](#-each). `bbox=` Retains features that intersect the given bounding box (xmin,ymin,xmax,ymax). `invert` Invert the filter -- retain only those features that would have been deleted. `remove-empty` Delete features with null geometry. May be used by itself or in combination with an ``. Common options: [`name=` `+` `target=` ](#common-options) ```bash # 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, by listing the fields to retain. If no files are given, then all attributes are removed. `` or `fields=` Comma-separated list of data fields to retain. `invert` Invert the filter -- delete the listed fields instead of retaining them. Common options: `target=` ```bash # 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 small-area islands using an area threshold (e.g. 10km2). `min-vertices=` Remove low-vertex-count islands. `remove-empty` Delete features with null geometry. [`target=`](#common-options) ### -filter-slivers Remove small polygon rings. `min-area=` Area threshold for removal (e.g. 10km2). `sliver-control=` (polygons) Preferentially remove slivers (polygons with a high perimeter-area ratio). Accepts values from 0-1, default is 1. Implementation: multiplies the area of polygon rings by the "Polsby Popper" compactness metric before applying area threshold. `remove-empty` Delete features with null geometry. [`target=`](#common-options) ### -frame Create a rectangular frame layer at a given display width. Frame size is used for scaling symbols and for setting the display size of SVG output. The geographical extent of the frame is based on the `bbox=` option or the bounding box of the target layer or layers, if `bbox=` is omitted. `width=` Width of frame (e.g. 5in, 10cm, 600px; default is 800px) `height=` Height of frame (in addition to or instead of width= option) `aspect-ratio=` Aspect ratio of frame (optional) `bbox=` Bounding coordinates of frame contents in projected map coordinates (xmin,ymin,xmax,ymax). If omitted, the bounding box of the target layer(s) is used. `offset=` Padding around the frame's `bbox` in display units or pct of width/height, e.g. 5cm 20px 5% `offsets=` Comma-sep. list of offsets for each side of the map frame, in l,b,r,t order Other options: `name=` `target=` ### -graticule Create a graticule layer appropriate for the target dataset's projection. Bounded and interrupted projections include matching outline paths. `polygon` Create a polygon enclosing the entire area of the graticule. Useful for creating background or outline shapes for bounded and interrupted projections. `outline` Create the same boundary as the `polygon` option, as a polyline layer. `interval=` Specify the spacing of graticule lines (in degrees). Common options are: 5, 10, 15, 30, 45. Default is 10. ### -grid Create a continuous grid of square, hexagonal, rhombus, triangle or cairo polygons. The `-grid` command should have a projected layer as its target. The cells of the grid will completely enclose the bounding box of the target layer. This command is intended for visualizing data in a grid. Typically, you would use the `-join` command to join data from a polygon or point layer to a grid layer. Use `-join interpolate=` to interpolate data values (typically count data) from the polygon layer to the grid layer based on area. Use `-join calc=' = sum()'` or `-join calc=' = count()'` to aggregate point data values. `type=` Supported values: `square` `square2` `hex` `hex2` `rhombus` `rhombus2` `triangle` `triangle2` `cairo`. The `square` and `square2` types have different rotations. The `hex` and `hex2` types have different rotations. `rhombus` and `rhombus2` subdivide `hex` and `hex2` cells into rhombi; `triangle` and `triangle2` subdivide them into triangles. `cairo` is the Cairo pentagonal tessellation. `interval=` The length of one side of a grid cell. Example values: `500m` `2km`. `cols=` The target number of grid columns. For non-square grids, this option sets a comparable horizontal grid resolution, not an exact column count. `rows=` The target number of grid rows. For non-square grids, this option sets a comparable vertical grid resolution, not an exact row count. `cells=` The target number of grid cells. The actual number may be larger because the grid is extended to enclose the target layer. `cell-scale=` Scale each grid cell from its center. Values must be greater than 0 and less than 2. Values less than 1 create gaps between cells; values greater than 1 create overlaps. `rotate=` Rotate the grid by a given number of degrees (similar to `-affine rotate=`). Other options: `name=` `+` `target=` ### -include `` 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. ### -inlay Inscribe a polygon layer within another polygon layer. `` or `source=` File or layer containing polygons to inlay Other options: `target=` ### -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=` ```bash # 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 polygon-to-polygon, point-to-polygon, polygon-to-point or point-to-point spatial join. `` 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](#-calc) 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()` `isMin()` and `isMode()` 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 both `fields` and `calc` are absent, all source fields are copied (except the source key field when joining with `keys=`). If `calc` is present and `fields` is absent, no fields are copied by default unless assigned by `calc`. Use `fields=*` to copy all source fields, including any key field. Use `fields=` (empty list) to copy no fields. `prefix=` Add a prefix to the names of fields joined from the external attribute table. `interpolate=` (polygon-to-polygon joins only) A list of fields to interpolate/reaggregate based on area of overlap. Interpolates fields containing count data, such as population counts or vote counts. Treats data as being uniformly distributed within polygon areas. Also interpolates string fields containing categorical data. The value associated with the largest area of overlap between source and target polygons gets copied to the target feature. `point-method` (polygon-to-polygon joins only) Use an alternate method for joining two polygon layers. The default polygon-polygon join method detects areas of overlap between two polygon layers by compositing the two layers internally. This method is simpler -- it generates a temporary point layer from the source layer with the greater number of features (using the same inner-point method as the `-points inner` command), and then performs a point-to-polygon or polygon-to-point join. This method does not support the `interpolate=` option. `largest-overlap` (polygon-to-polygon joins only) selects a single polygon to join when multiple source polygons overlap a target polygon, based on largest area of overlap. `min-overlap-pct=` (polygon-to-polygon joins only) Only source features with at least this percentage overlap of the target feature (by area) get joined. `min-overlap-area=` (polygon-to-polygon joins only) Only source features with at least this much areal overlap of the target feature get joined. `max-distance=` (point-to-point joins only) Join source layer points within this distance of a target layer point. `duplication` Create duplicate features in the target layer on many-to-one joins. `sum-fields=` (deprecated) 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)'`. `string-fields=` A comma-separated list of fields in source CSV file to import as strings (e.g. FIPS,ZIPCODE). `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. ```bash 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 string-fields=FIPS argument prevents FIPS codes in the CSV file from being converted to numbers.) ```bash mapshaper states.shp \ -join demographics.txt keys=STATE_FIPS,FIPS string-fields=FIPS \ -o out.shp ``` ### -lines Converts points and polygons to lines. Polygons are converted to topological boundaries. Without the `` argument, external (unshared) polygon boundaries are attributed as `TYPE: "outer", RANK: 0` and internal (shared) boundaries are `TYPE: "inner", RANK: 1`. `` or `fields=` (Optional) comma-separated list of attribute fields for creating a hierarchy of polygon boundaries. A single field name adds an intermediate level of hierarchy with attributes: `TYPE: , 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 polygon boundaries 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). `groupby=` Convert a point layer into multiple lines, using a field value for grouping. Common options: `name=` `+` `target=` ```bash # Example: Classify national, state and county boundaries. mapshaper counties.shp -lines STATE_FIPS -o boundaries.shp ``` ```bash # Example: add the names of neighboring countries to each section of border mapshaper countries.geojson \ -lines each='COUNTRIES = A.NAME + (B ? "," + B.NAME : "")' \ -o borders.geojson ``` ### -merge-layers Merge features from several layers into a single layer. Layers can only be merged if they have compatible geometry types. Target layers should also have compatible data 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. `flatten` (polygon layers) Remove polygon overlaps by assigning overlapping areas to the last overlapping polygon (the topmost feature if features are rendered in sequence). Common options: `name=` `target=` ```bash # 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 ``` ### -mosaic Flatten a polygon layer by converting overlapping areas to separate polygons. `calc=` Use a JavaScript expression to handle many-to-one aggregation (similar to the `calc=` option of the`-join` and `-dissolve` functions). See [-calc](#-calc) for a list of supported functions. Common options: `name=` `+` `target=` ### -point-grid Create a rectangular grid of points. `` 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. Common X-coordinate names are auto-detected (e.g. longitude, LON). `y=` Name of field containing y coordinate values. Common Y-coordinate names are auto-detected (e.g. latitude, LAT). `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. `vertices2` Convert all the vertices in polygon and polyline features into points, including duplicate coordinates (e.g. the duplicate endpoint coordinates of polygon rings). `endpoints` Capture the unique endpoints of polygon and polyline arcs. `midpoints` Find the midpoint of each path in a polyline layer. `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=` ```bash # 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. `from-rings` Convert a layer of closed polyline rings into polygons. Nested rings in multipart features are converted into holes. Common options: `target=` ### -proj Project a dataset using a PROJ string, EPSG code or alias. This command affects all layers in the dataset(s) containing the targeted layer or layers. Information on PROJ string syntax can be found on the [PROJ website](https://proj.org/usage/index.html). `` or `crs=` Target CRS, given as a Proj.4 definition or an alias. Use the [`-projections`](#-projections) command to list available projections and aliases. In some projections that require additional parameters, Mapshaper can fit parameters automatically from the data extent, for example `crs=utm` selects a UTM zone. You can also pass a Proj4 string enclosed in quotes, for example `crs='+proj=utm +zone=27'`. `densify` Interpolate vertices along long line segments as needed to approximate curved lines. `match=` Match the projection of the given layer or .prj file. `init=` 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 CRS is WGS84. As with `crs`, you can pass a Proj4 string enclosed in quotes if the selected projection requires extra parameters, for example `init='+proj=utm +zone=33'`. `nodata-color=` (raster) Color for output pixels that do not receive source raster content after reprojection. The default is white for image rasters and the source nodata value, when available, for categorical and continuous rasters. Use `transparent` for transparent output. `background=` (raster) Alias for `nodata-color=`. `resampling=nearest|bilinear` (raster) Resampling method for raster reprojection. Overrides the default set by `-i raster-type=`. Use `bilinear` for smooth continuous-tone imagery and elevation data, and `nearest` for categorical rasters or exact cell values. Bilinear resampling skips nodata source pixels and renormalizes the remaining weights, so a nodata value is never averaged into a real one. `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** ```bash # 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 EPSG:2831 -o out.json # Convert a projected Shapefile to WGS84 coordinates mapshaper area.shp -proj wgs84 -o out.shp # Use the Winkel Tripel projection with a custom central meridian mapshaper countries.shp -proj +proj=wintri +lon_0=10 -o out.shp # Shortcut notation for the above projection mapshaper countries.shp -proj wintri +lon_0=10 -o out.shp # Create Dymaxion-projected layers including a graticule and neatline mapshaper countries.geojson \ -proj dymaxion \ -graticule name=graticule \ -graticule outline name=neatline \ -o target="*" output/ # Convert an unprojected U.S. Shapefile into a composite projection with Alaska # and Hawaii repositioned and rescaled to fit in the lower left corner. # Show Puerto Rico and the U.S. Virgin Islands # Override the default central meridian and scale of the Alaska inset mapshaper us_states.shp \ -proj albersusa +PR +VI +AK.lon_0=-141 +AK.scale=0.4 \ -o out.shp ``` Interrupted Goode Homolosine (`+proj=igh`, `+proj=igh_o`), Interrupted Mollweide (`+proj=imoll`, `+proj=imoll_o`), rectangular tetrahedral projections (`+proj=narukawa2022`, `+proj=markley`, `+proj=calm`), Dymaxion (`+proj=dymaxion`, `+proj=dymaxion2`), and octahedral butterfly projections (`+proj=butterfly`, `+proj=butterfly2`, `+proj=cahill_keyes`) cannot be used as source CRSs or represented by generated Shapefile `.prj` files. They can be used as destinations for vector and raster layers. The `_o` variants are oceanic layouts and default to `+lon_0=-160`. `narukawa2022` uses Narukawa's published 2022 mathematical approximation of the original AuthaGraph modeling process. `markley` and `calm` use L. P. Lee's conformal tetrahedral face projection in two rectangular aspects. `dymaxion` uses the Gray-Fuller facet transformation; `dymaxion2` uses gnomonic facets. `butterfly` and `butterfly2` use the Cahill-Keyes 12-zone facet construction in a butterfly arrangement inspired by Cahill and Waterman; they differ only in their default central meridians of 157.5°E and 20°W, respectively. `cahill_keyes` uses the M-profile and also defaults to 20°W. ### -rectangle Create a new layer containing a rectangular polygon. `bbox=` Give the coordinates of the rectangle. `source=` Create a bounding box around a given layer. `aspect-ratio=` Aspect ratio as a number or range (e.g. 2 0.8,1.6 ,2). `offset=` Padding as a distance or percentage of width/height (single value or list). `name=` Assign a name to the newly created layer. ### -rectangles Create a new layer containing a rectangular polygon for each feature in the layer. `aspect-ratio=` Aspect ratio as a number or range (e.g. 2 0.8,1.6 ,2). `bbox=` Use an expression to generate rectangle bounds for each feature. The expression should evaluate to a GeoJSON-style bbox array. `offset=` Padding as a distance or percentage of width/height (single value or list). `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. `` or `fields=` List of fields to rename as a comma-separated list. Common options: `target=` ```bash # 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). `` or `names=` One or more layer names (comma-separated). `target=` Rename a subset of all layers. ```bash # 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 ``` ### -repel Move colliding point symbols apart. The target must be a projected point layer containing symbols from [`-symbols`](#-symbols), from [`-style`](#-style) or from the `radius=` option. All targeted layers are laid out together, so symbols in different layers are moved apart from each other as well. The command supports symbols with a circular outline: circles, pies, donuts and "ring"-type symbols. Other symbols created with the `-symbols` command, like arrows and polygons, are also supported if a `radius=` option is provided. The layout happens in pixel space, so the command needs to know the display scale. It takes it from a [`-frame`](#-frame) if the target has one, and otherwise requires a `width=` option. Give the same width to `-repel` and to `-o`, or symbols will be spaced for a differently sized map. `width=` Display width of the layer in pixels. Required if the target has no frame. `max-shift=` How far a symbol may move, in pixels (default is 20). Accepts a number, a field name or a JS expression, so the limit can vary from symbol to symbol. A symbol with a limit of 0 gets pinned in place. Symbols too crowded to separate within `max-shift=` are left overlapping `padding=` Pixels of clearance to leave around each symbol (default is 0). Accepts a field name or an expression. Padding surrounds each symbol, so a pair of symbols ends up with the *sum* of their two paddings between them. `margin=` Pixels of clearance to leave between two symbols (default is 0). Accepts a field name or an expression. A margin gives the minimum spacing between two symbols. If two symbols have different margin values, the *greater* of their two margins is used. `radius=` Field or expression giving symbol radius in pixels. Use this when the layer has no symbols from `-symbols` or `-style`. `polygons=` Layer or file of polygons that symbols must stay inside. Each symbol is confined to the polygon its true position falls in. Symbols outside every polygon are left free to move. `ticks=` Number of solver passes (default is 100). `strength=` Portion of each overlap resolved per pass, 0-1 (default is 0.4). Higher values clear crowded areas faster but can leave symbols further from their original positions. Common options: `target=` ``` # Put a dot in each county and keep them inside their respective states mapshaper counties.geojson \ -proj albersusa \ -dissolve STATE + name=states \ -style fill='#eee' stroke=white \ -target counties \ -points inner + name=dots \ -style r=2 fill=magenta \ -repel width=800 polygons=states \ -o width=800 target=states,dots map.svg ``` ### -require Require a Node module or ES module for use in commands like `-each` and `-run`. Modules are added to the expression context. When the `alias=` option is given, modules are accessed via their aliases. Modules that are imported by name (e.g. `-require d3`) are accessed via their name, or by their alias if the `alias=` option is used. Module files without an alias name have their exported functions and data added directly to the expression context. `` or `module=` Name of an installed module or path to a module file. `alias=` Import the module as a custom-named variable. ```bash # Example: use the underscore module (which has been installed locally) $ mapshaper data.json \ -require underscore alias=_ \ -each 'id = _.uniqueId()' \ -o data2.json ``` ```bash # Example: import a module file containing a user-defined function $ mapshaper data.json \ -require scripts/includes.mjs \ -each 'displayname = getDisplayName(d)' \ -o data2.json ``` ### -run Run mapshaper commands from a [command file](/docs/essentials/command-line.html.md#command-files) or generated on-the-fly from a JS expression. `` Either: - A path to a mapshaper [command file](/docs/essentials/command-line.html.md#command-files). - A JS expression or template containing embedded expressions, for generating one or more mapshaper commands. * Embedded expressions are enclosed in curly braces (see below). * Expressions can access `target` and `io` objects. * Expressions can also access functions and data loaded with the `-require` command. * Functions can be async. Expression context: If command has a single target layer: `target` object provides data and information about the command's target layer - `target.layer_name` Name of layer - `target.geojson` (getter/setter) Returns a GeoJSON FeatureCollection for the layer (getter) or replaces the layer with the contents of a GeoJSON object (setter). - `target.geometry_type` One of: polygon, polyline, point, `undefined` - `target.feature_count` Number of features in the layer - `target.null_shape_count` Number of features with null geometry - `target.null_data_count` Number of features with no attribute data - `target.bbox` GeoJSON-style bounding box - `target.proj4` PROJ-formatted string giving the CRS (coordinate reference system) of the layer `targets` object gives access to all layers targetted by the run command. - by numerical index, like an array (`targets[0]` refers to the first target layer) - by layer name (`targets.states` refers to a layer named "states") `io` object has a method for passing data to the `-i` command. - `io.ifile(, )` Create a temp file to use as input in a `-run` command (see example 2 below) **Example 1:** Apply a custom projection based on the layer extent. ```bash $ mapshaper -i country.shp \ -require projection.js \ -run '-proj {tmerc(target.bbox)}' \ -o ``` ```javascript // contents of projection.js file module.exports.tmerc = function(bbox) { var lon0 = (bbox[0] + bbox[2]) / 2, lat0 = (bbox[1] + bbox[3]) / 2; return `+proj=tmerc lat_0=${lat0} lon_0=${lon0}`; }; ``` **Example 2:** Convert points to a Voronoi diagram using a template expression together with an external script. ```bash $ mapshaper points.geojson \ -require script.js \ -run '-i {io.ifile("voronoi.json", voronoi(target.geojson, target.bbox))}' \ -o ``` ```javascript // contents of script.js file module.exports.voronoi = async function(points, bbox) { const d3 = await import('d3-delaunay'); // installed locally const coords = points.features.map(feat => feat.geometry.coordinates); const voronoi = d3.Delaunay.from(coords).voronoi(bbox); const features = Array.from(voronoi.cellPolygons()).map(function(ring, i) { return { type: 'Feature', properties: points.features[i].properties, geometry: { type: 'Polygon', coordinates: [ring] } }; }); return {type: 'FeatureCollection', features: features}; }; ``` ### -scalebar Add a scale bar to an SVG map. The command creates a data-only layer containing the scale bar's data properties. A scale bar is included in the SVG output file if the scale bar layer is included as an output layer. The length of the scale bar reflects the scale in the center of the map's rectangular frame. `