Contents
An animated map video shows a journey. A line draws itself from city to city, a pin moves along it, and each stop’s name appears as the pin arrives. A travel company can send one with each booking, a tour operator can add one to each itinerary, and a travel creator can open a trip video with one.
This article shows how to make one for every trip in a list, with a Python script and Shotstack’s video editing API. The base map comes from public-domain map data, so you can use the videos commercially. We rendered three trips on production and checked the pin and the names at every stop.
Here is the first trip from the sample file:
TL;DR
- The whole map is one
html5clip: an SVG with the country outlines, the route, the stop names and a pin, animated by one GSAP timeline. - The base map is Natural Earth’s public-domain country outlines. The script keeps only the outlines in view, so each trip’s edit is 30 to 52 KB.
- Each leg of the route draws itself in 1.6 seconds while the pin follows its tip. The next stop’s name appears when the pin arrives.
- One
trips.jsonfile describes many trips. The script renders all of them and saves the video links inresults.json. - At all 12 stop arrivals in our renders, the pin was within 0.7 pixels of the stop, and each name appeared on the arrival frame.
How the map is built
Shotstack’s html5 asset renders a web page (HTML, CSS and JavaScript) as a video clip. Two of its rules decide how the map is built:
- The page loads nothing from the network. It runs under a Content Security Policy of
default-src 'none'. Map tiles, scripts, data files and web fonts can’t load, so everything the map needs must be inside the page. - The animation must be seekable. The renderer captures each frame by moving the animation to that exact time. So the motion must run on a timeline from one of the preloaded libraries, such as GSAP, and not on timers.
So the script builds the whole map as one SVG inside the page:
- A dark rectangle for the sea.
- One path with the outline of every country in view.
- One curved path for each leg of the route.
- A dot and a name for each stop. These start hidden.
- A yellow pin.
One GSAP timeline then draws the legs one after the other, moves the pin and shows each stop. For more on the html5 asset, see how to convert an HTML animation to MP4 and how to convert an animated SVG to MP4.
Where the base map comes from
The country outlines come from Natural Earth, a free map dataset. Its terms of use say: “All versions of Natural Earth raster + vector map data found on this website are in the public domain.” They add: “No permission is needed to use Natural Earth.”
The script uses the 1:50m country outlines, a 3.1 MB GeoJSON file. It downloads the file the first time it runs and saves it as countries.geojson for the next runs.
The whole file would make each edit several megabytes. So for each trip, the script works out the area of the map that the video shows and keeps only the outlines inside it. Here is the size of each sample trip’s edit:
| Trip | Edit JSON size |
|---|---|
| Lisbon to Rome | 52 KB |
| Japan by rail | 38 KB |
| Pacific Coast road trip | 30 KB |
The map uses the Web Mercator projection, the same as most online maps. The script fits all the stops into the frame with a margin around them. It keeps the top 200 pixels free for the title.
What you need
- Python 3 and the
requestslibrary. We ran the script with Python 3.13. Install the library withpip install requests. - A Shotstack API key. Create a free account to get one. The script calls the production API.
- The latitude and longitude of each stop.
- A public URL for the music, if you want music.
Describe your trips in trips.json
Each trip in the file becomes one video:
{
"trips": [
{
"name": "lisbon-to-rome",
"title": "Lisbon to Rome",
"subtitle": "5 cities in 12 days",
"soundtrack": "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/music/unminus/palmtrees.mp3",
"stops": [
{"name": "Lisbon", "lat": 38.72, "lon": -9.14},
{"name": "Madrid", "lat": 40.42, "lon": -3.70},
{"name": "Barcelona", "lat": 41.39, "lon": 2.17},
{"name": "Nice", "lat": 43.70, "lon": 7.27},
{"name": "Rome", "lat": 41.90, "lon": 12.50}
]
},
{
"name": "japan-rail",
"title": "Japan by rail",
"subtitle": "Tokyo to Fukuoka in 10 days",
"soundtrack": "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/music/unminus/berlin.mp3",
"stops": [
{"name": "Tokyo", "lat": 35.68, "lon": 139.69},
{"name": "Mount Fuji", "lat": 35.36, "lon": 138.73},
{"name": "Kyoto", "lat": 35.01, "lon": 135.77},
{"name": "Hiroshima", "lat": 34.39, "lon": 132.46},
{"name": "Fukuoka", "lat": 33.59, "lon": 130.40}
]
},
{
"name": "pacific-coast",
"title": "Pacific Coast road trip",
"subtitle": "San Francisco to San Diego",
"soundtrack": "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/music/freepd/motions.mp3",
"stops": [
{"name": "San Francisco", "lat": 37.77, "lon": -122.42},
{"name": "Monterey", "lat": 36.60, "lon": -121.89},
{"name": "Santa Barbara", "lat": 34.42, "lon": -119.70},
{"name": "Los Angeles", "lat": 34.05, "lon": -118.24, "label": "below"},
{"name": "San Diego", "lat": 32.72, "lon": -117.16}
]
}
]
}| Field | What it does |
|---|---|
name | The name of the trip. The script uses it in file names, in its messages and in results.json, so give each trip a different name. |
title, subtitle | The text at the top left of the video. |
soundtrack | A music URL. This is optional. |
stops | The stops in travel order. Each stop has a name, a lat and a lon in decimal degrees. |
label | Optional, on a stop. "below" puts the stop’s name under its dot instead of above it. |
Use "label": "below" when two stops are close and their names would touch. In the sample, Los Angeles uses it because its name would otherwise touch Santa Barbara’s.
The script
Save this as route_map.py, in the same folder as trips.json:
"""Render one animated route map video per trip with the Shotstack Edit API.
Usage:
python route_map.py trips.json render every trip
python route_map.py trips.json --dry-run save each trip's Edit JSON in edits/ (no API key needed)
Set SHOTSTACK_API_KEY to your production API key before you render.
Map data: Natural Earth (public domain), https://www.naturalearthdata.com
"""
import json
import math
import os
import sys
import time
from html import escape
from pathlib import Path
import requests
API = os.environ.get("SHOTSTACK_API", "https://api.shotstack.io/edit/v1")
MAP_URL = ("https://raw.githubusercontent.com/nvkelso/natural-earth-vector/v5.1.2/geojson/"
"ne_50m_admin_0_countries.geojson")
W, H = 1920, 1080
START, LEG, HOLD, END = 0.8, 1.6, 0.5, 1.5 # seconds: before the first leg, per leg, at each stop, after the last stop
def load_countries(path="countries.geojson"):
"""Download the country outlines once, then reuse the local copy."""
if not Path(path).exists():
Path(path).write_bytes(requests.get(MAP_URL, timeout=60).content)
return json.loads(Path(path).read_text(encoding="utf-8"))["features"]
def mercator(lon, lat):
return lon, math.degrees(math.log(math.tan(math.pi / 4 + math.radians(lat) / 2)))
def projector(stops, margin=0.3, top=200):
"""Fit the stops into the frame below the title, with a margin. Returns lon, lat -> x, y in pixels."""
xs, ys = zip(*(mercator(s["lon"], s["lat"]) for s in stops))
span_x, span_y = max(max(xs) - min(xs), 0.5), max(max(ys) - min(ys), 0.5)
scale = min(W / (span_x * (1 + 2 * margin)), (H - top) / (span_y * (1 + 2 * margin)))
cx, cy = (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2
def to_px(lon, lat):
x, y = mercator(lon, lat)
return round(W / 2 + (x - cx) * scale, 1), round(top + (H - top) / 2 - (y - cy) * scale, 1)
return to_px
def land_path(countries, to_px):
"""One SVG path with the outline of every country that shows in the frame."""
parts = []
for feature in countries:
geometry = feature["geometry"]
polygons = geometry["coordinates"] if geometry["type"] == "MultiPolygon" else [geometry["coordinates"]]
for ring in (ring for polygon in polygons for ring in polygon):
points = [to_px(lon, max(min(lat, 85), -85)) for lon, lat in ring]
xs, ys = [p[0] for p in points], [p[1] for p in points]
if max(xs) < 0 or min(xs) > W or max(ys) < 0 or min(ys) > H:
continue # this ring is outside the frame
parts.append("M" + "L".join(f"{x:.0f},{y:.0f}" for x, y in points) + "Z")
return "".join(parts)
def build_edit(trip, countries):
stops = trip["stops"]
to_px = projector(stops)
pts = [to_px(s["lon"], s["lat"]) for s in stops]
legs = []
for (x1, y1), (x2, y2) in zip(pts, pts[1:]):
# A gentle curve: the control point sits beside the middle of the leg.
mx, my, dx, dy = (x1 + x2) / 2, (y1 + y2) / 2, x2 - x1, y2 - y1
legs.append(f'<path class="leg" d="M{x1},{y1} Q{mx - dy * 0.15:.1f},{my + dx * 0.15:.1f} {x2},{y2}"/>')
labels = "".join( # a stop with "label": "below" gets its name under the dot, for stops close together
f'<g class="stop" id="s{i}"><circle cx="{x}" cy="{y}" r="11"/>'
f'<text x="{x}" y="{y + 54 if s.get("label") == "below" else y - 26}">{escape(s["name"])}</text></g>'
for i, (s, (x, y)) in enumerate(zip(stops, pts)))
html = (f'<svg viewBox="0 0 {W} {H}" width="{W}" height="{H}"><rect width="{W}" height="{H}" class="sea"/>'
f'<path class="land" d="{land_path(countries, to_px)}"/>{"".join(legs)}{labels}'
f'<circle id="pin" r="16" cx="{pts[0][0]}" cy="{pts[0][1]}"/></svg>'
f'<div class="title"><b>{escape(trip["title"])}</b><span>{escape(trip.get("subtitle", ""))}</span></div>')
css = ("html,body{margin:0;width:1920px;height:1080px;overflow:hidden;font-family:sans-serif}"
".sea{fill:#0E2233}.land{fill:#1D3B50;stroke:#3A6079;stroke-width:1.5}"
".leg{fill:none;stroke:#FF5A5F;stroke-width:8;stroke-linecap:round}"
"#pin{fill:#FFD166;stroke:#0E2233;stroke-width:5}"
".stop{opacity:0}.stop circle{fill:#fff;stroke:#FF5A5F;stroke-width:5}"
".stop text{font-size:38px;font-weight:700;fill:#fff;text-anchor:middle;"
"paint-order:stroke;stroke:#0E2233;stroke-width:8px}"
".title{position:absolute;left:64px;top:56px;color:#fff}"
".title b{display:block;font-size:56px}.title span{font-size:32px;color:#A9C1D3}")
# One seekable GSAP timeline: each leg draws, the pin follows its tip, and the next stop appears on arrival.
js = f"""
const tl = gsap.timeline(), pin = document.getElementById('pin');
tl.set('#s0', {{opacity: 1}}, 0);
document.querySelectorAll('.leg').forEach((leg, i) => {{
const len = leg.getTotalLength(), draw = {{t: 0}};
leg.style.strokeDasharray = len;
leg.style.strokeDashoffset = len;
tl.to(draw, {{t: 1, duration: {LEG}, ease: 'power1.inOut', onUpdate: () => {{
leg.style.strokeDashoffset = len * (1 - draw.t);
const p = leg.getPointAtLength(len * draw.t);
pin.setAttribute('cx', p.x); pin.setAttribute('cy', p.y);
}}}}, {START} + i * {LEG + HOLD});
tl.set('#s' + (i + 1), {{opacity: 1}}, {START} + i * {LEG + HOLD} + {LEG});
}});"""
length = round(START + (len(stops) - 1) * (LEG + HOLD) + END, 2)
timeline = {"tracks": [{"clips": [{"asset": {"type": "html5", "html": html, "css": css, "js": js},
"start": 0, "length": length, "width": W, "height": H}]}]}
if trip.get("soundtrack"):
timeline["soundtrack"] = {"src": trip["soundtrack"], "effect": "fadeOut"}
return {"timeline": timeline, "output": {"format": "mp4", "fps": 30, "size": {"width": W, "height": H}}}
def render_all(edits, key):
headers = {"x-api-key": key}
jobs = {}
for name, edit in edits.items():
r = requests.post(f"{API}/render", json=edit, headers=headers, timeout=30)
jobs[name] = ({"id": r.json()["response"]["id"], "status": "queued", "url": ""} if r.ok
else {"id": "", "status": "failed", "url": "", "error": r.text[:300]})
print(f"{name}: {jobs[name]['status']} {jobs[name]['id']}")
time.sleep(0.25) # stays under the Edit API limit of 300 requests a minute
deadline = time.time() + 15 * 60
while time.time() < deadline and any(j["status"] not in ("done", "failed") for j in jobs.values()):
waiting = [n for n, j in jobs.items() if j["status"] not in ("done", "failed")]
time.sleep(max(10, len(waiting) / 4))
for name in waiting:
r = requests.get(f"{API}/render/{jobs[name]['id']}", headers=headers, timeout=30)
if r.ok:
render = r.json()["response"]
jobs[name].update(status=render["status"], url=render.get("url", ""), error=render.get("error", ""))
if render["status"] in ("done", "failed"):
print(f"{name}: {render['status']} {render.get('url') or render.get('error', '')}")
return jobs
def main():
trips = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))["trips"]
countries = load_countries()
edits = {trip["name"]: build_edit(trip, countries) for trip in trips}
if "--dry-run" in sys.argv:
Path("edits").mkdir(exist_ok=True)
for name, edit in edits.items():
Path("edits", f"{name}.json").write_text(json.dumps(edit, indent=2), encoding="utf-8")
print(f"{name}: edits/{name}.json, {len(json.dumps(edit)) // 1024} KB")
return
jobs = render_all(edits, os.environ["SHOTSTACK_API_KEY"])
Path("results.json").write_text(json.dumps(jobs, indent=2), encoding="utf-8")
print("Saved results.json")
if __name__ == "__main__":
main()How the script works
load_countries()downloads the Natural Earth file once and reads it.projector()turns a stop’s latitude and longitude into a pixel position on the 1920x1080 frame. It fits all the stops below the title, with a margin of 30% of the route’s size on each side.land_path()turns the country outlines into one SVG path. It skips every outline that is completely outside the frame.build_edit()builds the page and the edit for one trip. Each leg is a gentle curve: an SVG curve whose control point sits to one side of the leg’s middle, at 15% of the leg’s length. Every title and name goes throughescape(), so characters like&,<and quotes show as typed.render_all()sends every trip first. Then it checks each unfinished render about every 10 seconds until all of them are done or failed. Its pauses keep the script under the Edit API’s rate limit of 300 requests a minute on production.main()saves the result for each trip inresults.json.
The animation timeline
The JavaScript in build_edit() makes one GSAP timeline. For each leg, it does two things:
- It runs a 1.6-second tween from 0 to 1, with a slow start and end. On each frame,
onUpdateuses that value to draw that much of the leg (withstroke-dashoffset) and to move the pin to the tip of the line (withgetPointAtLength). - At the moment the tween ends,
tl.setshows the next stop’s dot and name.
The pin and the line read the same point on the same path, so the pin stays on the tip of the line. The timeline waits 0.8 seconds before the first leg, 0.5 seconds at each stop and 1.5 seconds after the last stop. So the length of the video is:
length = 0.8 + (stops - 1) x 2.1 + 1.5 secondsA trip with 5 stops is 10.7 seconds long, and a trip with 2 stops is 4.4 seconds long. Change START, LEG, HOLD and END at the top of the script to change the timing. The script works out the length of the clip from the same numbers.
Run the script
Set your API key in the terminal. On macOS or Linux:
export SHOTSTACK_API_KEY="your_production_api_key"On Windows, in PowerShell:
$env:SHOTSTACK_API_KEY = "your_production_api_key"First, build the edits without rendering anything. This saves each trip’s Edit JSON in an edits folder, prints its size and does not need an API key:
python route_map.py trips.json --dry-runlisbon-to-rome: edits/lisbon-to-rome.json, 52 KB
japan-rail: edits/japan-rail.json, 38 KB
pacific-coast: edits/pacific-coast.json, 30 KBThen render all the trips:
python route_map.py trips.jsonThe script prints a line when it sends each trip and another when each video is ready:
lisbon-to-rome: queued 5b2e8f41-0c7d-4a93-b6e1-9f3d27a84c06
japan-rail: queued c81a4d27-6f3e-4b05-a9d2-1e7b60f5c938
pacific-coast: queued 2f97c0e3-8a4b-4d16-b5f7-3c0e9a12d684
lisbon-to-rome: done https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/7n4qk2xw9e/5b2e8f41-0c7d-4a93-b6e1-9f3d27a84c06.mp4
japan-rail: done https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/7n4qk2xw9e/c81a4d27-6f3e-4b05-a9d2-1e7b60f5c938.mp4
pacific-coast: done https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/7n4qk2xw9e/2f97c0e3-8a4b-4d16-b5f7-3c0e9a12d684.mp4
Saved results.jsonresults.json holds the render ID, status, video URL and any error message for each trip. Open a URL to watch the video or download it.
What the renders showed
We ran the script on production with the sample file and measured the three videos.
- Each video is 1920x1080, 30 fps, 321 frames and 10.7 seconds long. Each has one audio track, which is the trip’s music.
- We checked all 12 stop arrivals across the three videos. On the arrival frame, the center of the pin was within 0.7 pixels of the stop’s dot every time.
- Each stop’s name was not on screen 2 frames before the pin arrived, and it was on screen on the arrival frame.
- The page uses
font-family: sans-serifand loads no web fonts. The renderer drew the text with its own sans-serif font.
Here is a frame from the middle of the Japan trip, with the pin on its way from Kyoto to Hiroshima:

And the last frame of the Pacific Coast trip. The Los Angeles name sits under its dot:

Special characters and a short trip
We also rendered a trip with 2 stops and this title: Mia's "big" Alps & Rhône trip, with the subtitle 2 stops <weekend>. The stops were Zürich and Saint-Étienne. The video was 4.4 seconds long, and the apostrophe, quotes, &, <weekend> and the accented names all showed exactly as typed:

Change the look
The style is in the css string in build_edit():
.seaand.landset the colors of the sea and the countries.strokeon.landsets the color of the borders..legsets the color and width of the route.#pinsets the color of the pin..stop textsets the size and color of the names. The darkstrokewithpaint-order: strokedraws an outline around each letter, so names stay readable on top of the route..title band.title spanset the title and subtitle.
To show more of the map around the route, pass a larger margin to projector(). To make room for a taller title, pass a larger top.
Make your first map video
Create a free Shotstack account, copy your production API key, and run the script with the sample file. Then replace the sample trips with your own. Add a trip for each booking or itinerary, and the script makes all the videos in one run. To make one video for each row of a spreadsheet instead, see how to make count-up animation videos, which reads a CSV file.
Frequently asked questions (FAQs)
Can I use Google Maps or Mapbox for the base map?
Not as live map tiles. An html5 page can’t load anything from the network while it renders, so tiles from a map service can’t load. Everything the map shows must be inside the page, which is why this script draws the countries itself from a file it downloaded before the render.
Does the route follow the real roads?
No. Each leg is a curve from one stop to the next, so the video shows the order of the stops, not the exact road or rail line.
How long is each video?
0.8 seconds, plus 2.1 seconds for each stop after the first, plus 1.5 seconds at the end. A 5-stop trip is 10.7 seconds, and a 2-stop trip is 4.4 seconds. Each extra stop adds 2.1 seconds.
Why does a stop’s name cover another one?
The map fits the whole trip into the frame. When two stops are close, their names can touch. Add "label": "below" to one of the stops to put its name under its dot.