Files
maptool/docs/library-design.adoc
T

13 KiB
Raw Blame History

Library: data model for tracks, points and sync (design)

Status: phase 1 implemented (lib/maptool/library.rb, see Decisions); phases 2–4 proposed. Replaces the file-based store behind Tracks & Points (GpxStore) with an item-based library that OsmAnd, Locus Map and the MapTool web app can all be synced against.

Why

The same tracks and points live in three places — MapTool, OsmAnd+ and Locus Map on the phone/tablet — each edited independently. Today the unit of storage in MapTool is a file (a .gpx/.fit/.geojson in a folder), and nothing inside a file has a stable identity, a change time, or a record of having been deleted. That’s fine for "upload and look at it", but any sync needs to answer which point changed, where, and since when — impossible when the smallest thing we know about is a whole file.

Goals:

  • One folder tree with points and tracks mixed in it (Locus-style "project" folders).

  • Every point and track an item with a stable id, timestamps and a tombstone on delete.

  • A change feed that a sync client (Android app, the PWA) can poll.

  • Import/export to GPX that round-trips what OsmAnd and Locus care about (folders, names, descriptions, colors, icons).

Non-goals (for now): real-time collaboration, merging concurrent edits field by field, syncing hiking trails / offline map data (those are derived, not user data), LiveTrack sessions.

How the apps model their data

Locus Map 4

  • One library: a tree of folders and subfolders in which tracks, planned routes and points can be mixed. The separate points/tracks tabs of Locus 3 are gone.

  • Nesting: 3 levels free, 6 with Premium.

  • Items can be filtered by type (only tracks / only points) for display.

  • Exporting a folder exports all of its content into one file.

  • Syncs every change to Locus' own web library (no public API known).

  • App data (waypoints.db, tracks.db) is SQLite, but not a supported integration point; the Locus API is mainly for sending points/tracks into Locus.

Sources: My Library, blog, locus-api.

OsmAnd+

  • Favorites (points) in folders/groups, nested ("Travel / Italy / Rome"); a name must be unique within its folder. Each has address, description, icon, color and background shape, defaulting to the folder’s. Stored as GPX <wpt> with osmand:icon, osmand:color, osmand:background, osmand:address extensions.

  • Tracks are separate GPX files in track folders (plus "smart folders", virtual filters). A track file can carry its own waypoints.

  • Points and tracks are not mixed: a "project" maps to a favorites folder plus a track folder of the same name.

  • AIDL API: add/update/remove favorites and favorite groups, import/show GPX. Whether it can list existing favorites/tracks is unverified — check osmand-api-demo before relying on reading from OsmAnd.

Sources: Favorites, Tracks, API/SDK.

mapy.com

No API. Data arrives by exporting/sharing a GPX from the app — the PWA share target (public/sw.js, public/js/share_import.js) covers that.

What that means for us

Locus' model is the most general: a folder tree with mixed items. OsmAnd fits into it by splitting each folder into "its points" (a favorites folder) and "its tracks" (a track folder). So MapTool adopts Locus' shape and maps to OsmAnd on export/sync.

Current model (GpxStore) and its gaps

  • data/gpx/ folder tree; each file is a .gpx, .fit or .geojson, converted to a GeoJSON FeatureCollection (cached as *.gpx.geojson).

  • A file mixes tracks/routes (LineString/MultiLineString) and waypoints (Point), each with properties: kind, name, description, time, category, color, icon (OsmAnd icon keys, e.g. amenity_parking), photos, activity_type.

  • Notes (notes.js) are Features appended to a .geojson "layer" file, the only ones with an id.

  • Plugin output and Overpass POIs land as .geojson files the same way.

Gaps: no per-item id (except notes), no updated_at, no tombstones, the file is the unit of move/delete/visibility, folder styling doesn’t exist, a file’s name is doubling as a "collection" name.

Proposed model

Stored in SQLite, data/library.sqlite (the sqlite3 gem is already a dependency for the place index).

Folders

