I am trying to implement a div
tooltip on mouseover for counties in a TopoJSON map of the United States, using D3 on a page built in Angular.
I have tried every combination of the x/y coordinates available in the D3 mouseover event, as well as some combinations suggested online (D3.pointer
, Element.getBoundingClientRect
, etc.), but no matter what I do the tooltip seems to fall at incorrect coordinates, offset from my mouse and not necessarily by the same degree at each location on the svg
.
Is there a proper way to do this? Examples of code are below. The relevant portion is within this.counties.on("mouseover", ...)
.
HTML
<div class="row g-0">
<div class="container" id="mapContainer">
<svg id="map"></svg>
<div id="tooltip">TESTING</div>
</div>
</div>
CSS
#mapContainer {
position: relative;
}
#tooltip {
position: absolute;
}
TypeScript
this.svg = d3.select("#map")
.attr("preserveAspectRatio", "xMidYMid meet")
.attr("viewBox", "0 0 960 600")
.attr("height", "100%")
.attr("width", "100%")
this.g = this.svg.append("g")
.attr("id", "g")
this.zoom = d3.zoom()
.scaleExtent([1, 8])
.translateExtent([[0, 0], [960, 600]])
.on("zoom", (event, d) => {
let {transform} = event
this.g.attr("transform", transform)
this.g.attr("stroke-width", 1 / transform.k)
})
this.counties = this.g.append("g")
.attr("class", "county")
.attr("fill", "#DFDFDF")
.attr("stroke", "#FFFFFF")
.attr("stroke-linejoin", "round")
.attr("stroke-width", "0.25")
.selectAll('path')
.data(topojson.feature(this.topography, this.topography["objects"]["counties"])["features"])
.join("path")
.attr("id", function(d) {return d["id"]})
.attr('d', this.path)
.attr("fill", "#DFDFDF")
.on("mousemove", (event, d) => {
d3.select("#tooltip")
.style("left", `${d3.pointer(event)[0]}px`)
.style("top", `${d3.pointer(event)[1]}px`)
})
// PER DERISTNOCHDA'S SUGGESTION
.on("mousemove", (event, d) => {
d3.select("#tooltip")
.style("left", `${event.pageY}px`)
.style("top", `${event.pageX}px`)
})
A few screenshots of results, e.g., when the cursor is in Maine in the top-right:
And when the cursor is in Arizona in the bottom-left:
Copyright Notice:Content Author:「OJT」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/71232139/angular-d3-topojson-mouseover-tooltip-coordinates-wrong