Resetting Map Position/Zoom
All Map Charts, unless disabled, can be panned and zoomed. This tutorial will explain how to reset map’s position and zoom to its original state via custom button or API.
Resetting via API
Section titled “Resetting via API”Easy way
Section titled “Easy way”Map chart provides a dedicated goHome(duration) method.
I wish it had a youredrunk parameter, but it only accepts a duration in milliseconds of how long should the zooming/panning animation play.
chart.goHome();chart.goHome();That’s all there is to the easy method.
Custom way
Section titled “Custom way”If you’d like more customization options for the reset, like adjusting zoom level but centering the map, you can use MapChart’s zoomToRectangle(north, east, south, west, zoomLevel, center, duration) method.
The parameters are as follows:
| Parameter | Type | Comment |
|---|---|---|
north |
number |
Latitude of the zoom rectangle’s top edge. |
east |
number |
Longitude of the zoom rectangle’s right edge. |
south |
number |
Latitude of the zoom rectangle’s bottom edge. |
west |
number |
Longitude of the zoom rectangle’s left edge. |
zoomLevel (optional) |
number |
Zoom level. (1 for completely zoomed out) |
center (optional) |
boolean |
Center the map while zooming. |
duration (optional) |
number |
Number of milliseconds to play zoom animation. |
While we may not know what latitude/longitude of the extreme edges of our map are, our Map Chart does. We can access them through its north, east, south, and west properties.
So, to reset our map to show all of the map, we can do something like this:
chart.zoomToRectangle( chart.north, chart.east, chart.south, chart.west, 1, true);chart.zoomToRectangle( chart.north, chart.east, chart.south, chart.west, 1, true);Adding a button
Section titled “Adding a button”Now, let’s add a button that does that for us:
let home = chart.chartContainer.createChild(am4core.Button);home.label.text = "Home";home.align = "right";home.events.on("hit", function(ev) { chart.goHome();});var home = chart.chartContainer.createChild(am4core.Button);home.label.text = "Home";home.align = "right";home.events.on("hit", function(ev) { chart.goHome();});{ // ... "chartContainer": { "children": [{ "type": "Button", "label": { "text": "Home" }, "events": { "hit": function(ev) { chart.goHome(); } } }] }}Complete example
Section titled “Complete example”Further reading
Section titled “Further reading”If you ended up here, you might be interested in the following as well: