map = {
const container = html`<div style="height:600px;">`;
yield container;
const map = L.map(container).setView([37.8, -96.9], 4);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: "© <a href=https://www.openstreetmap.org/copyright>OpenStreetMap</a> contributors"
}).addTo(map);
const svg = d3.select(map.getPanes().overlayPane).append("svg").style("position", "relative"),
g = svg.append("g").attr("class", "leaflet-zoom-hide");
function projectPoint(x, y) {
var point = map.latLngToLayerPoint(new L.LatLng(y, x));
this.stream.point(point.x, point.y);
}
const transform = d3.geoTransform({point: projectPoint}),
path = d3.geoPath().projection(transform);
var feature = g.selectAll("path")
.data(states.features)
.join("path")
.attr("d", path)
.style("fill", "#000")
.style("fill-opacity", .2)
.style("stroke", "#fff")
.style("stroke-width", "1.5px")
.style("pointer-events", "all")
.on("mouseover", function () {
const element = d3.select(this);
const datum = element.data()[0].properties.index;
element.style("fill", colorScale(datum)).style("fill-opacity", .7);
})
.on("mouseout", function () { d3.select(this).style("fill", "#000").style("fill-opacity", .2) });
// It can be difficult to compute a bounding box with arbitrary projections, but fortunately D3 provides a
// convenient mechanism for computing the projected bounding box of our features using our custom transform
// to convert the longitude and latitude to pixels:
var bounds = path.bounds(states),
topLeft = bounds[0], // [x, y]
bottomRight = bounds[1];
svg.attr("width", bottomRight[0] - topLeft[0])
.attr("height", bottomRight[1] - topLeft[1])
.style("left", topLeft[0] + "px")
.style("top", topLeft[1] + "px");
g.attr("transform", "translate(" + -topLeft[0] + "," + -topLeft[1] + ")");
// With Leaflet’s viewreset event, the SVG can be repositioned and rerendered whenever the map zooms
map.on("zoom", reset);
reset();
// Reposition the SVG to cover the features.
function reset() {
const bounds = path.bounds(states),
topLeft = bounds[0],
bottomRight = bounds[1];
svg .attr("width", bottomRight[0] - topLeft[0])
.attr("height", bottomRight[1] - topLeft[1])
.style("left", topLeft[0] + "px")
.style("top", topLeft[1] + "px");
g .attr("transform", "translate(" + -topLeft[0] + "," + -topLeft[1] + ")");
feature.attr("d", path);
}
}