English · Deutsch
Load ESRI Shapefiles straight into Leaflet, without converting them to GeoJSON first.
The binary .shp data is read into flat typed arrays, and Leaflet layers are built directly from those arrays. There are no GeoJSON features and no intermediate coordinate arrays.
.shp: all shape types (Point, MultiPoint, PolyLine, Polygon, each with Z/M, plus MultiPatch rings).dbfattributes (C, N, F, L, D, I, O, +). The text encoding comes from the.cpg, the language-driver byte, or auto-detection (UTF-8, falling back to Windows-1252).- Coordinate systems:
- WGS 84, Web Mercator, UTM and Gauss-Krüger (incl. the DHDN datum shift) are built in and read from the
.prj. - Without a
.prj, the CRS is auto-detected from the coordinate range. - Other projections work through an optional
proj4.
- WGS 84, Web Mercator, UTM and Gauss-Krüger (incl. the DHDN datum shift) are built in and read from the
.ziparchives without dependencies (uses the nativeDecompressionStream), including several shapefiles per archive- Very large files (gigabytes) through
ShapefileCanvasLayer: the file is streamed, stored compactly, drawn on one canvas, and a click reads the attributes straight from the.dbf. - Inputs: URL,
File/FileList(e.g. drag & drop),ArrayBuffer, or{ shp, dbf, prj, cpg } - Dependencies: only
leaflet(peer dependency). TypeScript types are included.
pnpm add leaflet-shape leaflet
# or
npm install leaflet-shape leaflet
# or
yarn add leaflet-shape leafletOr with a script tag. This registers L.shapefile, L.shapefileCanvas and window.LeafletShape:
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://unpkg.com/leaflet-shape/dist/leaflet-shape.iife.min.js"></script>
<script>
L.shapefile('data/roads.shp').addTo(map); // also fetches roads.dbf/.prj/.cpg next to it
</script>import L from 'leaflet';
import { shapefile } from 'leaflet-shape';
const layer = shapefile('data/municipalities.zip', {
style: (f) => ({ color: f.properties.TYPE === 'city' ? '#c00' : '#36f', weight: 1 }),
onEachFeature: (f, layer) => layer.bindPopup(String(f.properties.NAME)),
})
.on('load', () => map.fitBounds(layer.getBounds()))
.on('error', (e) => console.error(e.error))
.addTo(map);
await layer.ready; // alternative to the 'load' eventFile upload / drag & drop:
input.addEventListener('change', () => shapefile(input.files).addTo(map));shapefile() / ShapefileLayer |
shapefileCanvas() / ShapefileCanvasLayer |
|
|---|---|---|
| Meant for | up to ~50 MB / ~100,000 features | any size (tested: 1.4 GB, 6 M polygons) |
| Renders as | one L.Polygon/L.Polyline/L.CircleMarker per feature |
a single canvas |
| Attributes | all in memory (feature.properties) |
stay in the .dbf; a click reads one row |
| Interaction | everything Leaflet layers can do (popups, hover, setStyle) |
click event with feature.properties, pointer cursor |
import { shapefileCanvas } from 'leaflet-shape';
const layer = shapefileCanvas(fileInput.files, {
style: (f) => ({ color: f.properties.USE === 'garage' ? '#888' : '#36f', weight: 1 }),
filter: (f) => f.kind === 'polygon',
})
.on('progress', (e) => console.log(e.phase, e.loaded, e.total))
.on('load', () => map.fitBounds(layer.getBounds()))
.on('click', (e) =>
L.popup().setLatLng(e.latlng).setContent(JSON.stringify(e.feature.properties)).openOn(map),
)
.addTo(map);How the canvas layer works:
- The
.shpis streamed in 16 MB chunks, including straight out of a.zip. - Coordinates are projected once into map units and stored as
Float32offsets from each feature's origin. This takes about half the memory of the file and stays accurate to below 1 mm. - A packed Hilbert R-tree finds the visible features.
- Complex shapes get precomputed simplification levels. Features smaller than a pixel are painted together as a single pixel mask.
- Drawing is progressive and goes into an off-screen canvas, which replaces the visible one only when the frame is complete.
styleandfilterare evaluated once while loading, with one sequential pass over the.dbf.
Measured with a 1.4 GB .shp (6 M polygons, 66 M vertices, Node 26):
| Measurement | Result |
|---|---|
| Load | ≈ 8 s |
| Memory | ≈ 930 MB |
| Render full extent | ≈ 330 ms |
| Render street level | ≈ 25 ms |
| Hit test (click) | ≈ 2 µs |
| Read one attribute row | ≈ 2 ms |
Canvas layer options, in addition to the CRS options below:
style: object or function withcolor,weight,opacity,fill,fillColor,fillOpacity,radius,dashArraydatasetStylesfilterencodingpadding(default0.1)interactive(defaulttrue)tolerance(click tolerance in px, default3)
Methods:
load(source),setStyle(style),getBounds(),featureAt(containerPoint),getProperties(dataset, index),redraw()- the dataset methods described below
Events: progress, load, error, click, render.
Every .shp in a zip (or in a file selection) becomes its own dataset. A dataset is named after its file without the extension, e.g. buildings for data/buildings.shp. If files in different folders share a name, the path is used instead (north/buildings). Both layer types offer the same API:
const layer = shapefileCanvas('cadastre.zip', {
style: { weight: 1, fillOpacity: 0.3 }, // applies to all datasets
datasetStyles: { // per dataset, merged over `style`
buildings: { color: '#d62728' },
parcels: { color: '#555', fillOpacity: 0.05 },
roads: (f) => ({ color: f.properties.CLASS === 'A' ? '#000' : '#888' }),
},
}).addTo(map);
await layer.ready;
layer.getDatasetNames(); // ['buildings', 'parcels', 'roads', …]
layer.setDatasetStyle('parcels', { color: '#00f' });
layer.setDatasetVisible('roads', false);
map.fitBounds(layer.getDatasetBounds('buildings'));
layer.getDatasetStyle('parcels'); // effective style, e.g. for a color picker- If no style sets a
color, each dataset gets its own color fromDATASET_COLORS. - Names in
datasetStylesare case-insensitive. - Styles are layered in this order: the automatic color, then
style, then the dataset's own style. - Style functions also receive
feature.dataset.
The CRS is decided in this order:
- A
transformoption (your own function) always wins. - If there is a
.prj(otherwise thecrsoption is used):- Geographic: coordinates are used as lng/lat.
- Web Mercator: built in.
- Transverse Mercator (UTM, Gauss-Krüger): parameters are read from the WKT and converted with a built-in inverse. DHDN data also gets the 7-parameter Helmert shift to WGS 84. Results are within 5 cm of proj4.
- Well-known EPSG codes in
crsare built in: 25828–25838, 326xx, 4647, 5650, 31466–31469, 3857, 4326. - Anything else uses
proj4, if you pass it.
- If there is no
.prjand the coordinates clearly aren't lng/lat, the CRS is auto-detected from the value range:- Zone-prefixed UTM (
32xxxxxx) and Gauss-Krüger are unambiguous. - For plain UTM, the zone that puts the data inside the expected region wins. The default region is Germany; change it with
autoCrs: { region, zones }. - For eastings of roughly 250,000–500,000, UTM zones 32N and 33N both fit. Zone 32N is chosen and the result is marked as ambiguous (
dataset.crs.alternatives). Setcrs: 'EPSG:25833'to override it.
- Zone-prefixed UTM (
The CRS that was used ends up in dataset.crs (label, epsg, auto, alternatives).
shapefile('old.zip', { crs: 'EPSG:31468' }); // no .prj, Gauss-Krüger zone 4
import proj4 from 'proj4';
shapefile('lambert.zip', { proj4 }); // only needed for projections that aren't built in| Option | Type | Description |
|---|---|---|
style |
PathOptions | (feature) => PathOptions |
Style for lines, polygons and default point markers |
datasetStyles |
Record<string, style> |
Style per dataset (see above) |
pointToLayer |
(feature, latlng) => L.Layer |
Custom point layer (default: L.CircleMarker) |
onEachFeature |
(feature, layer) => void |
e.g. bind popups |
filter |
(feature) => boolean |
Skip features |
transform |
(x, y, z?) => L.LatLng |
Custom coordinate conversion |
crs |
string |
CRS to assume without a .prj (WKT, EPSG code, proj4 string) |
autoCrs |
boolean | { region, zones } |
Auto-detect the CRS without a .prj (default true) |
proj4 |
proj4 function |
Only for projections that aren't built in |
encoding |
string |
Force the .dbf encoding (any TextDecoder label) |
pathOptions |
PolylineOptions |
e.g. smoothFactor, noClip, renderer |
fetchOptions |
RequestInit |
For URL sources |
feature is not GeoJSON. It is { index, dataset, properties, record }, where record holds the raw data (coords, parts, z, m, bbox, type). Every created layer carries its feature as layer.shapeFeature.
Methods:
load(source),addData(datasets),setStyle(style),resetStyle(layer?)- the dataset methods described above
- everything from
L.FeatureGroup
Events: load (e.datasets), error (e.error).
You can use the parsers without any Leaflet layer, e.g. in a Web Worker:
import { readShapefile, iterateShp, parseDbf, detectCrs } from 'leaflet-shape';
const [ds] = await readShapefile(file); // { name, header, records, properties, fields, prj, encoding }
for (const rec of iterateShp(shpBuffer)) {
/* rec.coords: Float64Array x0, y0, x1, y1, … */
}- From about 50 MB on, use
shapefileCanvasinstead ofshapefile.shapefilecreates one Leaflet layer per feature and oneL.LatLngper vertex, which crashes the browser tab on multi-GB files. - Polygon rings are grouped by winding order (outer rings clockwise, holes counter-clockwise), and each hole goes to the smallest outer ring that contains it. Files with wrong winding are handled leniently.
- The canvas layer fills with the non-zero rule, so holes only show up when rings are oriented as the shapefile spec requires.
- Not supported:
- ZIP64 (archives > 4 GB)
- encrypted zips
- memo fields (
.dbt)
- In the canvas layer, MultiPatch triangle strips are drawn as areas.
pnpm install
pnpm dev # esbuild watch + server → http://localhost:8000/examples/
pnpm test # vitest
pnpm typecheck
pnpm build # dist/: ESM, CJS, IIFE (+ .min) and .d.tsReleases are automated with release-please. Use Conventional Commits:
fix: …makes a patch release.feat: …makes a minor release.feat!: …or aBREAKING CHANGE:footer makes a major release.
While the version is below 1.0, breaking changes bump the minor version.