csv2geojson

repository·gh-pages·Indexed 18 days ago

https://github.com/mapbox/csv2geojson

A utility for converting CSV and TSV files into GeoJSON FeatureCollections. It is available as a CLI binary, a Node.js library, and a browser-ready script. The tool supports automatic delimiter detection, custom latitude/longitude field mapping, and functions to convert point collections into LineStrings or Polygons.

Tokens
2.5K
Snippets
9
Records
11
Agent score
63%

What's inside csv2geojson

  1. Use csv2geojson in webpages

    gh-pages

    You can include csv2geojson directly in a browser environment by referencing the latest build via npmcdn:

    https://npmcdn.com/csv2geojson@latest/csv2geojson.js

    <script src="https://npmcdn.com/csv2geojson@latest/csv2geojson.js"></script>
  2. Use csv2geojson as a CLI binary

    gh-pages

    You can install csv2geojson globally and use it to convert CSV or TSV files to GeoJSON via the command line. By default, it looks for latitude and longitude columns using case-insensitive patterns like /^Lat/i.

    npm install -g csv2geojson
    csv2geojson geodata.csv > geodata.geojson
  3. Use csv2geojson in Node.js

    gh-pages

    To use the library in a Node.js project, install it as a dependency and use the csv2geojson.csv2geojson method. This method accepts a CSV string and an optional configuration object, and returns the data via a callback.

    var csv2geojson = require('csv2geojson');
    
    // Basic usage with default settings
    csv2geojson.csv2geojson(csvString, function(err, data) {
        // err has any parsing errors
        // data is the GeoJSON FeatureCollection
    });
    
    // Usage with explicit configuration
    csv2geojson.csv2geojson(csvString, {
        latfield: 'LATFIELDNAME',
        lonfield: 'LONFIELDNAME',
        delimiter: ','
    }, function(err, data) {
        // err has any parsing errors
        // data is the GeoJSON FeatureCollection
    });
  4. Reference the csv2geojson Node.js API

    gh-pages

    The following methods are available in the Node.js API:

    • csv2geojson.csv2geojson(csvString, [options], callback): Parses a CSV/TSV string into a GeoJSON FeatureCollection. options can include latfield, lonfield, and delimiter. delimiter can be a specific character (e.g., ',', ' ', '|') or 'auto' to attempt to detect the best delimiter from ,, , |, or ;.
    • csv2geojson.dsv(delimiter).parse(dsvString): Uses the dsv library for barebones DSV parsing.
    • csv2geojson.auto(dsvString): Automatically chooses a delimiter and parses the string.
    • csv2geojson.toPolygon(gj): Converts a GeoJSON object of points into a Polygon based on the coordinate order.
    • csv2geojson.toLine(gj): Converts a GeoJSON object of points into a LineString based on the coordinate order.
  5. Reference the csv2geojson CLI options

    gh-pages

    When using the CLI, you can specify the following options to control the conversion process:

    Usage: csv2geojson --lat [string] --lon [string] --line [boolean] --delimiter [string] FILE
    
    Options:
      --lat        the name of the latitude column
      --lon        the name of the longitude column
      --line       whether or not to output points as a LineString  [default: false]
      --delimiter  the type of delimiter                            [default: ","]
      --numeric-fields comma separated list of fields to convert to numbers
  6. Convert CSV strings to GeoJSON with csv2geojson()

    gh-pages

    The csv2geojson function converts a CSV string (or an array of parsed objects) into a GeoJSON FeatureCollection. It automatically attempts to detect latitude and longitude headers if they are not explicitly provided.

    Arguments:

    • x: The CSV string to parse, or an array of objects already parsed from CSV.
    • options: An object to configure the conversion:
      • delimiter: The character used to separate values (e.g., ',', ';', '\t', '|'). Use 'auto' to attempt automatic detection.
      • latfield: The name of the column containing latitude values. If omitted, the function uses regex to guess the header.
      • lonfield: The name of the column containing longitude values. If omitted, the function uses regex to guess the header.
      • crs: A string representing the Coordinate Reference System. If provided, it is added to the FeatureCollection under crs.properties.name.
      • numericFields: A comma-separated string of column names that should be cast to numbers.
      • includeLatLon: A boolean. If false (default), the latitude and longitude columns are removed from the feature properties in the output GeoJSON.
    • callback: A function called with (errors, featurecollection). errors will be an array of error objects if any rows contain invalid coordinates, otherwise null.
    const { csv2geojson } = require('csv2geojson');
    
    const csvData = 'lat,lon,name\n45.5,-122.6,Portland';
    
    csv2geojson(csvData, { latfield: 'lat', lonfield: 'lon' }, (err, geojson) => {
        if (err) {
            console.error('Errors:', err);
        }
        console.log(JSON.stringify(geojson, null, 2));
    });
  7. Automatically detect CSV delimiter

    gh-pages

    You can use the auto function to parse a CSV string by automatically detecting the delimiter (supporting ,, ;, \t, and |). It selects the delimiter that results in the highest number of columns (arity) consistently across all rows.

    Alternatively, when calling csv2geojson, you can set the delimiter option to 'auto'.

    const { auto } = require('csv2geojson');
    
    const data = 'name;lat;lon\nTest;45;-122';
    const parsed = auto(data);
    
    // Or in csv2geojson
    csv2geojson(data, { delimiter: 'auto' }, (err, geojson) => {
        // ...
    });
  8. Identify Latitude and Longitude headers

    gh-pages

    The library provides utility functions to check if a string matches common latitude or longitude header patterns using regular expressions.

    • isLat(f): Returns true if the string f matches latitude patterns (e.g., 'Lat', 'Latitude').
    • isLon(f): Returns true if the string f matches longitude patterns (e.g., 'Lon', 'Long', 'Longitude').
    • guessLatHeader(row): Given a parsed row object, returns the key name that most likely represents latitude.
    • guessLonHeader(row): Given a parsed row object, returns the key name that most likely represents longitude.
  9. Convert GeoJSON Point collections to LineString or Polygon

    gh-pages

    If you have a GeoJSON FeatureCollection consisting of Point features, you can aggregate them into a single geometry using toLine or toPolygon.

    • toLine(gj): Creates a FeatureCollection containing a single LineString feature. The coordinates are taken from the points in the input, and properties are aggregated into arrays (one entry per original feature) within the new feature's properties.
    • toPolygon(gj): Creates a FeatureCollection containing a single Polygon feature. The coordinates are taken from the points in the input (as the exterior ring), and properties are aggregated into arrays.
    const { toLine, toPolygon } = require('csv2geojson');
    
    // Assuming 'geojson' is a FeatureCollection of Points
    const line = toLine(geojson);
    const polygon = toPolygon(geojson);
  10. Reference the csv2geojson CLI flags

    gh-pages

    The following flags are available when using the csv2geojson CLI:

    FlagDescriptionDefault
    --latThe name of the latitude columnRequired
    --lonThe name of the longitude columnRequired
    --lineWhether or not to output points as a LineStringfalse
    --delimiterThe type of delimiter (e.g., , or \t),
    --numeric-fieldsA comma-separated list of fields to convert to numbersNone
    Usage: ./csv2geojson --lat [string] --lon [string] --delimiter [string] FILE
    
    Options:
      --lat             the name of the latitude column
      --lon             the name of the longitude column
      --line            whether or not to output points as a LineString       [default: false]
      --delimiter       the type of delimiter                                 [default: ","]
      --numeric-fields  comma separated list of fields to convert to numbers
  11. Use csv2geojson as a CLI tool

    gh-pages

    You can use csv2geojson as a command-line utility to convert CSV or TSV files into GeoJSON. The tool accepts a file path as a positional argument or reads from stdin. If no file is provided, it defaults to reading from standard input.

    ./csv2geojson --lat [latitude_column_name] --lon [longitude_column_name] [FILE]