Zooming to map area on click

This tutorial will show how you can set up your map to automatically zoom to an area (i.e. country) when user clicks on or taps it.

As you may be already aware if you got to this point, each area on the chart is configured using MapPolygonSeries template.

This task is no different - we'll be adding an event listener to the polygon template like this:

let polygonTemplate = polygonSeries.mapPolygons.template;
// ...
polygonTemplate.events.on("hit", function(ev) {
  ev.target.series.chart.zoomToMapObject(ev.target)
});
var polygonTemplate = polygonSeries.mapPolygons.template;
// ...;
polygonTemplate.events.on("hit", function(ev) {
  ev.target.series.chart.zoomToMapObject(ev.target)
});
{
  // ...
  "series": [{
    "type": "MapPolygonSeries",
    // ...
    "mapPolygons": {
      "events": {
        "hit": function(ev) {
          ev.target.series.chart.zoomToMapObject(ev.target)
        }
      }
    }
  }]
}

Now, our custom function handler will kick in whenever user clicks/taps an area on the map.

Since we have a reference to a clicked object in ev.target, we can use chart's zoomToMapObject(obj) method to make it automatically zoom.

That's all there is to it. Let's see how this works on a live map:

See the Pen amCharts V4: Map (zooming to object) by amCharts (@amcharts) on CodePen.24419

Related content