Most map apps stop at "tile layer plus blue dot". A marine app cannot: a sailor wants depth under the keel, wind and waves in six hours, distance off the planned track, and help if someone falls overboard, all without signal, which at sea is most of the time.

This post is a tour of Piri Reis, a marine navigation app we build with Flutter for iOS and Android, named after the 16th century Ottoman admiral and cartographer. This is mostly about the engineering: depth data, our own contour engine, a three.js scene inside Flutter, and the mistakes along the way.

What the app does

It turns a phone or tablet into a simple chartplotter for every sea, with the richest detail in the Mediterranean.

Depth chart with labelled contours in the Gulf of Gokova, Turkey

The main screen is a map with stacked layers: a land base map (standard, satellite or plain), a coloured depth layer with labelled contours (20, 30, 50, 100, 200, 500, 1000 and 2000 m), shaded seabed relief, OpenSeaMap sea marks and an optional rain radar. On top of that:

  • Route planning in nautical miles, plus a route briefing with ETA, wind, waves and current at every waypoint.
  • A navigation dashboard: SOG, COG, depth, position, cross-track error (XTE) and ETA.
  • A 48-hour marine forecast strip for any point you tap.
  • Man overboard (MOB), anchor watch, SOS to emergency contacts over WhatsApp or SMS, and automatic storm warnings for favourite spots.
  • Track recording with background GPS, voyage replay and GPX export; offline charts.
  • A 3D voyage view of your route, the seabed, the coast and the forecast.
  • Place search, favourites, GPX import, a fuel log, a boat calendar, units (kn, km/h, m/s, m, ft, °C, °F, DD/DMM), day and night themes, and 13 UI languages including right-to-left Arabic and Hebrew.

One rule we set early: safety features are never behind the paywall. Navigation, routes, MOB, storm warnings and SOS are free; premium adds the data-heavy features (offline packs, the depth map, anchor watch, detailed marine weather, the 3D view). The app also says plainly that it is not a replacement for official nautical charts, and that shaped many of the decisions below.

The stack at a glance

Layer What we use
App Flutter (Dart), one codebase for iOS and Android
2D map flutter_map 7 + latlong2, custom TileProviders
Storage sqflite (voyages, routes, favourites, SOS contacts, calendar, fuel log), shared_preferences
Location geolocator with background modes
3D three.js bundled by esbuild into one JS asset, loaded with webview_flutter
Backend Two small Cloudflare Workers (depth tiles; API for accounts, sync and 3D forecast tiles) + R2
Data NOAA ETOPO 2022, GEBCO, EMODnet Bathymetry, Open-Meteo, OpenSeaMap / OpenStreetMap, Nominatim

Everything heavy happens on the device. The backend caches and proxies; it is not in the loop for normal navigation.

Depth: the hard part

The first versions used pre-rendered depth tiles from public WMS servers: EMODnet for European waters, GEBCO for the rest. It looked fine in a demo and fell apart in real use:

  1. Speed. Server-rendered GEBCO tiles were 25 to 50 KB each and slow. A new region took about 12 seconds to show a patchy screen and roughly two minutes to fill. Users described it as "some squares light, some dark".
  2. Coverage. EMODnet contours only exist in European waters. Elsewhere we had colours but no lines.
  3. Offline. WMS layers cache badly, and depth matters most when there is no connection.

So we built our own pipeline.

One grid, three layers

A small Cloudflare Worker serves /v1/depth/{z}/{x}/{y}.png. It requests NOAA's ETOPO 2022 ImageServer as signed 16-bit integers with bilinear interpolation and packs the result into an ordinary RGB PNG:

