### Install and Import Shapefile.js
Source: https://github.com/calvinmetcalf/shapefile-js/blob/gh-pages/README.md
Instructions for installing the package via npm and importing it into an ESM-based web script.
```bash
npm install shpjs --save
```
```javascript
import shp from 'https://unpkg.com/shpjs@latest/dist/shp.esm.js'
```
--------------------------------
### Browser Usage with Leaflet and CDN
Source: https://context7.com/calvinmetcalf/shapefile-js/llms.txt
Demonstrates loading shapefile data in the browser using the global shp function. Includes examples for fetching from a URL and processing local files via input elements.
```html
```
--------------------------------
### Main Entry Point: shp() - Load Shapefiles
Source: https://context7.com/calvinmetcalf/shapefile-js/llms.txt
The primary function `shp(input)` accepts various input types including URLs (zip or .shp), binary buffers, or File API objects. It returns a Promise that resolves to GeoJSON FeatureCollection(s). For zip files containing multiple shapefiles, it returns an array of FeatureCollections.
```javascript
import shp from 'shpjs';
// Method 1: Load from URL (zip file)
const geojsonFromZip = await shp('https://example.com/data/countries.zip');
console.log(geojsonFromZip);
// {
// type: 'FeatureCollection',
// fileName: 'countries',
// features: [
// {
// type: 'Feature',
// geometry: { type: 'Polygon', coordinates: [...] },
// properties: { NAME: 'France', POP: 67390000 }
// },
// ...
// ]
// }
// Method 2: Load from URL (individual shapefile)
const geojsonFromShp = await shp('https://example.com/data/cities.shp');
// Also works without the .shp extension:
const geojsonAuto = await shp('https://example.com/data/cities');
// Method 3: Load from binary buffer (Node.js)
import { readFile } from 'fs/promises';
const zipBuffer = await readFile('./path/to/shapefile.zip');
const geojsonFromBuffer = await shp(zipBuffer);
// Method 4: Load from File API (browser)
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', async (e) => {
const file = e.target.files[0];
const arrayBuffer = await file.arrayBuffer();
const geojson = await shp(arrayBuffer);
console.log('Parsed features:', geojson.features.length);
});
```
--------------------------------
### Import and Parse Shapefile as ESM in Browser
Source: https://context7.com/calvinmetcalf/shapefile-js/llms.txt
Demonstrates how to import shapefile-js as an ES module directly in the browser to fetch and parse a zipped shapefile. The resulting GeoJSON features are then processed to extract properties and calculate bounding box coordinates.
```html
```
--------------------------------
### Load Shapefile Components from Object
Source: https://context7.com/calvinmetcalf/shapefile-js/llms.txt
Loads a shapefile by passing an object containing buffers for various components like shp, dbf, prj, and cpg. This provides fine-grained control over the input data.
```javascript
import shp from 'shpjs';
import { readFile } from 'fs/promises';
const shapefileObject = {
shp: await readFile('./data/buildings.shp'),
dbf: await readFile('./data/buildings.dbf'),
prj: await readFile('./data/buildings.prj'),
cpg: await readFile('./data/buildings.cpg')
};
const geojson = await shp(shapefileObject);
```
--------------------------------
### Parse Shapefile from URL
Source: https://github.com/calvinmetcalf/shapefile-js/blob/gh-pages/README.md
Load a shapefile or a ZIP archive containing shapefiles directly from a URL and convert it to GeoJSON.
```javascript
import shp from 'shpjs';
// Parse from .shp file
const geojson = await shp("files/pandr.shp");
// Parse from .zip file
const geojsonZip = await shp("files/pandr.zip");
```
--------------------------------
### Parse Shapefile from Component Object
Source: https://github.com/calvinmetcalf/shapefile-js/blob/gh-pages/README.md
Manually construct a shapefile object by providing individual component files (shp, dbf, prj, cpg) as binary buffers.
```javascript
const object = {};
object.shp = await fs.readFile('./path/to/file.shp');
object.dbf = await fs.readFile('./path/to/file.dbf');
object.prj = await fs.readFile('./path/to/file.prj');
object.cpg = await fs.readFile('./path/to/file.cpg');
const geojson = await shp(object);
```
--------------------------------
### Browser Usage with Script Tag
Source: https://context7.com/calvinmetcalf/shapefile-js/llms.txt
Includes the library via CDN for direct browser usage without a bundler. The library exposes a global `shp` function.
```APIDOC
## Browser Usage with Script Tag
### Description
Includes the library via CDN for direct browser usage without a bundler. The library exposes a global `shp` function that can load shapefiles from URLs or file inputs.
### Method
Global `shp` function
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **urlOrBuffer** (string | Buffer | Object) - The URL to a shapefile zip archive, a buffer of a shapefile zip archive, or an object with component buffers.
### Request Example
```html
Shapefile.js Browser Example
```
### Response
#### Success Response (GeoJSON FeatureCollection)
- **geojson** (Object) - A GeoJSON FeatureCollection object representing the shapefile data.
#### Response Example
```json
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": { ... },
"properties": { ... }
}
]
}
```
```
--------------------------------
### Parse Shapefile from Binary Buffer
Source: https://github.com/calvinmetcalf/shapefile-js/blob/gh-pages/README.md
Process a ZIP file containing shapefiles from a binary buffer, such as a Node.js file read or a browser File API object.
```javascript
// Node.js example
const data = await fs.readFile('./path/to/shp.zip');
const geojson = await shp(data);
// Browser File API example
const data = await file.arrayBuffer();
const geojson = await shp(data);
```
--------------------------------
### shp(shapefileObject)
Source: https://context7.com/calvinmetcalf/shapefile-js/llms.txt
Loads shapefile data by passing an object with individual component buffers (shp, dbf, prj, cpg).
```APIDOC
## shp(shapefileObject)
### Description
Loads shapefile data by passing an object with individual component buffers (shp, dbf, prj, cpg). This provides fine-grained control over which files to include.
### Method
`shp`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **shapefileObject** (Object) - Required - An object containing buffers for shapefile components.
- **shp** (Buffer) - Required - The buffer for the .shp file.
- **dbf** (Buffer) - Optional - The buffer for the .dbf file (for attributes).
- **prj** (Buffer) - Optional - The buffer for the .prj file (for projection).
- **cpg** (Buffer) - Optional - The buffer for the .cpg file (for encoding).
### Request Example
```javascript
import shp from 'shpjs';
import { readFile } from 'fs/promises';
// Load all components
const shapefileObject = {
shp: await readFile('./data/buildings.shp'),
dbf: await readFile('./data/buildings.dbf'), // optional - for attributes
prj: await readFile('./data/buildings.prj'), // optional - for projection
cpg: await readFile('./data/buildings.cpg') // optional - for encoding
};
const geojson = await shp(shapefileObject);
// Minimal: geometry only (no attributes, no projection)
const minimalObject = {
shp: await readFile('./data/boundaries.shp')
};
const geometryOnlyGeoJson = await shp(minimalObject);
```
### Response
#### Success Response (GeoJSON FeatureCollection)
- **geojson** (Object) - A GeoJSON FeatureCollection object representing the shapefile data.
#### Response Example
```json
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": { ... },
"properties": { ... }
}
]
}
```
```
--------------------------------
### Initialize Leaflet Map and Load Shapefile Data
Source: https://github.com/calvinmetcalf/shapefile-js/blob/gh-pages/index.html
This snippet initializes a Leaflet map and configures it to display geographic data. It then loads a shapefile from a specified URL using the shapefile-js library and adds the parsed data to the map.
```javascript
var m = L.map('map').setView([34.74161249883172, 18.6328125], 2);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(m)
var geo = L.geoJson({ features: [] }, { onEachFeature: function popUp(f, l) {
var out = [];
if (f.properties) {
for (var key in f.properties) {
out.push(key + ": " + f.properties[key]);
}
l.bindPopup(out.join(" "));
}
}
}).addTo(m);
var base = 'files/TM_WORLD_BORDERS_SIMPL-0.3.zip';
shp(base).then(function (data) {
geo.addData(data);
});
```
--------------------------------
### shp.combine([geometries, attributes])
Source: https://context7.com/calvinmetcalf/shapefile-js/llms.txt
Combines arrays of geometries and attributes into a GeoJSON FeatureCollection. Useful when parsing .shp and .dbf files separately.
```APIDOC
## shp.combine([geometries, attributes])
### Description
Combines arrays of geometries and attributes into a GeoJSON FeatureCollection. Useful when parsing .shp and .dbf files separately.
### Method
`shp.combine`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **geometries** (Array