Skip to content

Instantly share code, notes, and snippets.

@danvk
Created April 4, 2018 16:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danvk/e9e6478873ece54c7fc3cd896e4c992d to your computer and use it in GitHub Desktop.
Save danvk/e9e6478873ece54c7fc3cd896e4c992d to your computer and use it in GitHub Desktop.
Demonstration of polygon outlines in Mapbox GL JS
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Update a choropleth layer by zoom level</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.js'></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
#update { position: absolute; top: 20px; left: 20px; z-index: 1; font-size: 2em; }
</style>
</head>
<body>
<div id='map'></div>
<script src="index.js"></script>
</body>
</html>
mapboxgl.accessToken = 'pk.eyJ1IjoiZGFudmsiLCJhIjoiY2lrZzJvNDR0MDBhNXR4a2xqNnlsbWx3ciJ9.myJhweYd_hrXClbKk8XLgQ';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v9',
center: [-73.9781213544922, 40.72382748514871],
zoom: 11
});
let geojson;
const featureCollectionP = fetch("nyc-blockgroups.land.topojson")
.then(response => response.json())
.then(nyc => {
geojson = topojson.feature(nyc, nyc.objects['nyc-blockgroups.land']);
setValues(geojson);
console.log('GeoJSON is ', JSON.stringify(geojson).length, ' bytes');
});
const mapP = new Promise((resolve, reject) => {
map.on('load', resolve);
});
function setValues(geojson) {
for (const feature of geojson.features) {
feature.properties.value = Number(feature.properties['INTPTLAT']);
}
}
Promise.all([mapP, featureCollectionP]).then(() => {
map.addSource('blocks', {
type: 'geojson',
data: geojson,
});
map.addLayer({
'id': 'blocks',
'type': 'fill',
'source': 'blocks',
'layout': {
},
'paint': {
'fill-color': [
'interpolate',
['linear'],
['get', 'value'],
40.5, 'rgba(255, 0, 0, 0.6)', // blue-green
41, 'rgba(0, 255, 0, 0.6)', // yellow
],
'fill-outline-color': 'rgba(0,0,0,0)'
}
});
});
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment