AdvenShare is an app for off-road racing teams. Teams import the organiser's GPX file for a race and follow it on a Mapbox map. One real race file became my reference case: 1.7 MB, 19,463 track points across 27 segments, and 988 waypoints.
Loading that file produced roughly 2,030 style layers and 989 sources. The map crawled. On another screen, a broadcast route with 2,369 waypoints built about 4,700 layers and showed up in crash reporting as app hangs.
After the rewrite the same file draws with about 8 layers. This is what changed and why.
Where 2,000 layers came from
The original code was written for a handful of pins, and it did the obvious thing: one pin, one marker. Each waypoint got its own GeoJSON source, two layers (a pin and a low-zoom dot) and its own rasterised bitmap. 988 waypoints is 1,976 layers before the route is even drawn.
The route had the same shape of problem. Each of the 27 segments has its own shade, so each got a line layer and an arrow layer, both filtered to that segment's id. That is 54 layers over one source, and every one of them evaluates its filter against every feature.
The per-pin cost was not only the layers. Adding a pin also:
- asked the style for all of its layer identifiers to work out where to insert, which added up to roughly 5,000 round trips per draw
- scheduled a delayed closure to re-order the start and end markers above it, 988 times, each scanning every layer
- drew a bitmap with Core Graphics, 988 times, on every redraw
None of this is expensive once. All of it is linear in pin count, and some of it is linear in pin count times layer count.
One source, three layers
Mapbox styles are meant to be data-driven: a layer describes how to draw a class of feature and reads the specifics from feature properties. So the whole waypoint set becomes one FeatureCollection in one source, drawn by three layers: a symbol layer for text pins, a symbol layer for emoji pins (they anchor differently) and a circle layer for the low-zoom dots.
var features: [Feature] = []
features.reserveCapacity(pins.count)
for pin in pins {
var feature = Feature(geometry: .point(Point(pin.coordinate)))
feature.properties = [
"pinId": .string(pin.id),
"kind": .string(pin.isEmoji ? "emoji" : "pin"),
"icon": .string(pin.imageKey),
"dot": .string(pin.colorHex)
]
features.append(feature)
}
var source = GeoJSONSource(id: "pins")
source.data = .featureCollection(FeatureCollection(features: features))
var layer = SymbolLayer(id: "pins-text", source: "pins")
layer.filter = Exp(.eq) { Exp(.get) { "kind" }; "pin" }
layer.iconImage = .expression(Exp(.get) { "icon" })
layer.iconAllowOverlap = .constant(true)
Two things follow from this. Calling the function again when the source already exists only swaps the GeoJSON, so adding, editing or deleting one waypoint no longer rebuilds anything. And the insertion position and the start/end marker re-order are resolved once per collection instead of once per pin.
The route got the same treatment. I resolve each segment's colour up front, write it into the feature as a property, and draw all 27 segments with a single line layer whose colour is an expression reading that property, with the route's base colour as the fallback. 54 layers became 2.
Reusing pin bitmaps
Pin labels are baked into the bitmap because they use a specific bold font, and Mapbox text layers render with the style's own glyph fonts. So I kept the bitmaps but stopped drawing one per pin.
A pin's appearance is fully determined by its colour, its label truncated to four characters, and whether it is a text or glyph pin. I build the image id from exactly those values. Of the 988 waypoints in the reference file there are 606 distinct names but only 527 distinct four-character prefixes, and 198 of them are "Danger" pins in the hazard colour that all share one image.
var builders: [String: () -> UIImage] = [:]
for pin in pins where builders[pin.imageKey] == nil {
builders[pin.imageKey] = { renderPin(pin) }
}
for (key, build) in builders where !map.imageExists(withId: key) {
try? map.addImage(build(), id: key)
}
The builders are closures on purpose. Nothing is rasterised until the style says it does not have that id. First draw: 527 rasterisations instead of 988. Every redraw after that: zero. I ask the style rather than keeping my own set of registered ids because a style switch clears the sprite, and a stale cache would leave blank pins.
Hit-testing with the renderer
The old tap handler projected every waypoint to screen space, 988 point(for:) calls, then walked all 19,462 line segments of the route looking for the nearest one. That ran on every tap.
The renderer already knows what is drawn under a finger. queryRenderedFeatures takes a screen rect and a list of layer ids and returns the features there, with their properties.
let rect = CGRect(x: tap.x - 22, y: tap.y - 22, width: 44, height: 44)
let options = RenderedQueryOptions(layerIds: pinLayerIds, filter: nil)
_ = map.queryRenderedFeatures(with: rect, options: options) { result in
guard case .success(let hits) = result else { return }
let nearest = hits.min { distance($0, tap) < distance($1, tap) }
// read "pinId" from nearest's properties and open the sheet
}
Because every feature carries its id and label as properties, I no longer keep a parallel Swift table of waypoint coordinates for hit testing. The dot layer is included in the query so taps still land at zooms where the full pin has not faded in yet.
Tap-on-trail works the same way. The query returns the line geometry from the rendered tile, which is a few dozen vertices near the tap, and I snap to that instead of the full point array. The call is asynchronous, so the tap priority chain (live vehicle markers beat waypoints, waypoints beat the trail) had to become a chain of callbacks.
Zoom-gating the expensive layers
Direction arrows are symbols placed along a line, and line-symbol placement re-runs on camera moves over the whole geometry. At overview zoom, on 19,000 vertices, that is work for arrows nobody can read. The arrow layer now has minZoom 11, and its spacing interpolates from 400 at zoom 11 down to 100 at zoom 14.
Waypoints use opacity expressions on zoom instead of separate layers: dots at low zoom, pins fading in between roughly 12.5 and 13.5, dots gone by about 14.5.
I also changed the preferred frame rate from 120 to 60. Asking for a rate a heavy style cannot hold only makes the drops more visible.
What was measured
| Before | After | |
|---|---|---|
| Style layers (reference file) | ~2,030 | ~8 |
| Waypoint sources | 989 | 1 |
| Pin rasterisations, first draw | 988 | 527 |
| Pin rasterisations, redraw | 988 | 0 |
| Route segment layers | 54 | 2 |
| Work per tap | 988 projections + 19,462-segment walk | one rendered query |
These are counts, not frame times. I did not record a before-and-after FPS trace, and I will not quote one.
I did measure the thing I expected to need next, geometry simplification. Ramer–Douglas–Peucker at a 5 m tolerance keeps 26.5% of the points but puts about 10.6 px of drift into the trail at zoom 18. At 1 m the drift is 2 px, and it only removes a quarter of the points. No single tolerance was both worthwhile and invisible, so I did not ship one.
Takeaways
- Count layers before optimising geometry. I assumed 19,000 points was the problem. A single line layer over that many vertices is routine for Mapbox. Two thousand layers is not.
- If per-item code calls back into the style, it is quadratic waiting for a large enough file. The per-pin API survived for the recording screen, which handles a handful of waypoints, and that is the only place it belongs.
- Content-address images by what determines their pixels, and let the style be the cache.
- The route source still goes through a dictionary-to-JSON-string round trip of about 1.5 MB per redraw, and parsing still happens on the main thread. Those are next, after profiling says they matter.
- For shared race routes that many users load, the right answer is probably vector tiles served by the backend, so the client holds no geometry at all. I would start there if I were building this again.