### 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) - Required - An array of geometry objects. - **attributes** (Array | null) - Optional - An array of attribute objects. If null, properties will be empty. ### Request Example ```javascript import shp from 'shpjs'; import { readFile } from 'fs/promises'; // Read and parse components separately const shpBuffer = await readFile('./data/roads.shp'); const dbfBuffer = await readFile('./data/roads.dbf'); const prjString = await readFile('./data/roads.prj', 'utf-8'); const geometries = shp.parseShp(shpBuffer, prjString); const attributes = shp.parseDbf(dbfBuffer); // Combine into FeatureCollection const featureCollection = shp.combine([geometries, attributes]); // Without attributes (creates empty properties) const geometryOnly = shp.combine([geometries, null]); ``` ### Response #### Success Response (GeoJSON FeatureCollection) - **featureCollection** (Object) - A GeoJSON FeatureCollection object. #### Response Example ```json { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "LineString", "coordinates": [...] }, "properties": { "ROAD_NAME": "Main St", "SPEED_LIMIT": 35 } } ] } ``` ``` -------------------------------- ### Parse DBF Attributes with shapefile-js Source: https://context7.com/calvinmetcalf/shapefile-js/llms.txt Parses a raw .dbf file buffer into an array of attribute objects. Supports optional .cpg content for handling non-UTF8 character encodings. ```javascript import shp from 'shpjs'; import { readFile } from 'fs/promises'; // Read DBF file const dbfBuffer = await readFile('./data/cities.dbf'); // Parse attributes const attributes = shp.parseDbf(dbfBuffer); console.log(attributes); // With character encoding file for non-UTF8 data const cpgContent = await readFile('./data/cities.cpg', 'utf-8'); const attributesEncoded = shp.parseDbf(dbfBuffer, cpgContent); ``` -------------------------------- ### shp(input) Source: https://github.com/calvinmetcalf/shapefile-js/blob/gh-pages/README.md The primary function for parsing shapefile data. It accepts a URL string, a binary buffer (zip file), or an object containing specific file components. ```APIDOC ## [FUNCTION] shp(input) ### Description Parses a shapefile or zip archive containing shapefiles and returns GeoJSON data projected into WGS84. If multiple shapefiles are present in a zip, it returns an array of GeoJSON objects. ### Method N/A (Library Function) ### Parameters #### Request Body - **input** (string | ArrayBuffer | Object) - Required - Can be a URL to a .shp or .zip file, a binary buffer containing a zip file, or an object containing 'shp', 'dbf', 'prj', and 'cpg' buffers. ### Request Example ```javascript // URL example const geojson = await shp("files/pandr.zip"); // Object example const object = { shp: shpBuffer, dbf: dbfBuffer, prj: prjBuffer, cpg: cpgBuffer }; const geojson = await shp(object); ``` ### Response #### Success Response (200) - **geojson** (Object | Array) - The resulting GeoJSON object(s). Each object includes a 'fileName' property representing the original file name. #### Response Example ```json { "type": "FeatureCollection", "fileName": "pandr", "features": [...] } ``` ``` -------------------------------- ### shp.parseDbf(dbfBuffer, cpgString) Source: https://context7.com/calvinmetcalf/shapefile-js/llms.txt Parses raw .dbf file buffer to extract feature attributes. Optionally accepts .cpg content for non-UTF8 encoded files. Returns an array of attribute objects. ```APIDOC ## shp.parseDbf(dbfBuffer, cpgString) ### Description Parses raw .dbf file buffer to extract feature attributes. Optionally accepts .cpg content for non-UTF8 encoded files. Returns an array of attribute objects. ### Method `shp.parseDbf` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **dbfBuffer** (Buffer) - Required - The buffer containing the DBF file content. - **cpgString** (string) - Optional - The content of the CPG file for character encoding. ### Request Example ```javascript import shp from 'shpjs'; import { readFile } from 'fs/promises'; // Read DBF file const dbfBuffer = await readFile('./data/cities.dbf'); // Parse attributes const attributes = shp.parseDbf(dbfBuffer); console.log(attributes); // With character encoding file for non-UTF8 data const cpgContent = await readFile('./data/cities.cpg', 'utf-8'); const attributesEncoded = shp.parseDbf(dbfBuffer, cpgContent); ``` ### Response #### Success Response (Array of Objects) - **attributes** (Array) - An array where each object represents the attributes of a feature. #### Response Example ```json [ { "NAME": "New York", "POPULATION": 8336817, "COUNTRY": "USA" }, { "NAME": "London", "POPULATION": 8982000, "COUNTRY": "GBR" }, { "NAME": "Tokyo", "POPULATION": 13960000, "COUNTRY": "JPN" } ] ``` ``` -------------------------------- ### Parse Zip Archive: shp.parseZip(buffer, whiteList) Source: https://context7.com/calvinmetcalf/shapefile-js/llms.txt The `shp.parseZip(buffer, whiteList)` function specifically parses a zip file buffer. It can handle zip archives containing multiple shapefiles, returning an array of GeoJSON FeatureCollections. An optional `whiteList` parameter allows specifying additional file extensions to extract from the zip. ```javascript import shp from 'shpjs'; // In Node.js import { readFile } from 'fs/promises'; const buffer = await readFile('./data/multiple_layers.zip'); // Parse zip with multiple shapefiles const results = await shp.parseZip(buffer); // If zip contains multiple shapefiles, returns an array if (Array.isArray(results)) { results.forEach(layer => { console.log(`Layer: ${layer.fileName}`); console.log(`Features: ${layer.features.length}`); }); } else { // Single shapefile returns a single FeatureCollection console.log(`Features: ${results.features.length}`); } // With whitelist for additional file types const resultsWithExtras = await shp.parseZip(buffer, ['json', 'txt']); ``` -------------------------------- ### Combine Geometries and Attributes into GeoJSON Source: https://context7.com/calvinmetcalf/shapefile-js/llms.txt Merges separate geometry and attribute arrays into a standard GeoJSON FeatureCollection. This is useful when processing .shp and .dbf components independently. ```javascript import shp from 'shpjs'; import { readFile } from 'fs/promises'; const shpBuffer = await readFile('./data/roads.shp'); const dbfBuffer = await readFile('./data/roads.dbf'); const prjString = await readFile('./data/roads.prj', 'utf-8'); const geometries = shp.parseShp(shpBuffer, prjString); const attributes = shp.parseDbf(dbfBuffer); // Combine into FeatureCollection const featureCollection = shp.combine([geometries, attributes]); // Without attributes const geometryOnly = shp.combine([geometries, null]); ``` -------------------------------- ### Parse SHP Geometry: shp.parseShp(shpBuffer, prjString) Source: https://context7.com/calvinmetcalf/shapefile-js/llms.txt The `shp.parseShp(shpBuffer, prjString)` function parses a raw .shp file buffer directly. It can optionally take a projection string (`.prj` file content) or a proj4 object to transform coordinates to WGS84. It returns an array of GeoJSON geometry objects. ```javascript import shp from 'shpjs'; import { readFile } from 'fs/promises'; // Read individual shapefile components const shpBuffer = await readFile('./data/parcels.shp'); const prjString = await readFile('./data/parcels.prj', 'utf-8'); // Parse with projection transformation (converts to WGS84) const geometries = shp.parseShp(shpBuffer, prjString); console.log(geometries); // [ // { type: 'Polygon', coordinates: [[[-122.4, 37.8], [-122.3, 37.8], ...]] }, // { type: 'Polygon', coordinates: [[[-122.5, 37.7], [-122.4, 37.7], ...]] }, // ... // ] // Parse without projection (keeps original coordinates) const rawGeometries = shp.parseShp(shpBuffer); console.log(rawGeometries[0].coordinates); // Original coordinate system values ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.