Mapbox GL JS + React: Data overlay
See https://github.com/mapbox/mapbox-react-examples/
by Tristen Brown
HTML
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v0.39.1/mapbox-gl.css">
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-assembly/mbx/v0.18.0/assembly.min.css">
<script src="https://api.mapbox.com/mapbox-assembly/mbx/v0.18.0/assembly.js"></script>
<script src="https://api.mapbox.com/mapbox-gl-js/v0.39.1/mapbox-gl.js"></script>
<div id="app"></div>
Babel + JSX
/* See https://github.com/mapbox/mapbox-react-examples/ for full example */
mapboxgl.accessToken = 'pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4M29iazA2Z2gycXA4N2pmbDZmangifQ.-g_vE53SD2WrJ6tFX7QHmA';
const options = [{
name: 'Population',
description: 'Estimated total population',
property: 'pop_est',
stops: [
[0, '#f8d5cc'],
[1000000, '#f4bfb6'],
[5000000, '#f1a8a5'],
[10000000, '#ee8f9a'],
[50000000, '#ec739b'],
[100000000, '#dd5ca8'],
[250000000, '#c44cc0'],
[500000000, '#9f43d7'],
[1000000000, '#6e40e6']
]
}, {
name: 'GDP',
description: 'Estimate total GDP in millions of dollars',
property: 'gdp_md_est',
stops: [
[0, '#f8d5cc'],
[1000, '#f4bfb6'],
[5000, '#f1a8a5'],
[10000, '#ee8f9a'],
[50000, '#ec739b'],
[100000, '#dd5ca8'],
[250000, '#c44cc0'],
[5000000, '#9f43d7'],
[10000000, '#6e40e6']
]
}]
class Application extends React.Component {
constructor(props) {
super(props);
this.state = {
active: options[0]
};
}
componentDidUpdate() {
this.setFill();
}
componentDidMount() {
this.map = new mapboxgl.Map({
container: this.mapContainer,
style: 'mapbox://styles/mapbox/streets-v9',
center: [5, 34],
zoom: 1.5
});
this.map.on('load', () => {
this.map.addSource('countries', {
type: 'geojson',
data: 'https://cdn.rawgit.com/mapbox/mapbox-react-examples/master/data-overlay/src/data.json'
});
this.map.addLayer({
id: 'countries',
type: 'fill',
source: 'countries'
}, 'country-label-lg'); // ID metches `mapbox/streets-v9`
this.setFill();
});
}
setFill() {
const { property, stops } = this.state.active;
this.map.setPaintProperty('countries', 'fill-color', {
property,
stops
});
}
render() {
const { name, description, stops, property } = this.state.active;
const renderLegendKeys = (stop, i) => {
...