datamaps

repository·master·Indexed 26 days ago

https://github.com/markmarkoh/datamaps

An SVG-based library for creating interactive geographical data visualizations, such as choropleths and bubble maps. Built on top of D3.js and TopoJSON, version 0.5.9 allows for data-driven map coloring, bubble rendering on specific coordinates, and responsive map configurations.

Tokens
3.1K
Snippets
6
Records
12
Agent score
87%

What's inside datamaps

  1. Understand TopoJSON vs GeoJSON

    master

    TopoJSON is an extension of GeoJSON designed to encode topology. Instead of representing geometries discretely, TopoJSON stitches geometries together using shared line segments called arcs.

    Key benefits include:

    • Compactness: Typical TopoJSON files are approximately 80% smaller than their GeoJSON equivalents by eliminating redundancy.
    • Topology-aware features: Facilitates advanced mapping applications such as topology-preserving shape simplification, automatic map coloring, and cartograms.
  2. Configure Responsive Maps

    master

    To make a map responsive, set responsive: true in the options. You must then listen for the window resize event and manually call map.resize().

    Note: Avoid using hard pixel values for the container's height and width; use percentages instead. If your map's aspect ratio is not 16:9 (0.5625), provide the aspectRatio option.

    <div id="container" style="width: 50%; height: 300px;"></div>
    <script>
        var map = new Datamap({
            element: document.getElementById('container'),
            responsive: true
        });
    
        window.addEventListener('resize', function() {
            map.resize();
        });
    </script>
  3. Install and Setup Datamaps

    master

    Datamaps provides interactive, SVG-based geographical data visualizations. It requires D3.js and Topojson to function. You can include it via CDN, NPM, or Bower.

    Prerequisites

    1. Include d3.js on your page.
    2. Include topojson.min.js on your page.
    3. Include the Datamaps script (e.g., datamaps.world.min.js).
    4. Add a container element with position: relative and defined width and height.

    Installation via NPM

    npm install datamaps

    Then reference the file in your dist directory.

    <script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js"></script>
    <script src="/datamaps.world.min.js"></script>
    <div id="container" style="position: relative; width: 500px; height: 300px;"></div>
    <script>
        var map = new Datamap({
            element: document.getElementById('container')
        });
    </script>
  4. Create a Choropleth Map

    master

    A choropleth map color-codes different states or countries based on data. You can use 2-letter state codes (e.g., NY) or 3-letter country codes (e.g., SCT).

    Colors are applied in this priority order: fillKey (from the data object), then fill (a literal color string), and finally defaultFill.

    To draw a legend, call map.legend() after initialization.

    <script>
        var map = new Datamap({
            element: document.getElementById('container'),
            fills: {
                HIGH: '#afafaf',
                LOW: '#123456',
                MEDIUM: 'blue',
                UNKNOWN: 'rgb(0,0,0)',
                defaultFill: 'green'
            },
            data: {
                IRL: {
                    fillKey: 'LOW',
                    numberOfThings: 2002
                },
                USA: {
                    fillKey: 'MEDIUM',
                    numberOfThings: 10381
                }
            }
        });
    
        // Draw a legend for this map
        map.legend();
    </script>
  5. Add Labels to USA Maps

    master

    For USA-specific maps, you can add 2-letter state labels using map.labels().

    Options include:

    • labelColor: Font color (default: #000)
    • lineWidth: Line width for New England states (default: 1)
    • fontSize: Font size (default: 10)
    • fontFamily: Font family (default: 'Verdana')
    • customLabelText: An object where keys are uppercase 2-letter state codes and values are the replacement text.
  6. Render Bubbles on a Map

    master

    The bubbles plugin renders circles on specific coordinates. Each bubble object in the array must contain at least:

    • latitude
    • longitude
    • radius

    Optional properties include fillKey for color coding and any custom data to be used in the popupTemplate.

    var bombs = [{
        name: 'Joe 4',
        radius: 25,
        yield: 400,
        country: 'USSR',
        fillKey: 'RUS',
        significance: 'First fusion weapon test by the USSR',
        date: '1953-08-12',
        latitude: 50.07,
        longitude: 78.43
    }];
    
    // Draw bubbles
    bombMap.bubbles(bombs, {
        popupTemplate: function (geo, data) {
                return ['<div class="hoverinfo">' +  data.name,
                '<br/>Payload: ' +  data.yield + ' kilotons',
                '<br/>Country: ' +  data.country + '',
                '<br/>Date: ' +  data.date + '',
                '</div>'].join('');
        }
    });
    
    // To erase all bubbles:
    // map.bubbles([]);
  7. Update a Choropleth Map

    master

    You can update the colors of a map after it has been drawn using updateChoropleth. You can pass a literal color string or an object with a fillKey.

    To reset the entire map to the defaultFill, pass null as the first argument and {reset: true} as the second.

  8. Reference: Datamaps Default Options

    master

    The following configuration options are available when initializing new Datamap(options):

    {
      scope: 'world', // 'usa' or 'world'; custom maps can specify their own
      setProjection: setProjection, // Returns a d3 path and projection functions
      projection: 'equirectangular', // e.g., "mercator"
      height: null, // Grabs height of 'element' if null
      width: null, // Grabs width of 'element' if null
      responsive: false, // If true, call resize() on resize events
      done: function() {}, // Callback when map is done drawing
      fills: {
        defaultFill: '#ABDDA4' // Maps keys to the "fillKey" of [data] or [bubbles]
      },
      dataType: 'json', // 'json' or 'csv' (CSV requires an 'id' column)
      dataUrl: null, // URL to fetch map data
      geographyConfig: {
          dataUrl: null, // URL to fetch TopoJSON
          hideAntarctica: true,
          hideHawaiiAndAlaska : false,
          borderWidth: 1,
          borderOpacity: 1,
          borderColor: '#FDFDFD',
          popupTemplate: function(geography, data) { return '...'; },
          popupOnHover: true,
          highlightOnHover: true,
          highlightFillColor: '#FC8D59',
          highlightBorderColor: 'rgba(250, 15, 160, 0.2)',
          highlightBorderWidth: 2,
          highlightBorderOpacity: 1
      },
      bubblesConfig: {
          borderWidth: 2,
          borderOpacity: 1,
          borderColor: '#FFFFFF',
          popupOnHover: true,
          radius: null,
          popupTemplate: function(geography, data) { return '...'; },
          fillOpacity: 0.75,
          animate: true,
          highlightOnHover: true,
          highlightFillColor: '#FC8D59',
          highlightBorderColor: 'rgba(250, 15, 160, 0.2)',
          highlightBorderWidth: 2,
          highlightBorderOpacity: 1,
          highlightFillOpacity: 0.85,
          exitDelay: 100,
          key: JSON.stringify
      },
      arcConfig: {
        strokeColor: '#DD1C77',
        strokeWidth: 1,
        arcSharpness: 1,
        animationSpeed: 600,
        popupOnHover: false,
        popupTemplate: function(geography, data) { return '...'; }
      }
    }
  9. Import the D3 module

    master
    The src/js/components/d3/index.js file serves as an entrypoint that exports the d3 object. It ensures that document, window, and d3 are available in the global scope by requiring necessary global and D3 configurations. You can require this module to gain access to the D3 library within the project context.
  10. Reference TopoJSON utility methods

    master

    The following utility methods are attached to the topojson object:

    • topojson.topology: Core topology functionality.
    • topojson.simplify: Simplifies the geometry of the topology.
    • topojson.clockwise: Ensures polygons follow a clockwise orientation.
    • topojson.filter: Filters topological elements.
    • topojson.prune: Prunes unnecessary elements from the topology.
    • topojson.bind: Binds data to the topology.
    topojson.topology = require("./lib/topojson/topology");
    topojson.simplify = require("./lib/topojson/simplify");
    topojson.clockwise = require("./lib/topojson/clockwise");
    topojson.filter = require("./lib/topojson/filter");
    topojson.prune = require("./lib/topojson/prune");
    topojson.bind = require("./lib/topojson/bind");