geojson2svg

repository·master·Indexed 42 days ago

https://github.com/gagan-bansal/geojson2svg

A utility for converting GeoJSON data into SVG strings or path data, compatible with Node.js and browser environments. Version 2.0.5 features a class-based API (GeoJSON2SVG) that supports customizable viewport sizes, map extents, coordinate projection via coordinateConverter, and flexible mapping of GeoJSON properties to SVG attributes.

Tokens
3.6K
Snippets
10
Records
15
Agent score
54%

What's inside geojson2svg

  1. Handle Coordinate Projections

    master

    The library does not automatically project coordinates. If your GeoJSON is in WGS84 (latitude/longitude) but you want a Web Mercator (EPSG:3857) output, you must provide a coordinateConverter function during initialization.

    Recommended tools for projection:

    • reproject-spherical-mercator
    • reproject
    • proj4js
  2. Migrate from geojson2svg 1.x to 2.x

    master

    If you are upgrading from version 1.x, note the following breaking changes:

    1. Class-based API: The default export is no longer a function. You must now import the GeoJSON2SVG class and instantiate it with new.
    2. Map Extent Behavior: In 1.x, the default mapExtent was the Web Mercator projection's full extent. In 2.x, if mapExtent is not provided, mapExtentFromGeojson is assumed to be true (the extent is calculated from the input data).

    Warning: If your input GeoJSON uses Web Mercator projection and you do not specify a mapExtent, your code may fail in 2.x. To fix this, explicitly pass the Web Mercator extent in the options.

  3. Convert SVG strings to HTML DOM elements

    master

    The convert method returns raw strings for modularity. To use these as actual DOM elements in a browser, you must parse them. A common way is using the parse-svg package.

    // Using parse-svg
    var parseSVG = require('parse-svg');
    var svgElements = svgStrings.map(parseSVG);
  4. Use geojson2svg in Node.js or Browser

    master

    The library provides a GeoJSON2SVG class. You can use it with ES6 imports, CommonJS require, or directly in the browser via the global GeoJSON2SVG variable.

    To convert GeoJSON, instantiate the class with configuration options and call the .convert() method.

    // ES6
    import {GeoJSON2SVG} from 'geojson2svg';
    const converter = new GeoJSON2SVG(options);
    const svgStrings = converter.convert(geojson, options);
    
    // CommonJS
    const {GeoJSON2SVG} = require('geojson2svg');
    const converter = new GeoJSON2SVG(options);
    const svgStrings = converter.convert(geojson, options);
    
    // Browser
    const converter = new GeoJSON2SVG(options);
    const svgStrings = converter.convert(geojson, options);
  5. Configure GeoJSON2SVG instance options

    master

    When initializing new GeoJSON2SVG(options), you can provide several configuration keys to control the output:

    • viewportSize: Object {width: number, height: number} in pixels. Default: {width: 256, height: 256}.
    • mapExtent: Object {left: coord, bottom: coord, right: coord, top: coord}. Coordinates must match the GeoJSON projection.
    • mapExtentFromGeojson: Boolean. If true, mapExtent is calculated from the input data. (Note: If mapExtent is omitted, this defaults to true).
    • fitTo: 'width' | 'height'. Fits the output SVG to the specified dimension.
    • coordinateConverter: A function ( [x, y] ) => [x, y] used to transform coordinates during conversion.
    • pointAsCircle: Boolean. If true, points are rendered as <circle> elements instead of paths.
    • r: Number. The radius for point SVG elements.
    • attributes: Configuration for attaching GeoJSON properties to SVG elements (see Attributes Reference).
    • explode: Boolean. Whether to explode multi-GeoJSON into many SVG elements. Default: false.
    • precision: Number. Precision of output SVG coordinates. Default: false.
    • output: 'svg' | 'path'. 'svg' returns the full element string; 'path' returns only the 'd' attribute value. Default: 'svg'.
    • callback: Function. Called for every conversion, receiving the output string as an argument.
  6. Map GeoJSON properties to SVG attributes

    master

    You can control which GeoJSON properties are attached to the resulting SVG elements using the attributes option. This can be passed to the constructor or the .convert() method.

    1. Simple Property Mapping

    Pass an array of strings representing property paths. The last part of the path is used as the SVG attribute name.

    // If feature.properties.name = 'Park'
    attributes: ['properties.name'] 
    // Result: <path name="Park" ... />

    2. Advanced Mapping (Static and Dynamic)

    Pass an array of objects to define complex rules:

    • type: 'static': Always uses the provided value.
    • type: 'dynamic': Extracts a value from the feature using a property path.
    attributes: [
      { type: 'static', property: 'class', value: 'land-mass' },
      { type: 'dynamic', property: 'properties.pop_density', key: 'density' }
    ]
    // Result: <path class="land-mass" density="[value]" ... />
  7. Attach SVG attributes from GeoJSON features

    master

    You can attach attributes from your GeoJSON features to the resulting SVG elements using the attributes option. This option accepts an array of StaticAttribute, DynamicAttribute, or a plain ObjectAttributes map.

    // Example using the attributes option
    const options: Options = {
      attributes: [
        // Static attribute: always uses the same value
        { type: 'static', property: 'fill', value: 'red' },
        // Dynamic attribute: pulls value from a GeoJSON property
        { type: 'dynamic', property: 'opacity', key: 'custom-opacity' },
        // Plain object mapping
        { 'stroke-width': '2' }
      ]
    };
  8. Call the convert method

    master

    The .convert(geojson, options) method returns an array of SVG element strings.

    While most options are set during instantiation, you can override or provide attributes, r, and callback specifically for a single conversion call by passing them in the second argument.

    let svgStrings = converter.convert(geojson, {
      "attributes": ..., 
      "r": 2,
      "callback": function(svgString) { /* ... */ }
    });
  9. Configure conversion Options

    master

    The Options object allows fine-grained control over how GeoJSON is rendered to SVG. Key configuration properties include:

    • viewportSize: An object { width: number, height: number } defining the pixel dimensions.
    • mapExtent: An object { left: number, right: number, bottom: number, top: number } defining the coordinate bounds.
    • mapExtentFromGeojson: If true, the mapExtent is automatically calculated from the provided GeoJSON data.
    • output: Determines the return format: 'svg' (returns full <path d="..."/> strings) or 'path' (returns only the d attribute value).
    • fitTo: Either 'width' or 'height' to scale the output map.
    • coordinateConverter: A function (point: [number, number]) => [number, number] to transform coordinates during conversion.
    • precision: A number defining the decimal precision of the output coordinates.
    • explode: A boolean; if true, MultiGeoJSON features are split into multiple SVG elements.
    • pointAsCircle: If true, GeoJSON points are rendered as SVG <circle> elements instead of paths.
    • r: The radius for point SVG elements when pointAsCircle is enabled.
    • callback: A function (svgString: string) => void called for every converted element.
  10. Reference: Configure SVG attributes

    master

    The attributes option allows you to map GeoJSON properties to SVG attributes. It supports three modes:

    1. Dynamic (List of paths): Maps property paths to attribute keys of the same name. { "attributes": ["properties.foo", "properties.bar"] } Result: <path foo="val" bar="val" ... />

    2. Static (Object): Applies the same value to all elements. { "attributes": {"class": "mapstyle"} } Result: <path class="mapstyle" ... />

    3. Mixed (List of objects): Provides fine-grained control over dynamic and static attributes.

      {
        "attributes": [
          { "property": "properties.foo", "type": "dynamic", "key": "id" },
          { "property": "properties.baz", "type": "dynamic" },
          { "property": "bar", "value": "barStatic", "type": "static" }
        ]
      }

      Result: <path id="fooVal" baz="bazVal" bar="barStatic" ... />

    Note: If a feature lacks the specified property path, the attribute is simply omitted without error.

    // Example of mixed dynamic and static attributes
    const options = {
      attributes: [
        { property: 'properties.foo', type: 'dynamic', key: 'id' },
        { property: 'properties.baz', type: 'dynamic' },
        { property: 'bar', value: 'barStatic', type: 'static' }
      ]
    };
  11. Convert GeoJSON to SVG elements

    master

    Use the .convert(geojson, options) method to transform GeoJSON data into an array of SVG strings (e.g., <path ... /> or <circle ... />).

    Behavior

    • Input Types: Supports FeatureCollection, Feature, GeometryCollection, and individual Geometry objects.
    • Extent Calculation: If mapExtent was not provided during initialization, the converter calculates the bounding box of the input GeoJSON using geojson-bbox and resets the internal state after conversion.
    • Output: Returns an array of SVG element strings. If options.output is set to something other than 'svg', it returns the raw path data.
    • Callback: If options.callback is provided, it is called with the resulting array of SVG elements.
    const { GeoJSON2SVG } = require('geojson2svg');
    const converter = new GeoJSON2SVG({ viewportSize: { width: 500, height: 500 } });
    
    const geojson = {
      type: 'Feature',
      geometry: { type: 'Point', coordinates: [0, 0] },
      properties: { id: 'my-point' }
    };
    
    const svgElements = converter.convert(geojson);
    // Returns: ['<path d="..." id="my-point" />']