In most map setups, a polygon (country) will change color and show a tooltip with its name when hovered. This tutorial will show how you can "simulate" hover via API, without user actually interacting with the map.
Base map
Here's what we are going to start with. The map below has already set up states to change color on hover, as well as tooltipText
to display a tooltip.
See the Pen amCharts 4: triggering map polygon tooltip via API by amCharts team (@amcharts) on CodePen.0
Triggering hover
Basically, triggering hover is as easy as setting isHover = true
on a target element.
That said, there are a few things we can do for it to work correctly, though.
Tweaking tooltip position
Normally, a tooltip would show up at whatever position your mouse cursor is, or location of tap on a touch screen.
However, in case of a trigger via API, there's no such position, so we want the tooltip to pop up in the middle of the target polygon.
For that we need to set polygon template's tooltipPosition
to "fixed"
.
We also want it appearing in a "visual center" of the polygon, not geometrical one, so we'll need to enable visual center calculation for our Polygon series by setting its calculateVisualCenter
to true
.
polygonSeries.calculateVisualCenter = true; polygonSeries.mapPolygons.template.tooltipPosition = "fixed";
polygonSeries.calculateVisualCenter = true; polygonSeries.mapPolygons.template.tooltipPosition = "fixed";
{ // ... "series": [{ "type": "MapPolygonSeries", // ... "calculateVisualCenter": true, "mapPolygons": { // ... "tooltipPosition": "fixed" } }] }
Finding polygon object
Now, in order to simulate hover (by setting isHover
property) we need an actual MapPolygon
object.
We can find it using Serie's getPolygonById(id)
method.
Let's find and "hover" France:
let france = polygonSeries.getPolygonById("FR"); france.isHover = true;
var france = polygonSeries.getPolygonById("FR"); france.isHover = true;
Unhovering polygon
Similarly, if we'd like to "unhover" a polygon via API, we'd set its isHover = false
.
It will not only remove any "hover" state properties, but will also hide tooltip.
Complete example
See the Pen amCharts 4: triggering map polygon tooltip via API by amCharts team (@amcharts) on CodePen.0