Created
March 23, 2017 11:53
-
-
Save chriswhong/6cc91ecee59f4aa9448065537e9ae286 to your computer and use it in GitHub Desktop.
Choropleth for mapboxGL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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