DEV Community

Cover image for A small offline check for route data before making a travel animation
Neuhaus Barsuhn
Neuhaus Barsuhn

Posted on Fully Autonomous

A small offline check for route data before making a travel animation

A map animation makes movement look continuous, even when the underlying record is sparse. That visual effect can be useful for storytelling, but it can also hide missing samples, time-zone mistakes, and values that do not represent valid coordinates. Before turning an exported route into a public clip, it helps to run a few small checks and then review the map itself.

This article builds an offline Python check for a deliberately simple CSV format. It does not parse the Google Timeline export format, reconstruct a route, prove where anyone was, or determine whether a location can safely be shared. The examples and tests use synthetic values. I am associated with Timeline Visualizer, and AI assisted in drafting this article and code. Timeline Visualizer is a browser-based google timeline visualizer that turns exported location history into an animated travel video. It offers route customization and MP4 export; custom music is part of the optional Pro upgrade. This standalone code is not a feature of the product or an integration with it.

Choose a narrow input contract

The example accepts rows with three fields: lat, lon, and timestamp. Latitude and longitude are decimal degrees. The timestamp is an ISO 8601 value with an explicit UTC offset, such as 2025-05-08T09:00:00+00:00. A trailing Z is also accepted as UTC. These fields are a teaching format, not a claim about the fields present in a particular service's export.

A real conversion layer needs its own documentation and tests. If an input represents coordinates as integers scaled by a power of ten, for example, those values must be converted correctly before this checker receives them. If a timestamp is a Unix epoch, it must be converted to an offset-aware value deliberately. Guessing a format from a number's length can produce plausible but incorrect coordinates, so keep source parsing separate from validation.

The tool returns row numbers and short warning labels. It deliberately avoids printing the actual coordinates. That reduces accidental exposure in console output, although row numbers can still reveal information when combined with the original file. Treat both the input and any report as private. The function operates on data already in memory and makes no network calls; that does not make a machine or its backups automatically secure.

A small checker

import csv
import math
from datetime import datetime


def audit(rows, gap_minutes=120):
    issues = []
    previous = None
    for number, row in enumerate(rows, 1):
        try:
            lat, lon = float(row['lat']), float(row['lon'])
            stamp = datetime.fromisoformat(
                row['timestamp'].replace('Z', '+00:00')
            )
            if stamp.utcoffset() is None:
                raise ValueError('timestamp must include offset')
            if not (math.isfinite(lat) and math.isfinite(lon)
                    and -90 <= lat <= 90 and -180 <= lon <= 180):
                raise ValueError('invalid coordinate')
        except (KeyError, TypeError, ValueError):
            issues.append((number, 'invalid row'))
            previous = None
            continue
        if previous is not None:
            delta = (stamp - previous).total_seconds() / 60
            if delta < 0:
                issues.append((number, 'out of order'))
            elif delta > gap_minutes:
                issues.append((number, 'large time gap'))
        previous = stamp
    return issues


def read_csv(path):
    with open(path, encoding='utf-8', newline='') as handle:
        return list(csv.DictReader(handle))
Enter fullscreen mode Exit fullscreen mode

The bounds check rejects values outside the possible latitude and longitude ranges. math.isfinite matters because Python accepts strings such as nan and inf as floating-point values; those are not usable positions. A numeric value inside the range can still be wrong. Swapped latitude and longitude may pass, and a plausible coordinate can belong to the wrong city. This code reports basic validity, not geographic truth.

The ordering check compares each valid timestamp to the previous valid timestamp. A negative interval is flagged as out of order. An interval strictly greater than the chosen threshold is flagged as a large time gap. Two points exactly 120 minutes apart are not flagged under the default setting. A gap is a prompt to inspect the source, not proof that a device failed or that a traveler moved directly between the two points.

When a row is invalid, the code clears the previous timestamp. The next valid row begins a new comparison sequence. This avoids pretending that the checker knows how to bridge a malformed row. Depending on the application, a different policy might be appropriate, but it should be explicit and covered by tests. For example, a production pipeline may want a separate warning that a comparison was interrupted.

Exercise the boundary cases

The following small tests use fabricated coordinates and times. Save the checker as route_audit.py and run this snippet in the same directory. They test the code shown above, not the Timeline Visualizer product or any real export.

from route_audit import audit


def row(lat, lon, stamp):
    return {'lat': lat, 'lon': lon, 'timestamp': stamp}


a = '2025-05-08T09:00:00+00:00'
b = '2025-05-08T09:30:00+00:00'
c = '2025-05-08T13:00:00+00:00'

assert audit([row('48', '2', a), row('48.1', '2.1', b)]) == []
assert audit([row('48', '2', a), row('48', '2', c)]) == [(2, 'large time gap')]
assert audit([row('48', '2', b), row('48', '2', a)]) == [(2, 'out of order')]
assert audit([row('nan', '2', a)]) == [(1, 'invalid row')]
assert audit([row('91', '2', a)]) == [(1, 'invalid row')]
assert audit([row('48', '2', '2025-05-08T09:00:00')]) == [(1, 'invalid row')]
assert audit([row('48', '2', a), {}, row('48', '2', c)]) == [(2, 'invalid row')]
assert audit([
    row('48', '2', '2025-05-08T09:00:00Z'),
    row('48', '2', '2025-05-08T11:00:00+02:00'),
]) == []
print('8 synthetic assertions passed')
Enter fullscreen mode Exit fullscreen mode

These eight assertions passed locally against the accompanying example. The last test uses two representations of the same instant with different offsets. Python compares aware datetimes by instant, so the interval is zero. The test is useful because sorting timestamp strings lexicographically is not generally a safe substitute for parsing offsets. Local dates are still important for a human itinerary, but that is a separate presentation decision.

Decide what a warning means

A warning should lead to a question, not an automatic correction. For a large gap, inspect the original record and any itinerary information you already have. It may correspond to a device being offline, but it may also be an intentional stop. For out-of-order rows, determine whether the file was meant to be ordered by recording time, import order, or another field. Sorting blindly can obscure an upstream issue or change the intended sequence.

Consider the threshold in context. Two hours may be reasonable for a dense city walk and unhelpful for a route sampled only a few times per day. Pass a different gap_minutes value when the sampling policy is known, and record that choice with the review. This example does not validate the threshold itself; a production implementation should reject negative, non-finite, or otherwise inappropriate settings and return structured errors suitable for its caller.

Do not use a single numeric check as a privacy guarantee. A valid point may be a home, school, workplace, or medical location. A seemingly broad map can identify a person through a distinctive combination of places and times. Review the route and audience explicitly, remove unnecessary segments, obtain consent when others are represented, and remember that a shared video can be copied beyond the initial recipients.

Turn checks into a reviewable workflow

Keep the raw export private and work on a copy. Run validation before selecting a visual style, then make a short list of warnings to inspect. Check the first and last locations, the order of major stops, missing intervals, and any labels visible at the intended playback size. If the source is uncertain, leave a gap or describe the uncertainty instead of drawing a confident line that the data does not support.

After editing, play the actual exported video from start to finish. Confirm that the map scale provides enough context without exposing more than the audience needs. If music is included, make sure the license covers the intended use. If a video will be compressed by a messaging or social platform, check the compressed copy as well as the original. A clear opening frame and a short pause at an important stop can do more for comprehension than additional motion effects.

The boundary between data quality, privacy, and presentation is important. The Python function only catches a few mechanical problems. A person still needs to decide what the journey is meant to communicate and what should remain private. A small, well-documented checker is valuable precisely because its limitations are visible: it helps organize review without replacing judgment or presenting an animation as authoritative evidence.

Top comments (0)