Shapefile.js

repository·gh-pages·Indexed 21 days ago

https://github.com/calvinmetcalf/shapefile-js

A pure JavaScript library for parsing Shapefiles and returning GeoJSON projected into WGS84. It supports loading data via URLs, binary buffers (ArrayBuffer, TypedArray, DataView, Node.js Buffer), or objects containing individual component files (.shp, .dbf, .prj, .cpg). The library provides high-level functions like getShapefile() and parseZip(), as well as low-level utilities such as parseShp(), parseDbf(), and combine().

Tokens
2K
Snippets
9
Records
11
Agent score
72%

What's inside shpjs

  1. How zipfile parsing handles multiple shapefiles

    gh-pages

    When parsing a .zip file:

    • If the zip contains only one .shp file, shp() returns a single GeoJSON object.
    • If the zip contains multiple .shp files, shp() returns an array of GeoJSON objects.

    All returned GeoJSON objects include an extra property fileName, which contains the name of the shapefile minus its extension (e.g., the common part of the filename).

  2. Include shpjs in a webpage via CDN or ESM import

    gh-pages

    To use Shapefile.js in a browser without a bundler, you can use unpkg to include the standalone script or import it directly into an ESM-based web script.

    Standalone script (old fashioned way):

    • https://unpkg.com/shpjs@latest/dist/shp.js
    • https://unpkg.com/shpjs@latest/dist/shp.min.js

    ESM Import:

    import shp from 'https://unpkg.com/shpjs@latest/dist/shp.esm.js'
  3. Parse shapefiles using URLs

    gh-pages

    You can pass a URL directly to the shp function. This works for both a direct .shp file URL or a .zip file URL containing the shapefile.

    Example: Loading a .shp file

    import shp from 'shpjs';
    const geojson = await shp("files/pandr.shp");

    Example: Loading a .zip file

    import shp from 'shpjs';
    const geojson = await shp("files/pandr.zip");
  4. Parse shapefiles using an object of component files

    gh-pages

    You can pass an object containing the individual components of a shapefile to the shp function. This is useful when you have the files separated.

    Object Properties:

    • shp: (Required) The .shp file buffer.
    • dbf: (Optional) The .dbf file buffer. Required if you want to include attributes.
    • prj: (Optional) The .prj file buffer. Required if the file uses a projection that needs conversion to WGS84.
    • cpg: (Optional) The .cpg file buffer. Required if the .dbf uses a non-UTF8 encoding.

    Example:

    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);
  5. Parse shapefiles using binary buffers

    gh-pages

    You can pass a binary buffer containing a zip file (which must contain at least one shapefile) to the shp function. Supported types include ArrayBuffer, TypedArray, DataView, and Node.js Buffer.

    Example: In Node.js

    const data = await fs.readFile('./path/to/shp.zip');
    const geojson = await shp(data);

    Example: In the Browser (using File API)

    const data = await file.arrayBuffer();
    const geojson = await shp(data);
  6. Reference the TM_WORLD_BORDERS-0.1 dataset schema

    gh-pages

    The TM_WORLD_BORDERS-0.1.ZIP dataset contains country and area border polygons. When processing this shapefile, you can access the following attributes for each feature:

    ColumnTypeDescription
    ShapePolygonCountry/area border as polygon(s)
    FIPSString(2)FIPS 10-4 Country Code
    ISO2String(2)ISO 3166-1 Alpha-2 Country Code
    ISO3String(3)ISO 3166-1 Alpha-3 Country Code
    UNShort Integer(3)ISO 3166-1 Numeric-3 Country Code
    NAMEString(50)Name of country/area
    AREALong Integer(7)Land area, FAO Statistics (2002)
    POP2005Double(10,0)Population, World Population Prospects (2005)
    REGIONShort Integer(3)Macro geographical (continental region), UN Statistics
    SUBREGIONShort Integer(3)Geographical sub-region, UN Statistics
    LONFLOAT (7,3)Longitude
    LATFLOAT (6,3)Latitude
  7. Parse shapefiles with getShapefile()

    gh-pages

    The primary entrypoint for converting shapefile data into GeoJSON. getShapefile is highly versatile and accepts several input types:

    1. URL (string): A URL pointing to a .zip file or a .shp file (and its associated .dbf, .prj, etc.). If a .zip is provided, it will be unzipped and parsed.
    2. Buffer/ArrayBuffer: A buffer containing a zipped shapefile.
    3. Object: An object containing individual buffers for shp and optionally dbf, cpg, or prj.

    If the input is a .zip file containing multiple layers, the function returns an array of GeoJSON objects. If it contains a single layer, it returns that single GeoJSON object.

    import getShapefile from 'shapefile-js';
    
    // From a URL
    const geojson = await getShapefile('https://example.com/data.zip');
    
    // From a Buffer (zip file)
    const geojsonFromBuffer = await getShapefile(zipBuffer);
    
    // From an object of buffers
    const geojsonFromParts = await getShapefile({
      shp: shpBuffer,
      dbf: dbfBuffer,
      prj: prjBuffer
    });
  8. Combine shape and dbf data with combine()

    gh-pages

    The combine function takes two arrays—one for geometries (shp) and one for properties (dbf)—and merges them into a single GeoJSON FeatureCollection.

    • shp: An array of geometry objects.
    • dbf: An array of property objects. If dbf is not provided or is shorter than shp, empty objects {} are used for the missing properties.
    import { combine } from 'shapefile-js';
    
    const geojson = combine([
      [{ type: 'Point', coordinates: [0, 0] }], // shp array
      [{ name: 'Location A' }]                   // dbf array
    ]);
    // Result: { type: 'FeatureCollection', features: [{ type: 'Feature', geometry: ..., properties: { name: 'Location A' } }] }
  9. Parse a zipped shapefile with parseZip()

    gh-pages

    Use parseZip to manually parse a buffer containing a ZIP archive. It automatically handles .shp, .prj, .dbf, .cpg, and .json files within the archive.

    If the ZIP contains .prj files, they are processed using proj4 to handle coordinate transformations. You can provide a whiteList of file extensions to include specific non-standard files from the ZIP.

    import { parseZip } from 'shapefile-js';
    
    // buffer is the ArrayBuffer of the zip file
    // whiteList is an optional array of extensions to include
    const geojson = await parseZip(buffer, ['geojson', 'custom']);
  10. Parse shape components with parseShp() and parseDbf()

    gh-pages

    For low-level control, you can use the exported internal parsing functions directly:

    • parseShp(shp, prj): Parses a shape buffer. shp should be a DataView or ArrayBuffer. prj can be a string (projection definition) or a proj4 transformed object. If prj is invalid, it defaults to false.
    • parseDbf(dbf, cpg): Parses a DBF buffer. dbf should be a DataView or ArrayBuffer. cpg is an optional character encoding file (as a string or buffer).
    import { parseShp, parseDbf } from 'shapefile-js';
    
    // Parsing shape
    const geometries = await parseShp(shpBuffer, prjString);
    
    // Parsing attributes
    const properties = await parseDbf(dbfBuffer, cpgBuffer);