Skip to content

Pre-zooming Map to a Country

You can pre-zoom the map to certain coordinates and level. If you don’t want to do that, you can make the chart pre-zoom to a particular country. This tutorial will explain how.

The Map chart has a dedicated method for zooming to a polygon (country) of our choice: zoomToMapObject(object).

The name leaves little to the imagination about what it does: when invoked it will zoom the map to that particular object, in our cause it’s Map polygon.

It accepts an object reference as a parameter.

Let’s say all we have is a country ISO ID. The ID for India is "IN".

Since we need to pass in a full fledged map object, not just an ID, we’ll need to find it among Map series’ mapPolygons. MapPolygonSeries has a method for that: getPolygonById(id).

Finally, we want the map to be fully loaded when we start zooming it, so we will use its "ready" event.

chart.events.on("ready", function(ev) {
chart.zoomToMapObject(polygonSeries.getPolygonById("IN"));
});
Open in CodePen

Let’s go a bit further, and highlight the country we have zoomed in to.

To do that, we will need to create an "active" state, as well as trigger it on the pre-zoomed country.

// Create active state
let as = polygonTemplate.states.create("active");
as.properties.fill = am4core.color("#7B3625");
// ...
chart.events.on("ready", function(ev) {
let india = polygonSeries.getPolygonById("IN");
// Pre-zoom
chart.zoomToMapObject(india);
// Set active state
setTimeout(function() {
india.isActive = true;
}, 1000);
});
Open in CodePen

Countries with parts over longitude threshold

Section titled “Countries with parts over longitude threshold”

Boundaries for some countries cross the -180/180 longitude threshold and therefore will be zoomed seemingly incorrectly.

The solution is using custom zoom settings as described in “Using custom map zoom settings for individual countries”.