Skip to content

Animating map lines with CSS

Each line in a MapChart is an SVG object in document’s DOM tree. This means we can use CSS to target and modify it, including using CSS animations. This tutorial will show how we can make MapLine animate itself from the start.

We’re going to assume that you know what MapLine is, how to create, and configure it. If that’s not the case, check out this tutorial first.

We’re also not going to look into details on how CSS animations work. For the background and details, head over to this Mozilla article.

Now that we know our map lines and CSS animations, let’s start making it happen.

Let’s start with a simple two-leg line on a map:

let lineSeries = chart.series.push(new am4maps.MapLineSeries());
lineSeries.mapLines.template.strokeWidth = 4;
lineSeries.mapLines.template.stroke = am4core.color("#e03e96");
lineSeries.mapLines.template.nonScalingStroke = true;
let line = lineSeries.mapLines.create();
line.multiGeoLine = [[
{ "latitude": 48.856614, "longitude": 2.352222 },
{ "latitude": 40.712775, "longitude": -74.005973 },
{ "latitude": 49.282729, "longitude": -123.120738 }
]];

Since we will need to target specific line to via CSS, we need to assign an ID to it.

line.id = "myline";
line.setClassName();

We need to use setClassName() method (or in case of JSON config autoSetClassName: true) to make our line element have class with an id we just set.

Final touch: add the actual animation CSS:

.amcharts-myline path {
stroke-linejoin: round;
stroke-linecap: round;
stroke-dasharray: 500%;
stroke-dasharray: 0 /; /* fixes IE prob */
stroke-dashoffset: 0 /; /* fixes IE prob */
-webkit-animation: am-draw 40s;
animation: am-draw 40s;
}
@-webkit-keyframes am-draw {
0% {
stroke-dashoffset: 500%;
}
100% {
stroke-dashoffset: 0%;
}
}
@keyframes am-draw {
0% {
stroke-dashoffset: 500%;
}
100% {
stroke-dashoffset: 0%;
}
}
Open in CodePen