Files
mapbox_gl_d3_playground/gemma.html
2025-08-27 02:00:32 -06:00

97 lines
2.9 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mapbox GL JS + D3 Example</title>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.css" rel="stylesheet" />
<script src="https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.js"></script>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { height: 1000px; width: 1600px; }
.map-overlay {
position: absolute;
top: 0;
left: 0;
pointer-events: none; /* Allow map interactions to pass through */
}
</style>
</head>
<body>
<div id="map"></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1Ijoiam9yZGl0b3N0IiwiYSI6ImQtcVkyclEifQ.vwKrOGZoZSj3N-9MB6FF_A'; // Replace with your Mapbox access token
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://style/mapbox/light-v9',
center: [-74.0060, 40.7128], // New York City
zoom: 10
});
map.on('load', () => {
// Sample data (replace with your actual data)
const data = [
{ longitude: -74.0060, latitude: 40.7128, value: 10, label: "A" },
{ longitude: -73.9857, latitude: 40.7484, value: 20, label: "B" },
{ longitude: -73.9960, latitude: 40.7589, value: 15, label: "C" },
{ longitude: -73.9960, latitude: 40.7389, value: 25, label: "D"}
];
const canvas = map.getCanvas();
const svg = d3.select(canvas)
.append("svg")
.attr("class", "map-overlay")
.attr("width", canvas.width)
.attr("height", canvas.height);
// Create circles for each data point
const circles = svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", (d) => map.project([d.longitude, d.latitude])[0])
.attr("cy", (d) => map.project([d.longitude, d.latitude])[1])
.attr("r", (d) => d.value / 5)
.attr("fill", "steelblue")
.attr("opacity", 0.7);
// Add labels to each circle
const labels = svg.selectAll("text")
.data(data)
.enter()
.append("text")
.attr("x", (d) => map.project([d.longitude, d.latitude])[0])
.attr("y", (d) => map.project([d.longitude, d.latitude])[1] - 10) // Adjust vertical position
.text((d) => d.label)
.attr("font-size", "12px")
.attr("font-family", "Arial")
.attr("fill", "white")
.attr("text-anchor", "middle");
// Update circle positions on map move
map.on('move', () => {
circles.each(function (d) {
const [x, y] = map.project([d.longitude, d.latitude]);
d3.select(this)
.attr("cx", x)
.attr("cy", y);
});
labels.each(function (d) {
const [x, y] = map.project([d.longitude, d.latitude]);
d3.select(this)
.attr("x", x)
.attr("y", y - 10);
});
});
});
</script>
</body>
</html>