Files
mapbox_gl_d3_playground/03-map-data-interactions.html
2025-08-25 08:56:15 -06:00

116 lines
3.2 KiB
HTML

<!DOCTYPE html >
<html>
<head>
<meta charset="utf-8" />
<title>mapboxgl.js + d3.js tutorial - 03</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<link href="https://api.mapbox.com/mapbox-gl-js/v3.0.1/mapbox-gl.css" rel="stylesheet" />
<script src="https://api.mapbox.com/mapbox-gl-js/v3.0.1/mapbox-gl.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style media="screen">
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
svg {
position: absolute;
width: 100%;
height: 100%;
}
circle {
fill: #e55e5e;
stroke: #e55e5e;
stroke-width: 0;
cursor: pointer;
transition: 0.5s fill, 0.5s stroke-width;
}
circle:hover {
fill: #5e5ee5;
stroke-width: 18;
}
</style>
</head>
<body>
<div id="map">
</div>
<script>
//////////////////
// Mapbox stuff
//////////////////
// Set-up map
mapboxgl.accessToken = 'pk.eyJ1Ijoiam9yZGl0b3N0IiwiYSI6ImQtcVkyclEifQ.vwKrOGZoZSj3N-9MB6FF_A';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/outdoors-v9',
zoom: 11.5,
center: [13.4426, 52.5100],
});
//////////////////////////
// Mapbox+D3 Connection
//////////////////////////
// Get Mapbox map canvas container
var canvas = map.getCanvasContainer();
// Overlay d3 on the map
var svg = d3.select(canvas).append("svg");
// Load map and dataset
map.on('load', function () {
d3.json("data/berlin-parks.json", function(err, data) {
drawData(data);
});
});
// Project GeoJSON coordinate to the map's current state
function project(d) {
return map.project(new mapboxgl.LngLat(+d[0], +d[1]));
}
//////////////
// D3 stuff
//////////////
// Draw GeoJSON data with d3
var circles;
function drawData(data) {
console.log("draw data");
// Add circles
circles = svg.selectAll("circle")
.data(data.features)
.enter()
.append("circle")
.attr("r", 16)
.on("click", function(d) {
alert(d.properties.name);
});
// Call the update function
update();
// Update on map interaction
map.on("viewreset", update);
map.on("move", update);
map.on("moveend", update);
}
// Update d3 shapes' positions to the map's current state
function update() {
console.log("update");
circles.attr("cx", function(d) { return project(d.geometry.coordinates).x })
.attr("cy", function(d) { return project(d.geometry.coordinates).y });
}
</script>
</body>
</html>