Search code examples
javascriptamchartsamcharts4

Retrieve information on clicked city in amCharts 4


I am trying to implement a kind of like animation along lines in amCharts 4. I'm struggling to get the clicked city (am4core.Circle), it displays the tooltip information on hover, however, I am not able to get the data when the element is clicked.

Here's how I add the cities to my map:

//SetImageSeries()
let imageSeries = mapChart.series.push(new am4maps.MapImageSeries());
imageSeries.mapImages.template.propertyFields.longitude = `longitude`;
imageSeries.mapImages.template.propertyFields.latitude = `latitude`;
imageSeries.mapImages.template.propertyFields.url = `url`;

//AddCities
let cities = mapChart.series.push(new am4maps.MapImageSeries());
cities.mapImages.template.nonScaling = true;
cities.tooltip.background.strokeWidth = 0;
cities.cursorOverStyle = am4core.MouseCursorStyle.pointer;

let city = cities.mapImages.template.createChild(am4core.Circle);
city.radius = 10;
city.fill = am4core.color(`#d4a259`);

const addCity = (coords, title) => {
  let city = cities.mapImages.create();
  city.latitude = coords.latitude;
  city.longitude = coords.longitude;
  city.tooltipText = title;
  city.name = title;

  return city;
};

let genova = addCity({ 'latitude': 44.4056, 'longitude': 8.9463 }, `Genova`);
let amman = addCity({ 'latitude': 31.9539, 'longitude': 35.9106 }, `Amman`);
let sydney = addCity({ 'latitude': -33.8688, 'longitude': 151.2093 }, `Sydney`);
let london = addCity({ 'latitude': 51.5074, 'longitude': -.1278 }, `London`);
let barcelona = addCity({ 'latitude': 41.3851, 'longitude': 2.1734 }, `Barcelona`);

And here what I'm trying to get:

cities.events.on(`hit`, element => {
  console.log(element.target.dataItem);
  console.log(element.target.dataItem.dataContext);
});

element.target.dataItem.dataContext is undefined, however, the tooltip (or any other custom data) should be somewhere there.

Maybe I'm not putting the listener on the correct object...

The issue's similar to this one but their solution provided doesn't work in my case, and I guess is because of my way of loading data. I am open to change it if needed.


Solution

  • According to AmCharts 4 (Circle) every circle element has its own click (hit) event so, they gave me the clue by:

    chart.seriesContainer.events.on("hit", function(ev) {
      console.log(ev.target.baseSprite);
    });
    

    So, you can add any custom value using city.customValue=value and retrieved using:

    cities.events.on(`hit`, element => {
      console.log(element.target.customValue);
    });
    

    Listening on the event in the variable city itself also works:

    aman.events.on(`hit`, element => {
      console.log(element.target.customValue);
    });