CREATE TABLE folders (
  id          TEXT PRIMARY KEY,          -- uuid
  parent_id   TEXT REFERENCES folders(id),
  name        TEXT NOT NULL,
  color       TEXT,                      -- default for items inside
  icon        TEXT,                      -- OsmAnd icon key
  visible     INTEGER NOT NULL DEFAULT 1,
  created_at  TEXT NOT NULL,
  updated_at  TEXT NOT NULL,
  deleted_at  TEXT,
  UNIQUE (parent_id, name)
);

Depth capped at 6 so a tree always fits Locus Premium (warn above 3).

Items

CREATE TABLE items (
  id           TEXT PRIMARY KEY,         -- uuid
  folder_id    TEXT NOT NULL REFERENCES folders(id),
  type         TEXT NOT NULL,            -- 'point' | 'track' | 'route'
  name         TEXT,
  description  TEXT,
  geometry     TEXT NOT NULL,            -- GeoJSON geometry (Point / LineString / MultiLineString)
  properties   TEXT NOT NULL DEFAULT '{}', -- JSON: color, icon, width, category, time,
                                         -- activity_type, photos, address, ...
  bbox         TEXT NOT NULL,            -- [w,s,e,n], for search and the map
  fingerprint  TEXT NOT NULL,            -- hash of type + rounded geometry, for dedupe
  source_id    TEXT REFERENCES sources(id), -- the uploaded file it came from, if any
  created_at   TEXT NOT NULL,
  updated_at   TEXT NOT NULL,
  deleted_at   TEXT,
  rev          INTEGER NOT NULL          -- global change counter at last write
);
CREATE INDEX items_rev ON items(rev);
  • type: track = recorded (has timestamps/elevation), route = planned. Both lines; the split matters to Locus and for stats.

  • A recorded track keeps per-point time/elevation inside geometry’s coordinates ([lng, lat, ele]) plus a parallel `properties.times array — what the elevation profile needs today.

  • properties stays an open JSON bag so a GPX extension we don’t model (Locus/OsmAnd specific) survives a round trip unchanged.

Sources (original files)

CREATE TABLE sources (
  id          TEXT PRIMARY KEY,
  filename    TEXT NOT NULL,
  path        TEXT NOT NULL,              -- data/library/sources/<id>/<filename>
  imported_at TEXT NOT NULL
);

An upload is still kept as-is (for "download original"), but what the app works with is the items extracted from it. Deleting items never deletes the source; deleting a source is a separate admin action.

CREATE TABLE item_links (
  item_id      TEXT NOT NULL REFERENCES items(id),
  app          TEXT NOT NULL,             -- 'osmand' | 'locus' | ...
  device       TEXT NOT NULL,             -- one phone/tablet
  external_ref TEXT NOT NULL,             -- the app's id / favorite name+group / GPX path
  synced_rev   INTEGER NOT NULL,          -- our rev when last pushed/pulled
  PRIMARY KEY (item_id, app, device)
);

Neither app gives us our id back, so this table — kept by the sync client, reported to the server — is how "this OsmAnd favorite" and "this MapTool point" stay the same thing.

Change counter

A single rev sequence (a one-row table, incremented in the same transaction as every write) stamped on each folder/item write. rev — not wall-clock time — is what clients sync against, so clock skew on a phone can’t skip a change.

API

Route Purpose

GET /api/library/tree

Folders with item counts (replaces /api/gpx/tree).

GET /api/library/folders/:id/items.geojson

A folder’s items as a FeatureCollection, id/folder_id/updated_at in properties — what the map draws.

POST /api/library/import

Multipart upload (GPX/FIT/GeoJSON/ZIP) into a folder: stores the source, extracts items, skips items whose fingerprint already exists in that folder (re-sharing the same track from OsmAnd doesn’t duplicate it).

PUT /api/library/items/:id, DELETE …​

Edit (name, description, style, move to folder) / tombstone. PUT carries the rev the client last saw; an older one gets 409 with the current item.

GET /api/library/changes?since=<rev>

Folders and items (including tombstones) with rev > since, plus the new high-water rev. The sync feed.

GET /api/library/folders/:id/export.gpx?flavor=locus|osmand

GPX of a folder for an app (see mapping below).

Mapping to the apps

GPX in (import, share target)

  • <wpt> → point; <trk> → track; <rte> → route.

  • <type> → properties.category; osmand:color/locus: color and osmand:icon → color/icon (already parsed by Gpx.waypoint_style).

  • Folder: the one picked in the import dialog; a GPX’s own waypoint groups (OsmAnd’s per-folder favorites export) become subfolders.

  • FIT → one track. GeoJSON → items by geometry type.

Locus

Folder ⇄ folder, 1:1. Export a folder as one GPX with tracks and points together (Locus imports it into a folder). Locus-specific extensions (locus:icon, track style) are kept in properties and written back.

OsmAnd

  • A folder’s points → favorites group with the folder path as its name ("Van / Croatia 2026"), written as GPX <wpt> with osmand: extensions. OsmAnd requires unique names per group → duplicates get " (2)" appended on export only.

  • A folder’s tracks/routes → one GPX per item in a track folder with the same path (tracks/Van/Croatia 2026/<name>.gpx), track color/width in the GPX <extensions> (exact osmand: tag names to verify against a file exported from OsmAnd).

Sync (later phase)

  • Direction 1 — MapTool → apps: the Android sync client polls /changes, pushes new/changed items into OsmAnd (AIDL: favorites, GPX import) and Locus (locus-api: points/tracks into a folder), and records item_links. Deletes: remove via the API where it allows it.

  • Direction 2 — apps → MapTool: for now, sharing from the app (PWA share target) — fingerprint dedupe makes re-sharing safe. Automatic reading from the apps only if their APIs turn out to allow listing data (open question above).

  • Conflicts: last writer by rev wins per item; the losing version goes to an item_history table so nothing is silently lost.

Migration from GpxStore

One-off rake task, idempotent, data/gpx/ left untouched until verified:

  1. Each directory under data/gpx/ → a folder (same path).

  2. Each file → a subfolder named after the file (without extension), its features → items in it; the file → a sources row. (Alternative: put items straight into the directory’s folder — see open questions.)

  3. Notes' existing properties.id reused as the item id, so links to them survive.

  4. Category/icon/color carried over in properties.

Then the app switches to the library; GpxStore and /api/gpx/* are removed once nothing uses them.

What changes in the code

  • lib/maptool/library.rb (new): schema, import (reusing Gpx, Fit, Geojson parsing), queries, change feed, GPX export.

  • app.rb: /api/library/ instead of /api/gpx/.

  • public/js/gpx.js: tree of folders → items (visibility per folder and per item, item rename/move/delete), map sources per folder.

  • public/js/notes.js: create/edit items instead of appending to a layer file.

  • lib/maptool/search.rb: the "layers" source queries items (an FTS table over name/description) instead of scanning files in memory.

  • Plugins: output imported via the same import path.

  • share_import.js: posts to /api/library/import.

Phases

  1. Library schema + import + read-only map view, migration task, behind the same UI (tree shows folders/items). Old store still present.

  2. Editing (rename, move, delete, style) + notes on the library; remove GpxStore.

  3. Change feed + GPX export flavors for OsmAnd/Locus.

  4. Android sync client (one direction), then the other direction if the app APIs allow it.

Decisions (phase 1)

  • Migration: each old file → a subfolder named after it, holding the file as one layer item still drawn from its GeoJSON — not split into points. Splitting a layer into items can come later if needed; new imports are split right away.

  • Track waypoints: independent points with an optional parent_id (the GPX’s single track). The tree draws them with their track; Locus can get them loose in the folder, OsmAnd inside the track’s GPX. Both apps import a GPX with tracks and points together; neither exports GeoJSON (Locus imports it, OsmAnd doesn’t), so exports are GPX.

  • Simplified against the schema above: no sources table (an item’s source_path points at the stored upload), no description/bbox columns (in properties / computed when needed), folder styling and item_links not yet.

  • Migration runs on first start (no library.sqlite yet); rake library:migrate re-runs it (idempotent).

Open questions

  • Folder depth over 3 — fine to require Locus Premium?

  • Does OsmAnd’s AIDL API list existing favorites/tracks? Does locus-api read points/tracks by folder? Decides whether direction 2 can be automatic.