Skip to content

Instantly share code, notes, and snippets.

@chriswhong
Created March 23, 2017 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriswhong/6cc91ecee59f4aa9448065537e9ae286 to your computer and use it in GitHub Desktop.
Save chriswhong/6cc91ecee59f4aa9448065537e9ae286 to your computer and use it in GitHub Desktop.
Choropleth for mapboxGL
// choropleth.js
// given polygon geojson data and options, returns a GL fill style
// adaptation of Tim Wisniewskis' Leaflet Choropleth
import chroma from 'chroma-js';
const Choropleth = (geojson, opts) => {
opts = opts || {};
// Calculate limits
const values = geojson.features.map((item) => {
if (typeof opts.valueProperty === 'function') {
return opts.valueProperty(item);
}
return item.properties[opts.valueProperty];
});
const limits = chroma.limits(values, opts.mode, opts.steps - 1);
// Create color buckets
const colors = opts.colors || chroma.scale(opts.scale).colors(opts.steps);
// build stops
const stops = limits.map((limit, i) => [limits[i], colors[i]]);
return {
'fill-color': {
property: opts.valueProperty,
stops,
},
};
};
export default Choropleth;
// get a mapboxgl style to use for choropleth
const choroplethStyle = choropleth(geoJson, {
valueProperty: 'delta',
scale: ['#edf8fb', '#b2e2e2', '#66c2a4', '#2ca25f', '#006d2c'],
steps: 5,
mode: 'q',
});
// choroplethStyle is the 'fill-color' object to be added to your mapboxGL layer style
const paint = _.extend({
'fill-outline-color': 'white',
'fill-opacity': 0.75,
}, choroplethStyle);
map.addLayer({
id: 'pipeline-polygons',
source: 'pipeline-polygons',
type: 'fill',
paint,
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment