datamaps
repository·master·Indexed 26 days ago
https://github.com/markmarkoh/datamapsAn 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.
What's inside datamaps
- D3.js (Data-Driven Documents) is a JavaScript library used to manipulate documents (HTML, SVG, and CSS) based on data. It leverages web standards to provide powerful visualization components and data-driven DOM manipulation without requiring a proprietary framework.
Understand TopoJSON vs GeoJSON
masterTopoJSON 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.
Configure Responsive Maps
masterTo make a map responsive, set
responsive: truein the options. You must then listen for the windowresizeevent and manually callmap.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 theaspectRatiooption.<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>Install and Setup Datamaps
masterDatamaps 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
- Include
d3.json your page. - Include
topojson.min.json your page. - Include the Datamaps script (e.g.,
datamaps.world.min.js). - Add a container element with
position: relativeand definedwidthandheight.
Installation via NPM
npm install datamapsThen reference the file in your
distdirectory.<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>- Include
Create a Choropleth Map
masterA 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 thedataobject), thenfill(a literal color string), and finallydefaultFill.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>Add Labels to USA Maps
masterFor 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.
Render Bubbles on a Map
masterThe
bubblesplugin renders circles on specific coordinates. Each bubble object in the array must contain at least:latitudelongituderadius
Optional properties include
fillKeyfor color coding and any custom data to be used in thepopupTemplate.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([]);Update a Choropleth Map
masterYou 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 afillKey.To reset the entire map to the
defaultFill, passnullas the first argument and{reset: true}as the second.Reference: Datamaps Default Options
masterThe 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 '...'; } } }Import the D3 module
masterThesrc/js/components/d3/index.jsfile serves as an entrypoint that exports thed3object. It ensures thatdocument,window, andd3are 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.Use the TopoJSON API
masterThetopojsonmodule provides tools for working with TopoJSON data, including topology management, simplification, and geometric operations. It exports the core TopoJSON functionality along with several utility methods for manipulating topological data.Reference TopoJSON utility methods
masterThe following utility methods are attached to the
topojsonobject: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");