metres = R * 256 + G - 32768 (sea negative, land positive; R = G = 0 means no data) B = GEBCO 2024 TID code (how this cell's depth was obtained) 

Tiles are 260 x 260, not 256: two pixels of padding per edge, so contours join seamlessly across tile borders and the slope checks below work in edge cells too.

The blue channel matters. GEBCO publishes a "Type Identifier" grid saying whether each cell's depth came from a survey or was estimated from satellite gravity. Shipping it alongside the depth means one request answers both "how deep" and "how much should I trust this".

On the device, three TileProviders consume the same grid: one paints the colour ramp, one runs the contour engine and draws lines and labels, one computes hillshade (Horn slope and aspect, light from the north-west). All pixel work runs in Isolate.run. Because they share a grid, colour, relief and contours are always aligned, there is no extra request per layer, and once a tile is on disk all three work offline.

The colour ramp was not hand picked. We matched EMODnet's rainbow tiles against our grid in 12 regions (about 480,000 pixel pairs) and took the median colour per depth bucket, so colours do not jump when you sail out of EMODnet coverage.

A contour engine that refuses to lie

The engine is marching squares, ported line by line from a Python reference. A fixture generated by the Python code is checked bit for bit by a Dart unit test, which caught regressions more than once.

Plain marching squares is not enough. Global data at 15 arc-seconds cannot know exactly where a line runs along a steep coast; a one-cell shift on a cliff is a huge depth error. Drawn naively, about half of our 50 m line in test areas was wrong, and some crossed land. So every segment passes a slope gate:

  • a near window (4 x 4 nodes) bounds the relief around the segment relative to the contour level;
  • a wide window (8 x 8) rejects segments that look flat locally but sit next to a wall, typical on carbonate bank edges in the Bahamas or Fiji;
  • a plateau check (16 x 16) removes "contours" that are just the edge of a flat plateau whose value happens to match the level.

Segments in cells marked as estimated are drawn dashed with a tilde label, and where data is too weak the app draws no line. In European waters our lines are suppressed entirely in favour of EMODnet's survey-based contours, so users never see two conflicting lines. Knowing where EMODnet has coverage required a generated mask: a world scan at zoom 6, a re-scan of every non-empty tile at zoom 8, about 3,000 tiles baked into the app as a constant list.

We validated against GEBCO 2020 at a couple of hundred points across 13 regions. The lesson: for a safety-adjacent feature, an honest gap beats a confident wrong line. Users accepted "no contour here" once the store text and an in-app note explained why.

The 2D map in Flutter

Planning a three-leg route with bearings and distances per leg

flutter_map does a lot of the work, but almost every layer runs through a custom tile provider.

Read-through cache. Every displayed tile is written to disk, keyed by the MD5 of its URL. The offline downloader uses the same URL builders and keys, so pre-downloaded tiles are served from cache with no special path. One bug: flutter_map's built-in WMS URL generator formats parameters slightly differently from ours, so downloaded WMS tiles missed the cache. Now every WMS URL comes from one shared function.

Loading. Satellite tiles share one persistent HTTP connection, off-screen tiles are cancelled, and a preview from two zoom levels lower shows while high-zoom tiles load. The contour halo that keeps lines readable used to be a full-screen ImageFiltered layer recomputed every frame; baking it once per tile made panning noticeably smoother.

Routes, briefing and GPX

Route briefing: ETA, wind, waves and current at every waypoint

Routes live in sqflite next to favourites and voyages. Routes, favourites and tracks import and export as GPX 1.1 (rte, wpt, trk), since that is what plotters, OpenCPN and Garmin expect. The files are small, so the parser is a few regular expressions rather than an XML library.

The briefing takes the route, a departure time and a planned speed, computes when you reach each waypoint, and asks the forecast for that place at that hour. It is labelled as a planning aid: constant speed, current taken at the start of each leg.

The navigation dashboard

Following a route: SOG, COG, depth under the boat, XTE and ETA

After "Go", the dashboard shows SOG and COG, depth at the boat from the depth grid, the active waypoint, XTE with a direction arrow, and ETAs.

GPS is where battery is won or lost, so the location service has three profiles: idle (medium accuracy, roughly every 10 seconds or 25 m), navigating (best accuracy, interval stepped by boat speed with a little hysteresis) and recording (background mode: a foreground service on Android, background location on iOS, so the track survives a locked screen). An early version opened a new position stream on every toggle without closing the old one and wrote points two or three times. Now one service owns a single stream that every screen, including 3D, subscribes to.

Weather: a 48-hour strip

Tap anywhere for depth, wind, waves and a 48-hour hourly strip

Tap the sea and a panel shows depth, wind (speed, direction, gust, Beaufort), waves and swell, sea and air temperature, pressure, visibility and cloud, with a 48-hour strip on top; tapping an hour updates every row. Data comes from Open-Meteo's forecast and Marine APIs.

Two early bugs: a hard-coded home time zone silently shifted rows for everyone else (fixed with timezone=auto plus timeformat=unixtime), and every coordinate printed as °N °E. A small units module now handles hemispheres, DD/DMM and all units.

Storm warnings reuse the forecast: up to eight favourite spots, nearby ones merged into one request, checked over 48 hours against Beaufort and gust thresholds.

Safety features that must never get in the way

Man overboard: bearing, distance and time back to the marked position

Man overboard is one tap, with no confirmation dialog: in that moment every extra tap is a failure. A red strip keeps showing bearing, distance and elapsed time back to the spot.

Anchor drag alarm when the boat leaves the safe radius

Anchor watch has its own location stream, independent of the map, so it runs with the app in the background. On iOS it uses the location background mode and an audio category that plays even on silent. Once silenced, the alarm does not re-trigger until the boat has come back inside the circle and left again: an endless alarm causes panic without adding information.

Related: for months the app had zero ratings because it never asked. The review prompt now appears only after a good moment (a completed voyage, a quiet anchor watch, a 10-minute GPS session) and never during an alarm, on the SOS screen or after an anchor alarm.

Night mode, and a decision we reverted

Night chart: dark base map with a separate label layer

The first night mode, a red ColorFiltered matrix over the map, was unpopular, so it went. The night chart now uses Esri's dark grey base with a separate reference layer for place names; the dark base alone has no labels, and you could not find a harbour at night. Contour lines got a white stroke with a navy edge so they read on both themes.

The 3D voyage view: three.js inside Flutter

3D voyage view following the boat along the route, with the dashboard underneath

Draw a route, tap 3D, and see seabed, coastline, route, waves, current and hazards in three dimensions. While navigating the camera follows the boat, and the 2D dashboard stays underneath.

Why a WebView

We already had a three.js route simulator from an aviation project; rebuilding it in Flutter would have taken months. So the engine is plain JavaScript in its own folder (core, sea, weather, observations, text, helpers), esbuild bundles it with three.js into one minified file of about 800 KB, and the app loads it from Flutter assets with webview_flutter's loadFlutterAsset. No website, no login, same behaviour on both platforms.

The bridge is tiny. Flutter calls one global function with a config object (language, theme, route, speed, departure time, boat draft, units, hazards, harbours, GPS fix). The page posts JSON on one channel: ready, draft changed, time changed, close, error. While navigating, Flutter pushes each fix with piriKonum({lat, lon, sog, cog}), reusing the map's location stream instead of opening another one.

Terrain and depth in 3D

The scene combines Terrarium elevation tiles for the coast and land (about 30 m per pixel at zoom 12), EMODnet's bathymetry DTM (about 115 m) for the seabed where available with ETOPO 2022 elsewhere, and an optional satellite texture on land. A cold open used to take tens of seconds, so the scene now loads in two passes: a coarse mesh appears within seconds while full-detail data already downloads in parallel, then the detailed mesh replaces it without moving the camera.

Details that took several iterations:

  • Coastline staircase. Separate land and sea materials gave a jagged, grid-aligned coast. A single material now blends land and sea per vertex, and each cell's triangle diagonal is chosen to follow the coast.
  • 3D must match 2D. Users compared the views and spotted different colours and levels. The engine now uses the exact palette and contour levels of the Dart code, the seabed is drawn unlit so lighting does not shift colours, and each contour line gets one label at its true depth.
  • Water that reads as depth. The water column is nearly transparent in the shallows and darker with depth, and there is an underwater camera.
  • Shader gotcha. A ShaderMaterial with fog: true requires a vertex shader variable named exactly mvPosition, or you get a confusing compile error.

Shallow-water checks without false alarms

The 3D view samples the route every 35 m or so and warns about water shallower than the boat's draft plus a margin, and about legs crossing land. The check was easy; the false positives were not:

  • In narrow bays the coarse global grid can say "land" where the 30 m coastline says "sea". Such cells are unknown: no warning, no red.
  • EMODnet smears the shoreline by a cell or two. A route 100 to 250 m off a rocky headland, through water clearly deep on satellite imagery, was reported as 0.3 m. Now, within about 350 m of the high-resolution coast, EMODnet shallowness is not a shallow warning; within about 80 m it becomes "very close to shore".
  • Departure and arrival quays are excluded from the land check.

Each rule came from a real route that produced a bogus warning, checked against satellite imagery. A fixed note reminds users that depth is approximate.

Forecast tiles on the server

Free 3D mode: the camera follows the boat's GPS position without a route

There is also a free mode with no route, where the camera simply follows the boat. Waves, swell, current and sea temperature come from Open-Meteo Marine, cached by the API Worker as forecast tiles in R2. Our policy got stricter over time:

  • Where a user has drawn a route, data must be fresh: a missing or nearly hour-old tile is refreshed during the request.
  • If it cannot be refreshed (daily budget used, or upstream 429), old data is not served. Cells come back null, the layer is hidden, and the screen says current data is unavailable. A stale wave layer shown as current is worse than none.
  • An hourly cron warms tiles in the background, spreading the remaining daily budget over the remaining hours, recently requested areas first.

One Cloudflare trap: responses served from the Cache API came back with a much longer Cache-Control max-age than we had set. We now keep the intended lifetime in a custom header and re-apply it on hits.

Hazards (rocks, reefs, islets, sea marks, cables) come from OpenStreetMap via Overpass, queried by the app itself, because public Overpass mirrors did not answer requests from Cloudflare's egress. The app asks three mirrors at once and takes the first valid answer, rounds the bounding box to 0.1 degrees so nearby routes share a cache entry, and keeps results for 24 hours. The same lookup powers the 2D "tap a lighthouse" card, which shows the light characteristic in chart notation such as Fl(2) W 10s 15m 12M.

Offline first, private by default

All user data lives in SQLite on the device. Signing in is optional and used for backup and moving to a new phone: records carry device-generated UUIDs, conflicts are "last writer wins" on a timestamp, deletes are soft so they sync. We later went further: coordinates do not leave the device. Track points, routes and favourites are not uploaded; only voyage summaries, and calendar and fuel entries without coordinate columns, are synced. Where someone anchors every night is sensitive, and the simplest protection is never to hold it.

Lessons learned

  1. Own your core data path. Our own depth grid made the app faster, offline-capable and able to flag confidence per cell. The Worker serving it is under 300 lines.
  2. Pad your tiles, and port algorithms with a golden test. Two pixels of overlap removed a class of seam artefacts; a bit-exact fixture kept the contour engine honest.
  3. Not drawing is a feature. Gating contours and hiding stale forecasts cost visual completeness and earned trust.
  4. A WebView is a fine 3D runtime. For a self-contained scene with a narrow bridge, an embedded three.js bundle beat a rewrite by months. Keep the bridge tiny and share one GPS stream.
  5. Safety UX is about what you do not do. No confirmation on MOB, no rating prompt after an alarm, no alarm loop after silencing.
  6. Watch for permissions you never asked for. A file picker plugin referenced camera and photo APIs, and an iOS build was silently dropped during processing because the usage descriptions were missing from Info.plist. It never appeared in the build list.

What is not there (yet)

  • Tides. We have not found a free, global, open tide source we would trust, so the app says "no data" rather than guessing.
  • Real-time wave buoys and high-resolution ocean currents are not integrated.

Try it

If you sail, tell me where the depth data or the 3D view gets your waters wrong; that feedback shaped the filters above.

Questions about the contour gates, the three.js bridge or the tile cache are welcome in the comments.

Data credits: OpenStreetMap contributors, OpenSeaMap, NOAA NCEI ETOPO 2022, GEBCO, EMODnet Bathymetry, Open-Meteo, Esri, RainViewer. Depth information is approximate and comes from public third-party data; always use official nautical charts.