The map adapter
Part of Architecture, which is built from ARCHITECTURE.md in the repository, where it is edited.
MapLibre GL JS is the only map engine, and the ui never imports it. The adapter and the engine styles are in packages/adapter-maplibre, whose entry module exports createMapLibreMapAdapter, its options type MapLibreMapAdapterOptions and TILE_LAYER_SLOW_MS, and nothing else, so the class, the loader and the test options can change; its built declarations do not import maplibre-gl. The host imports it in createServices() only. MapView takes an adapter factory (() => MapAdapter) from the services, mounts one adapter in a host element and wires events to the rest of the ui. Changing basemap calls setBasemap on that adapter. It avoids transformStyle because a swap with it set waits for the current style, so a failed swap could not put the last basemap back. The adapter builds an inline raster style for a raster source and loads the style URL for a vector source. For a hybrid source it loads the label style and, in its style.load handler, before data layers, keeps only the line and symbol layers that draw from one of labelSourceLayers, less those in labelOmitLayers, so no area of the style (land, water, buildings, road areas) covers the imagery, and removes any source only the removed layers used. It then adds the imagery as a raster source capped at maxTileZoom and a layer under the rest, so MapLibre enlarges the deepest real level instead of asking for more, and under that a background layer in the basemap's swatch colour, so a dark basemap is not pale before its imagery draws. If that fails, a pending mount or swap fails with it, so a swap puts the last basemap back. No code names a basemap. MapLibreMapAdapter.ts keeps the map and the lifecycle (mount, destroy, the pending style load and style.load) and holds one module for each other job: the camera (camera.ts), the flat or globe placement of overlay marks (overlayPlacement.ts), the options of the map on screen (engineMap.ts), the engine loader (engineLoader.ts, which is the only adapter module that imports maplibre-gl at run time), and the modules named below for style, data layers, edit handles, image export and failures. The factory createMapLibreMapAdapter takes one option, loadWorkerUrl, a function that resolves to the URL of the engine's worker as the host serves it. The adapter does not import the worker: Vite's ?worker&url query lives in the host's packages/web/src/adapters/maplibre/workerUrl.ts, which adds the policy's cache key to the URL and which createServices() passes in, so the package holds nothing that only Vite understands. loadEngine calls it when the first map mounts, before it calls the engine's setWorkerUrl; a rejected loader fails the mount as load-failed and is asked again on the next one. The timing options the tests use (workerFailureGraceMs, imageTilesWaitMs, tileLayerSlowMs) are a second constructor argument that the factory does not take, and TILE_LAYER_SLOW_MS is the only constant MapLibreMapAdapter.ts re-exports, which the entry module exports in turn, for e2eTimers.test.ts. The style code is in basemapStyle.ts, as functions of the map and a basemap that hold no state: styleFor, composeHybrid and applyZoomLimits. The adapter calls them when it draws a basemap and in its style.load handler.
- Zoom is normalised to the 256 px tile convention (OpenStreetMap tile numbering). MapLibre counts 512 px tiles, so the engine zoom is the normalised zoom minus one. That offset is one constant, converted only inside the adapter. For the 256 px raster style, the tile level equals the normalised zoom. The URL, the saved view, the scale bar, the zoom level in the readout and the tests use the normalised value only.
- Overlays (pin, measure line, accuracy circle, the open card's ring) are drawn once, in a single overlay layer positioned with
adapter.projectand hidden withadapter.isVisiblewhen they are on the far side of a globe. The pin, the measure line, drawn shapes, handles and directions stops are placed throughplacePointandplacePathin core (packages/core/src/globe), described under Flat or globe. - Data layers are the exception, because hundreds of points or a tiled image belong in the engine.
setFeatureLayerdraws points whose colour, size and shape the ui has already worked out,setTileLayerdraws raster or WMS tiles ({bbox-epsg-3857}is filled by MapLibre), requests no tile wholly outside the definition's optionalbounds([west, south, east, north], west less than east; a tile that straddles an edge is still drawn whole), and changes opacity in place,setShapeLayerdraws an affected area, andremoveLayerremoves any of them. They stack tiles, then shapes, then points, above the basemap, may be set before mount, and are drawn again after everystyle.load, because a full style swap drops them. Points are symbols whose images are rasterised inmarkerImages.ts, so squares and triangles carry meaning beside colour. A tap within a fingertip of a point emitsfeatureTapbeforeclick. The planning code is indataLayerPlan.ts, as functions that hold no state and change nothing in the engine (planDataLayer,basemapFont): each turns a kept layer into the source, the engine layers and the ids a tap can land on. The label font is read through a function the adapter passes in, at the moment a plan needs it.DataLayerStoreindataLayerStore.tskeeps the layers, adds the marker and pattern images, and draws, erases and orders what the plans describe. The adapter holds one and stays the owner of the map and of when its style is ready. The store's interface isset,setTiles(which only changes opacity when the tiles are the same),remove,restore(every kept layer again, then one ordering, called fromstyle.load),styleChanged(forgets the label font read from the old style),hitsAtandtapAt. It draws only on the map the adapter hands it throughreadyMap, tells the adapter throughchangedthat a layer was set or removed, and reports a tile layer's source being drawn or erased throughTileSourceRegistry, a hook thatTileLayerTrafficintileLayerTraffic.tsimplements with the tile layers' counters (see "Failures"). It imports only types frommaplibre-gl. - Styled shapes, vector tiles and heatmaps.
setStyledShapesdraws polygons or lines whose look (colour, opacity, hatching, dash and width) the ui has already worked out per shape, and optional label text.setVectorLayerdraws vector tiles whose features the ui never sees, so the port carries a rule (fixed,categoryorstepsover one property) that the adapter compiles to engine expressions, with a zoom window for the layer and for each source layer.setHeatmapLayerdraws point density from loaded points or from a vector source layer. Layer windows are normalised zoom, converted inside the adapter; a source'sminzoomandmaxzoomare tile levels and are passed through. One data layer owns several engine layers (a fill, a hatching layer, outlines per dash, labels), and the adapter keeps their ids so it erases and orders them as a unit. Hatching is a data-drivenfill-patternover images rasterised inpatternImages.ts; dashes cannot be data-driven, so there is one engine layer per dash style, filtered by value. Labels need glyphs, so they are drawn only when the basemap's style has a glyph source and a literal font stack; a raster basemap has neither, and the list, card and legend carry the words there. Stacking, lowest first: tiles, vector tiles, styled shapes, affected areas, heatmaps, points. - Hits and bounds.
featuresAt(point)lists every tappable feature under a pixel, topmost first and once each (points and lines within a fingertip, polygons exactly), andfeatureTapcarries the topmost one together with that list inhits.getBounds()is the box the map shows. Vector tile features and heatmaps are not tappable, and neither are the pixels of a raster tile layer: a tap on one is asked of the layer'sidentifyservice throughLayerSource.identify, not through the engine. - Image export.
toImage(options)returns a PNG blob. The adapter hands the work toMapImageExporterinimageExport.ts, which keeps only the queue of requested exports (below) and reads seven things from the adapter throughMapImageExportHost: the mounted map (none beforemountor afterdestroy), whether a basemap swap is pending, the overlay placement on a given map, the size and view of the map on screen, a signal that aborts when the adapter is destroyed, a style version that changes with the basemap, data layers (a tile layer included, unless only its opacity changed) and projection, and a way to open a render map (below). The exporter asks the host again after each wait, so a swap or adestroythat happens during an export is seen. - Image export, step by step. The exporter does not set
preserveDrawingBuffer, which would cost every frame; it repaints, copies the canvas inside the engine'srenderevent, where the buffer is valid, draws the credit text along the bottom edge, and encodes it. With nosize,pixelRatioorviewit copies the map on screen, requests nothing, and goes on with what has loaded if a tile is stuck forIMAGE_WAIT_MS. It fails with aMapEngineErrorof reasonexport-failed(including a browser that blocks reading the canvas, an adapter that is not mounted or is destroyed during the export, and a basemap swap that is still loading or starts before the pixels are copied). - Image export, a requested size and view.
size(the map's size in CSS pixels, defaulting to the map on screen),pixelRatio(image pixels for each CSS pixel, defaulting to 1 so the result does not depend on the device) andview(aboundsbox, or acenterand normalisedzoom; always north-up, defaulting to where the map on screen looks) are drawn on a render map: a second MapLibre map the adapter builds (RenderMapOpenerinrenderMapOpener.ts) fromgetStyle()of the map on screen, in a hidden, attached container of the requested size (sized through the style object, which the production Content Security Policy allows). MapLibre sizes its canvas asround(ratio * floor(width))from the container, soplanRequestedImagerounds the CSS size to whole pixels first, and the default size is the host'sclientWidthandclientHeight, not the fractional bounding box. The map on screen is only read, so it is not resized or moved and emits no event, and the URL hash does not change. The render map has the same sources and layers and adds no source or origin of its own, but it is a separate map with its own caches: it fetches again the style's tile descriptions, sprite sheets and glyph ranges and the tiles of its view, unless the browser's HTTP cache has them, from the providers the map on screen already uses. The request volume is that of one more map at the requested view; nothing new is sent to anyone, so the privacy position is unchanged.getStyle()leaves out the images added withaddImage, so the adapter copies its own marker and pattern images (names with themapcairn-marker:ormapcairn-pattern:prefix) and sets the app's projection afterstyle.load. It has no interaction, no fade (fadeDuration: 0) and amaxCanvasSizeofMAX_IMAGE_SIDE_PX, since MapLibre would otherwise lower the ratio of a canvas over its default 4096 px. After the new map is built, a box view is checked by comparing the map'sgetBounds()with the box (coversBounds, withinFIT_TOLERANCE_DEGREES, 0.0001): MapLibre keeps its default camera when it cannot fit a box and keeps the camera inside what the projection allows, so a box in a tall, narrow container, or below the basemap's lowest zoom, comes back cropped, and that is refused asinvalid("The view cannot be framed at this size.") instead of saving the wrong place. A box on a globe is refused asinvalidfor now (refuseBoxOnGlobein core, called by the fake and the adapter): the fit runs on the flat camera beforestyle.loadsets the projection, and on a sphere a box can lie beyond what is shown, so no check made at that point can promise the framing; a centre and zoom is drawn on either. When a request names only a size or pixel ratio, the view on screen is used with its latitude clamped to the Web Mercator limit (a globe can look beyond it) and its longitude wrapped. A box across the antimeridian is given in the short form thatboundsOfPointsreturns (the west inside -180 to 180, the east past 180) and the render map is fitted to it as it is: after a fit the engine'sgetBounds()holds the box in the same unwrapped longitudes, socoversBoundscompares them directly. The long form (the west beyond the east) is refused asinvalid. What is still refused: a west outside -180 to 180 (so thegetBounds()of a world-wide view, which reaches beyond -180 or 180, is not an acceptablebounds) and an east more than 360 degrees past the west. A very wide box that passes these can still come backinvalid("The view cannot be framed at this size.") from the framing check, because the engine may have to crop it; the real engine was probed only for boxes up to 20 degrees wide. The exporter waits for the render map'sidleevent, which a map over a sparse tile layer would never fire (a 404 tile asks for no frame), so the adapter paints it everyTILE_SETTLE_NUDGE_MSuntil it does. Unlike the map on screen, which gives up painting when a tile never answers (see "Tile layers that find no tiles"), the render map is painted until it goes idle or the export finishes or times out and removes it. It then copies the canvas as above and removes the map and the container on every path, includingdestroy(), which stops a wait for tiles at once with the not-mounted error. Requested images are drawn one at a time: each waits for the ones asked for before it, so only one extra WebGL context and canvas exist at a time, and a failure does not hold up the next. The queue has no cap and a caller cannot cancel an export in it yet. The size and view are read when an export is asked for and the style when its turn comes, so the adapter counts changes to the basemap, data layers and projection (styleVersion, read when queued and again at the turn): an export that waited while one changed fails withexport-failed("The map changed while the image was waiting.") instead of mixing the new style with the old view and credits. Adestroy()while the pixels are being copied waits for the 3 second frame timer. Credits and marks are drawn atpixelRatioimage pixels to a CSS pixel, and marks are placed with the render map's own camera. A request is checked first byplanRequestedImagein core, which the fake and the adapter both call, before any engine work. A size or ratio that is not a finite number above zero, a view that cannot be drawn (a latitude beyond the Web Mercator limit, a longitude beyond -180 to 180 for a centre or a box's west, or a box whose south is not below its north, whose west is not below its east, or whose east is more than 360 degrees past its west), or an image of under one pixel, is aMapImageExportErrorof kindinvalid. An image overMAX_IMAGE_SIDE_PXon a side orMAX_IMAGE_PIXELSin all, counted in image pixels, istoo-large, and so is a canvas the device could not make at the size asked for. Tiles that have not loaded afterIMAGE_TILES_WAIT_MS(15 seconds) aretimed-out.MapImageExportErrorextendsMapEngineErrorwith reasonexport-failed, so a caller that handles only that still works. Known limits: a second map that cannot start (the likeliest cause is memory pressure, on iOS especially) is anexport-failederror with nokind; a tile that errors (a 404, a 429, a blocked response) still lets the map settle, so the image is saved with a gap and no error, as on screen; and a basemap swap is refused only while it is still loading when the pixels are copied (or when a queued export starts), so one that starts and finishes during the tile wait is not noticed and the image shows the basemap the map had when the export started. The Save image button passes none of these options and is unchanged. - Image export, drawn shapes. Overlays the ui draws itself (the pin, the measure line, the open card's ring) are not in the image, except marks the caller passes as
drawing(positions, two hex colours): the exporter places them with the sameplacePathandplacePointas the overlay (curves, copy of the world and horizon) and strokes them over the copy with a halo, so drawn shapes are saved as they were seen. The scale bar, legend and title are not drawn into an image yet. - Edit handles.
setEditHandlesgives the adapter the points the person may press and drag (id, position, kind: vertex, midpoint or radius). The ui draws them in the overlay; the adapter only owns the gesture, because only the engine can stop a press from also panning the map. The gesture code isEditHandleControllerineditHandles.ts: the adapter holds one, forwards the engine's pointer events to it, and gives it the overlay placement and two callbacks forhandleDragandhandleHover; it holds the handles, the press in progress, the hover and the dropped click, and keeps no state outside the instance. Handles are placed withplacePoint, as the overlay draws them, so a handle beyond the horizon of a globe cannot be pressed and one just across the antimeridian is pressed where it shows. A press within reach of a handle (12 px for a mouse, 22 px for a finger, the nearest wins, chosen bypressHandlein core so both adapters agree) callspreventDefaulton MapLibre'smousedownor one-fingertouchstart, is reported ashandleDrag(start, thenmoveonce the pointer leaves the click tolerance, thenend, withmovedfalse for a tap), and itsclickis dropped.handleHoverreports the handle under a mouse. Handles live on the controller, not in the style, so they survive a basemap swap, andMapViewcancels a pending long-press when a press starts on one. - Flat or globe.
Settings.projection("flat", the default, or"globe") is the one setting for the map's shape. It reaches the adapter as data:MapMountOptions.projectionon mount, andsetProjection(projection)when it changes. The adapter calls the engine'ssetProjection(mercatororglobe) after everystyle.load, so a first mount and every basemap swap keep it, and the app's setting always wins over a style's ownprojection(VersaTiles Colorful asks for a globe). No code branches on a basemap id. Zoom stays the normalised 256 px convention, the address hash is unchanged, and the camera stays north-up with no pitch, so a globe is a different drawing of the same view.isVisible(latlng)is the engine's own horizon test (transform.isLocationOccluded) and is always true on a flat map; on a globeprojectstill returns a pixel for a place on the far side, so every overlay checksisVisibleand leaves out a pin, vertex or handle beyond the horizon.- Cost of the switch. Measured in Chromium with a 4x CPU throttle and software GL, the first switch from flat to globe on a page is one long task of about 165 ms on the world view (about 235 ms with a measure line and the population layer on), almost all of it the engine's first globe frame: building the globe shader programs and drawing the globe's tiles. The adapter asks the engine for the shape once per change (never again on
style.loadunless a style was loading), the React render, the overlay placement andsetProjectionitself are each well under 50 ms, and a second switch on the same page has no long task, so there is nothing of the app's to defer. Switching back to flat takes 50 to 145 ms. A shorter first switch would need a visible busy state or a shader warm-up, which this document does not describe because neither is built. - Placing marks.
placePointandplacePath(core,globe/placement.ts) take aMapPlacement(the shape, the view,projectandisVisible). The engine'sprojectplaces a longitude on the copy of the world it names (190 is one world east of -170) and MapLibre wraps nothing, so a point is drawn on the copy nearest the view centre and every segment of a path goes the short way, across the antimeridian when that is shorter. Positions are only unwrapped for drawing; stored, exported and linked positions keep their own longitudes, and the adapter bringsunprojectand event positions into [-180, 180). A polygon's area is measured with its edges taken the short way too. - Curves. On a globe each segment is cut along its great circle (
densifyAlongGreatCircles), the path the measured distance runs along, into pieces short enough to stay withinGLOBE_CHORD_TOLERANCE_PX(0.5 px) of the arc: a chord of angle θ on a globe of radius R pixels strays at most Rθ²/8, so the step is √(8 · 0.5 / R), with R fromglobeRadiusPixels(MapLibre'sgetGlobeRadiusPixels: 256 · 2^zoom / 2π / cos(centre latitude) in the normalised zoom). That is about 18 degrees at zoom 0, 2.2 at zoom 6 and 0.28 at zoom 12, with at mostMAX_GREAT_CIRCLE_STEPS(1,024) pieces a segment. A piece that goes over the horizon gains a point where it does (12 halvings), so a line stops at the edge of the disc, andvisibleRunssplits a path into the parts in sight, wrapping round a ring's closing edge. A closed shape is filled only while all of its outline is in sight. Edge midpoint handles sit on the great circle on a globe (editHandlesFor(…, projection)), and picking a shape (pickShape) uses the same placement. A flat map draws straight segments, as before. Data layers and the directions route are drawn by the engine and are not curved by the app. - Space around the globe. MapLibre clears the canvas around the sphere to transparent and draws no atmosphere unless a style has a
sky(none of the site's do), so the space is the map region's own background.MapViewrendersdata-projectionon the host from its first render, and on a globe the host and the engine container (packages/adapter-maplibre/src/styles.css.ts) take themapGlobeSpacetoken instead ofmapBackground; a flat map is unchanged. Before the app mounts, the inline theme script also reads the stored map shape (PROJECTION_STORAGE_KEY) and marks the root withdata-map-shape="globe", and the server-rendered placeholder takes the same token under that mark, so a globe started in either theme does not flash the pale ground first. The script's hash inpublic/_headersandconstants/securityHeaders.tschanged with it. - Scale. MapLibre sizes the globe so a feature at the view centre is as large as on the flat map, so the scale bar, which reads the centre, is the same on both. The sphere has one scale, so on a globe
metresPerPixel(lat)returns the centre's resolution for any latitude (mapMetresPerPixel), which sizes the accuracy circle of a fix away from the centre correctly; between normalised zoom 12 and 13, where the engine blends into the flat map, the two differ by under one percent.
- Cost of the switch. Measured in Chromium with a 4x CPU throttle and software GL, the first switch from flat to globe on a page is one long task of about 165 ms on the world view (about 235 ms with a measure line and the population layer on), almost all of it the engine's first globe frame: building the globe shader programs and drawing the globe's tiles. The adapter asks the engine for the shape once per change (never again on
- Engine CSS lives in one file,
packages/adapter-maplibre/src/styles.css.ts. It styles MapLibre only, scopes its rules under the host'sdata-map-hostattribute (anddata-projection), both of whichMapViewsets, hides MapLibre's own controls, replaces fonts and focus rings, and sets the map background from the tokens.MapLibreMapAdapter.tsimports it, so it is compiled into@mapcairn/adapter-maplibre/styles.css, which a host outside this repository imports once. The reference host resolves the package's source and gets the rules through its own vanilla-extract plugin whencreateServices.tsimports the factory, so it does not import the stylesheet.MapView.test.tsxchecks the two attributes where they are set, andbasemap.spec.tschecks in a browser that the engine container has the map background and that no engine control shows, which fails if the styles stop reaching the page. - Loading is lazy. The MapLibre module imports
maplibre-gldynamically the first time the map mounts. The adapter reportsloadingwhile the style, or the style of a requested basemap, is loading, and while the basemap's own sources are not all in (any source whose id does not start withmapcairn:, read from the engine's style when it loads, and each askedisSourceLoadedon every source event, error and frame while the map is busy, so a tile answered with a 404, which fires no event, still ends it; a style with no source of its own is in once the engine goes idle). It reportsloadand settles a waiting mount at the moment they are all in, rather than waiting for the engine's ownloadandidle, which wait for every source, data layers included;idleclears the same state as a final safety. A data layer's tiles never holdloading, because a tile that never answers keeps the engine from going idle for good and would leave the map regionaria-busyfor as long. A feed layer reports its own status, and a tile layer reportstileLayerSlowwhen none of its tiles has loaded forTILE_LAYER_SLOW_MSandtileLayerUnavailablewhen the map settles with none loaded (see "Tile layers that find no tiles"). The first does not wait for the engine to go idle, which a tile that never answers prevents, soloadingis not the place to show a layer's tiles. - User zoom. The adapter emits
userZoomonly for zoom gestures the engine handles (wheel, pinch, double-click), which MapLibre marks with the input event.MapViewadds the zoom keys and exposes both asonUserZoom, so the app announces the settled level after every zoom the person makes and never after one made in code. - Failures. The code is in
failureDetection.ts:FailureDetectionclassifies the engine'serrorevents and owns the counters and timers described here, inbasemapTiles.ts(the basemap's tiles),tileLayerTraffic.ts(each tile layer's),workerFailureCheck.ts(the worker grace check) andrepaintUntilIdle.ts(the painting that lets a map settle). It tells the adapter what it found through a small set of reports (tileError,basemapUnavailable,fatalErrorand the three tile layer reports), and asks the adapter's lifecycle only for the pending mount or swap and to reject it, so the adapter stays the owner of that lifecycle. The busy state isBasemapLoadStateinbasemapLoadState.ts. Tile and source failures aretileError, and the map keeps working: one tile error is never fatal. The adapter counts the tiles of the basemap's own sources (any source whose id does not start withmapcairn:, so data layers do not count; for a hybrid basemap only the imagery, because its labels can load while the imagery is down) from the moment its style loads. If some have failed and none has loaded when the map goes idle, it reportsbasemapUnavailablewith that basemap (the one whose style loaded, captured then, because the report can come before the mount has resolved: MapLibre firesloadand the firstidlein one render), at most once per style load; an expired certificate or a host that is down looks like this. Once any tile of the basemap has loaded, nothing more is reported for that style, because later failures look the same as a patchy connection or a few missing tiles, and leaving a basemap the person can already see would be worse than the general tile error.MapViewpasses the report on asonBasemapUnavailable(basemap), and the host (useBasemapChoice.unavailableNow) marks the basemap unavailable for five minutes (useBasemapAvailability), goes back to the previous basemap or the default (never one already marked), and says so; with nothing left it stays and only says so. A basemap the person chose in this session was saved when its style loaded, so the choice saved before it is put back; a saved or linked basemap the person did not just choose is not rewritten by an outage, only by going back or dismissing the message, which saves the basemap the map went back to. A source-less error before the pending style document has loaded (style.load) is that document failing, and rejects the mount or basemap swap; a sprite or glyph failure comes after it and is atileError. A failed swap puts the last basemap that loaded back, so the map keeps working:MapViewreports it throughonBasemapError, not as an engine error, and the app saves a basemap choice only once it has loaded, then shows "That basemap could not be loaded." with "Use previous basemap". A start that fails to load a basemap other than the default (a saved or linked one whose provider is down) falls back the same way:useMapEnginemounts again when a different basemap is asked for after such a failure, the host (useBasemapChoice.mountFailed) asks for the default and shows the same banner, and going back saves the default so the next start no longer asks for the failed one. A failure of the default itself, or without WebGL, is not about the basemap and keeps its own message. MapLibre reports every workererrorevent with one message, whether the worker never started or threw while running, so after load the adapter waits up to five seconds: if the map goes idle or has everything loaded, it is atileError; otherwisefatalError(reasonstopped), and the app shows "The map stopped working" with Reload, as an alert. A worker error during the first load rejects the mount. A missing WebGL2 context is recognised by MapLibre's exportedGPUInitializationError. - Tile layers that find no tiles. A raster tile data layer is judged by its own tiles, and its failures are not the general
tileError. From the momentsetTileLayerdraws its source (a newtilestemplate, or a basemap swap drawing it again; an opacity change redraws nothing and counts on), the adapter counts the tiles of that source it asks for (sourcedataloading), gives up on (sourcedataabort) and loads (sourcedata). While a tile of the layer has been asked for and not answered, and none has loaded, the adapter also starts a wait ofTILE_LAYER_SLOW_MS(10 seconds) from the first tile asked for; later tiles do not restart it. When it ends with a tile still outstanding, the adapter emitstileLayerSlowwith the same layer id andtilestemplate, once for that drawing and never once any tile of the layer has loaded; it does not wait foridle, so a provider that never answers is reported. The figure is a judgement, not a measurement: long enough that a provider that is merely slow to render a tile is not flagged, and shorter thanTILE_SETTLE_GIVE_UP_MS, which is counted from the last tile asked for and so never ends before it. The painting goes on meanwhile, so a tile answered late with a 404 can still turn the report intotileLayerUnavailable; a layer that has both reported slow first. The optiontileLayerSlowMsoverrides the wait in a test. When the map goes idle with tiles asked for and none loaded, it emitstileLayerUnavailablewith the layer id and thetilestemplate it was drawn from, once for that drawing, and never once any tile of the layer has loaded. A provider that has no tile for what was asked (NASA GIBS for a half hour it has not published answers each with a 404 that carries open CORS headers) raises no engineerror, so a count of failures could not see it; and because that 404 fires no event and asks for no new frame, the map is never painted again and never reportsidle, so while tile layer tiles load the adapter paints the map everyTILE_SETTLE_NUDGE_MSuntil it does. A tile of the basemap's own sources being asked for while the map is busy starts the same painting, so a basemap tile answered with a 404 is seen to be in; it stops atidle, or when the basemap is in and no tile layer has a tile outstanding, so a basemap tile that never answers does not keep the map painting. A tile that never answers keeps the engine from going idle however often the map is painted, and the counts cannot tell it from a 404, so the painting also stops 30 seconds (TILE_SETTLE_GIVE_UP_MS) after the last tile of a tile layer or the basemap was asked for, and starts again when one is asked for later. A layer whose only tile never answers is therefore never reported as unavailable (that report waits foridle), but it is reported as slow, and a 404 that arrives later than that after the last request is not seen until the next pan or zoom. Anerrorevent for a tile layer's source (a failed request, a blocked CORS response) is counted the same way and no longer raises the generaltileError, so the "Check your connection" banner is left to the basemap and the other sources. A tile layer whose tiles partly load, or fail after some loaded, therefore says nothing.MapDataLayerspasses the slow report touseDataLayers.reportTilesSlow(id, tiles), which ignores it unlesstilesis still the layer's current URL and the layer is on, then keeps the layer's status astiles-slowuntil its tiles change, it is turned off, a tile loads or the layer is reported unavailable, and announces "Rainfall: Still waiting for imagery. The provider may be slow or not answering." once, politely and withkeep, because the person turned the layer on and would otherwise see nothing. It passes the unavailable report touseDataLayers.reportTilesUnavailable(id, tiles), which ignores it unlesstilesis still the layer's current URL, then keeps the layer's status astiles-unavailableuntil its tiles change (a control that is in the URL), it is turned off or a tile loads later, and announces it once, politely. After a transient failure (offline, a server error, a rate limit) the tiles can load on a later pan or zoom: the first tile of a layer that has reported (slow, unavailable or both) loads, and the adapter emitstileLayerRecoveredwith the same layer id andtilestemplate, once for each drawing that reported and never for a layer that has not reported.MapDataLayerspasses it touseDataLayers.reportTilesRecovered(id, tiles), which ignores it unless the layer is showing the slow or unavailable status for those tiles, then clears the status and announces "Rainfall: imagery is showing again." once, politely. A date or time control that changes the tiles still clears the status and restarts counting, so a recovery for the old tiles is ignored. Once tiles of a drawing have loaded, the layer says nothing more for it (the existing rule for a layer whose tiles fail after some loaded). The adapter counts afresh, and so can report and recover again, whenever the layer is drawn again: newtiles, or a redraw with the same tiles such as a basemap swap. A redraw with the same tiles keeps a report (slow or unavailable) that had loaded no tile, because the ui still shows it, so the first tile after the redraw ends it; an opacity-onlysetTileLayerdraws nothing again and changes nothing. If the adapter reports the same tiles again after a recovery, the hook shows the status and announces it again, and the next recovery clears it. There is no Try again action: the control is the way to ask for another time, and panning or zooming asks for new tiles. - Referrer for layer tiles. The engine makes the tile requests, so the adapter gives its maps (the one on screen and an export's render map) a
transformRequest,DataLayerTileRequestsindataLayerTileRequests.ts. The data layer store registers the tile URL template of every source it draws that requests tiles (raster and vector, whatever the provider) and drops it when the layer is erased. A request whose URL matches a registered template getsreferrerPolicy: "no-referrer", so a layer's provider never learns which site the visitor is on; every other request, the basemap's included, is left to the page'sReferrer-Policy, because a basemap provider may ask for the site's origin. A placeholder stands for text without/,?,&or#, so a layer's template never matches a basemap URL that differs in path. The policy holds only while MapLibre loads raster tiles withfetch, so neither map setsrefreshExpiredTiles: false, which would load them through an image element that has no referrer policy (a test pins it). Nothing in it names a provider or a layer. - No WebGL means no map. There is no fallback basemap. The app shows a plain message in place of the map ("MapCairn needs WebGL to draw the map.") with advice to try a different browser or turn on hardware acceleration.
MapUnavailabledraws it inside the map region, so the region and the skip link still work, and announces it once, assertively, through the shared announcer rather than being a live region itself. It has no Retry, because mounting again would fail the same way.