JSFiddle - React, Tailwind, and code Playground
by Sahil Kashyap
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Display a map</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.48.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.48.0/mapbox-gl.css' rel='stylesheet' />
<script src='https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js'></script>
</head>
<body>
<div id='map'></div>
</body>
</html>
CSS
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
JavaScript
mapboxgl.accessToken = 'pk.eyJ1Ijoic2FoaWxrYXNoeWFwNjQiLCJhIjoiY2tkNDFxYmtoMXQxbjJybXlleGxhejE4MSJ9.LGSnbgHFFcuBE8wXHxIMiA';
const map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/light-v9', // stylesheet location
center: [-97, 39],
interactive: false,
zoom: 3
});
let newdata = new Map();
const getJSON = (url, callback) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = () => {
const status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
map.on('load', () => {
getJSON('https://raw.githubusercontent.com/lobenichou/dataForGuides/master/usPresResults.json', (err, data) => {
if (err !== null) {
console.log('error fetching file')
} else {
data.forEach((row) => {
if (!row['combined_fips']) {
return;
}
// get winner
const winner = row['votes_dem'] > row['votes_gop'] ? 'dem' : 'gop';
const id = row['combined_fips'];
newdata[id] = {
winner: winner,
diff: row['per_point_diff'] * 100
}
})
}
initLayers();
})
const initLayers = () => {
const blueScale = d3.scaleLinear()
.domain([0, 100])
.range(['#bad2f0', '#1868d1']);
const redScale = d3.scaleLinear()
.domain([0, 100])
.range(['#f2cbcb', '#be2d1e']);
map.addSource('counties', {
'type': 'vector',
'url': 'mapbox://lobenichou.cil176kr'
});
map.addLayer({
'id': 'counties-join',
'type': 'fill',
'source': 'counties',
'source-layer': 'uscountiesnew',
'paint': {
'fill-color': ['feature-state', 'color']
}
}, 'waterway-label');
const setCountiesColor = () => {
for (let key in newdata) {
map.setFeatureState({
source: 'counties',
...