function createZoomAbleMap(chosenWidth=900, chosenHeight=500, minZoom=0.5, maxZoom=100, projection=d3.geoMercator(), data=countries, fillColor="red", strokeColor="white", fillColorNone="#444", names = false, textColor = "grey", fontSize = 1, markersData=completedMap, radius=1, markersFillColor="orange") {
const width = chosenWidth;
const height = chosenHeight;
const zoom = d3.zoom()
.scaleExtent([minZoom, maxZoom])
.on("zoom", zoomed);
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.attr("width", width)
.attr("height", height)
.attr("style", "max-width: 100%; height: 100%;")
.on("click", reset);
const path = d3.geoPath(projection);
const g = svg.append("g");
const states = g.append("g")
.attr("fill", fillColorNone)
.attr("cursor", "pointer")
.selectAll("path")
.data(data.features)
.join("path")
.attr("d", path)
.on("click", clicked);
let textLabels = "";
if (names) {
textLabels = g.append("g")
.attr("pointer-events", "none")
.selectAll("text")
.data(data.features)
.join("text")
.attr("text-anchor", "middle")
.style("font-size", "12px")
.text(d => d.properties.name);
} else {
states.append("title").text(d => d.properties.name);
}
const markers = g.append("g")
.attr("fill-opacity", 0.3)
.selectAll("circle")
.attr("cursor", "pointer")
.data(markersData)
.join("circle")
.attr("cx", d => projection([d.Longitude, d.Latitude])[0])
.attr("cy", d => projection([d.Longitude, d.Latitude])[1])
.attr("r", radius)
.attr("fill", markersFillColor)
.append("title")
.text(d => createTooltip(d));
g.append("path")
.attr("fill", "none")
.attr("stroke", strokeColor)
.attr("stroke-linejoin", "round")
.attr("d", path(countrymesh.features));
svg.call(zoom);
function reset() {
states.transition().style("fill", null);
svg.transition().duration(750).call(
zoom.transform,
d3.zoomIdentity,
d3.zoomTransform(svg.node()).invert([width, height])
);
}
function clicked(event, d) {
const [[x0, y0], [x1, y1]] = path.bounds(d);
event.stopPropagation();
states.transition().style("fill", null);
d3.select(this).transition().style("fill", fillColor);
svg.transition().duration(750).call(
zoom.transform,
d3.zoomIdentity
.translate(width / 2, height / 2)
.scale(Math.min(100, 0.9 / Math.max((x1 - x0) / width, (y1 - y0) / height)))
.translate(-(x0 + x1) / 2, -(y0 + y1) / 2),
d3.pointer(event, svg.node()),
);
console.log(d.properties.name);
}
function zoomed(event) {
const {transform} = event;
g.attr("transform", transform);
g.attr("stroke-width", 1 / transform.k);
if (names) {
textLabels.attr("transform", d => `translate(${path.centroid(d)}) scale(${Math.min(transform.k / 10, 5)})`);
textLabels.style("font-size", fontSize); // Adjust font size based on zoom scale
textLabels.attr("fill", textColor);
}
// Update marker positions on zoom
markers.attr("x", d => projection([d.Longitude, d.Latitude])[0])
.attr("y", d => projection([d.Longitude, d.Latitude])[1]);
}
return svg.node();
}