MapChart with an auto-populated legend

This demo shows how we can populate a custom legend on a Map chart from its Polygon series data.

Code

Contrary to other chart types, Legend cannot readily use data items from a Map series.

The main reason being that most map series use geodata, which is parsed asynchronously, so the data items might not yet be available immediately.

To address that, we use datavalidated event on the series.

Another issue to address is the naming and coloring of the map polygons. The legend can't access that information because it is stored in a non-standard way in map series.

The following code addresses that issue by iterating through series' data items, then adding each of them directly to legend's data.

let legend = root.container.children.push(am5.Legend.new(root, {
  nameField: "name",
  fillField: "color",
  strokeField: "color",
  layout: root.verticalLayout,
  x: am5.p100,
  centerX: am5.p100,
  y: am5.p50,
  centerY: am5.p50,
  marginLeft: 30
})); 

series.events.on("datavalidated", function() {
  am5.array.each(series.dataItems, function(item) {
    legend.data.push({
      name: item.dataContext.name,
      color: item.get("mapPolygon").get("fill")
    });
  });
});
var legend = root.container.children.push(am5.Legend.new(root, {
  nameField: "name",
  fillField: "color",
  strokeField: "color",
  layout: root.verticalLayout,
  x: am5.p100,
  centerX: am5.p100,
  y: am5.p50,
  centerY: am5.p50,
  marginLeft: 30
})); 

series.events.on("datavalidated", function() {
  am5.array.each(series.dataItems, function(item) {
    legend.data.push({
      name: item.dataContext.name,
      color: item.get("mapPolygon").get("fill")
    });
  });
});

Example

See the Pen
MapChart with a legend
by amCharts team (@amcharts)
on CodePen.0

Posted in Uncategorized