Search code examples
javascriptamcharts4

Why tooltipPosition = "fixed" don't work (amCharts v4)


Why tooltipPosition = "fixed" don't work for my map? I read the documentation and did as it says. (https://www.amcharts.com/docs/v4/reference/tooltip/)

function addSeries(country, tooltipHTML) {
    let newSeries = chart.series.push(new am4maps.MapPolygonSeries());
    newSeries.useGeodata = true;
    newSeries.include = country;
    newSeries.mapPolygons.template.fill = am4core.color("#4D7EAA");
    newSeries.fill = am4core.color("#4D7EAA");
    newSeries.mapPolygons.template.tooltipText = tooltipHTML;
    newSeries.mapPolygons.template.tooltipHTML = tooltipHTML;
    newSeries.tooltip.getFillFromObject = false;
    newSeries.tooltip.background.fill = am4core.color("#000");
    newSeries.tooltip.tooltipPosition = "fixed";
    newSeries.tooltip.x = 10;
    newSeries.tooltip.trackable = false;
    newSeries.tooltip.y = 30;
    newSeries.mapPolygons.template.events.on("over", over);
    newSeries.mapPolygons.template.events.on("out", out);
    newSeries.cursorOverStyle = am4core.MouseCursorStyle.pointer;
    let hs = newSeries.mapPolygons.template.states.create("hover");
    hs.properties.fill = am4core.color("#004685");
}

Full code: https://codepen.io/nefayran/pen/BEmQvE


Solution

  • This is a good question.

    Please note the documentation also says:

    Inherited from Sprite

    I.e. the property is not actually that of the Tooltip instance itself, rather it is a property & behavior a tooltip acquires from the object triggering it (not entirely unlike tooltipText).

    Generally, there is 1 tooltip on a series that is shared between its objects, so even though in this case each mapPolygon triggers the tooltip, it's not a tooltip per polygon rather one shared on a series (almost like a singleton). This way, as you hover from mapPolygon to mapPolygon, the tooltip remains continuously visible and just changes properties accordingly.

    So, in this case, instead of setting the property on the tooltip itself, just set it on the template for mapPolygons:

    // newSeries.tooltip.tooltipPosition = "fixed";
    newSeries.mapPolygons.template.tooltip.tooltipPosition = "fixed";
    

    Here's a fork:

    https://codepen.io/team/amcharts/pen/29890969c7222b7ddba5c9fbeefa80b5

    Addendum (2019-04-17)

    Problem: Hovering over the city (mapImage/its children) or line (mapLine or variant) kills the hover effect of the mapPolygon and the line/animation it triggers.

    Solution: If the cities/lines don't have any user interaction features like a tooltip, my suggestion is to disable interactions altogether so hovering over them goes straight to the mapPolygon underneath, i.e.

    cities.mapImages.template.interactionsEnabled = false;
    lineSeries.mapLines.template.interactionsEnabled = false;
    

    The demo above has been updated to include those lines.