JSFiddle - React, Tailwind, and code Playground
by PantelisChin
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>US Choropleth Map</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.css" rel="stylesheet">
<style>
body { margin: 0; padding: 0; }
#zoom-button {position: absolute; top: 0; width: 120px; height: 60px}
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script src="script.js"></script>
<button id="zoom-button">Reproduce issue</button>
</body>
</html>
JavaScript
mapboxgl.accessToken = 'yout mapbox access token';
const generateRandomData = () => {
const features = [];
const bbox = [-125.0, 24.396308, -66.934570, 49.384358]; // US boundary coordinates
for (let i = 0; i < 10000; i++) {
const lng = Math.random() * (bbox[2] - bbox[0]) + bbox[0];
const lat = Math.random() * (bbox[3] - bbox[1]) + bbox[1];
const value = Math.floor(Math.random() * 1001); // Random value between 0 and 1000
const feature = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [lng, lat],
},
properties: {
value: value,
},
};
features.push(feature);
}
return {
type: 'FeatureCollection',
features: features,
};
};
// Initialize the map
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/satellite-streets-v12',
center: [-103.6702, 26.5991], // Center the map on the US
zoom: 4.998938247287756, // Adjust the zoom level
});
function changeMapView() {
const randomZoom = Math.floor(Math.random() * (6 - 4 + 1)) + 4; // Random zoom between 4 and 6
// Generate random coordinates within the bounding box of the GeoJSON source
const randomLng = Math.random() * ([-125, -66][1] - [-125, -66][0]) + [-125, -66][0];
const randomLat = Math.random() * ([25, 49][1] - [25, 49][0]) + [25, 49][0];
map.flyTo({
center: [randomLng, randomLat],
zoom: randomZoom,
duration: 0.1,
essential: true,
});
}
document.getElementById('zoom-button').addEventListener('click', () => {
for (var i = 0; i < 100; i++) {
setTimeout(changeMapView, i * 10); // Call the function every 10ms
}
});
map.on('load', function() {
map.addSource('terrain-data', {
type: 'raster-dem',
url: 'mapbox://mapbox.mapbox-terrain-dem-v1',
tileSize: 512,
maxzoom: 20,
});
map.setTerrain({
source: 'terrain-data',
exaggeration: 1
});
// Load the custom GeoJSON data
map.addSource('custom-data', {
...