Seeking to enhance my d3 maps with tooltips, I came across a helpful code snippet at this link
However, upon implementing the same code in an Angular 2 TypeScript file, an error emerged:
Error: Cannot read property 'transition' of undefined
The issue arises from d3.event being null and not working as expected in JavaScript code. Here's a snippet of my ngAfterViewInit method:
ngAfterViewInit() {
this.tooltip = d3.select("map-tag")
.append("div")
.attr("class", "tooltip")
.style("opacity", 0);
this.svgContainer = d3.select("map-tag").append("svg")
.attr("width", this.width)
.attr("height", this.height)
.style("border", "2px solid steelblue")
.call(this.zoom);
this.usaSVG = this.svgContainer
.append("path")
.attr("d", this.geoPath(this.usaFeatureCollection))
.style({ fill: "none", stroke: "black" });
this.geoPoint1 = {
"type": "MultiPoint", "coordinates": [[-80.6665134, 35.0539943]]
};
this.div = d3.select("map-tag")
.append("div")
.attr("class", "tooltip")
.style("opacity", 0);
this.pointPath = this.svgContainer.append("path").attr("d", this.geoPath(this.geoPoint1)).style("stroke", "#FFFFFF")
.on('mouseover', function (d, i) {
this.div.transition()
.duration(200)
.style("opacity", .9);
this.div.text("sample text")
.style("left", (d3.event.x) + "px") // Error occurs here
.style("top", (d3.event.y - 28) + "px");
})
.on('mouseout', function (d, i) { d3.select(this).style({ fill: 'black' }); });
}
/* Custom Tooltip Styling */
div.tooltip {
position: absolute;
text-align: center;
width: 60px;
height: 28px;
padding: 2px;
font: 12px sans-serif;
background: white;
border: 0px;
border-radius: 8px;
pointer-events: none;
}