Ga naar hoofdinhoud

CnMapWidget

Leaflet-backed map primitive for declarative manifest-driven maps. Renders a configurable layer stack (tile / WMS / WFS / inline GeoJSON) plus an optional marker set sourced from inline features OR an HTTP dataSource.url. Marker clustering is opt-in (lazy-loads leaflet.markercluster only when first toggled). Spec: REQ-MMW-* (manifest-map-widget).

Try it​

Loading CnMapWidget playground…

Usage​

<!-- Standalone — embed a map inside a custom component -->
<CnMapWidget
:center="[52.1326, 5.2913]"
:zoom="7"
:layers="[
{ type: 'tile',
url: 'https://service.pdok.nl/brt/achtergrondkaart/wmts/v2_0/standaard/EPSG:3857/{z}/{x}/{y}.png',
options: { attribution: '© Kadaster', maxZoom: 19 } },
{ type: 'wms',
url: 'https://service.pdok.nl/lv/bag/wms/v2_0',
options: { layers: 'pand', transparent: true, opacity: 0.6 } },
]"
:markers="{
dataSource: { url: '/index.php/apps/procest/api/cases/geo' },
latField: 'lat',
lngField: 'lng',
popupField: 'title',
clustering: true,
}"
height="500px"
@marker-click="onMarkerClick" />

The layers[] array dispatches by type:

layer.typeLeaflet factory
tileL.tileLayer(url, options)
wmsL.tileLayer.wms(url, options)
wfsfetch(url) → L.geoJSON(features, options)
geojsoninline data → L.geoJSON; OR fetched URL
image{ url, width, height } → L.imageOverlay on flat pixel coordinates (see below)

Unknown types log a warning and are skipped — manifests stay forward-compatible.

Image maps​

Not every map is the earth: a game world, a floor plan or a terrain drawing is a picture with places on it. A layer { "type": "image", "url": "/img/valley.png", "width": 2400, "height": 1600 } turns the map into a picture in flat pixel coordinates: (0, 0) is the picture's top left, x runs right and y runs down. The whole picture is fitted on open, a drag cannot move it far out of view (the bounds are padded by 10 percent), and zoom runs from fitting the picture to four times its native size. The url goes through safeHref; the browser loads it as an image and the widget fetches nothing. A map is either a picture or the earth: any other layer beside an image layer is skipped with a warning, and one image layer per map.

  • Markers read markers.xField and markers.yField (default x and y) from their rows and stay on the same spot of the picture at every zoom. A row without both numbers is not plotted and is counted in a note under the map.
  • click carries { x, y }, rounded to whole pixels and clamped to the picture, instead of { lat, lng }: the click position for an "add pin here" form. A geographic map keeps emitting { lat, lng }.
  • Fit all markers fits the whole picture, and autoFit does not run.
{
"layers": [{ "type": "image", "url": "/img/valley.png", "width": 2400, "height": 1600 }],
"markers": { "xField": "x", "yField": "y", "popupField": "name", "dataSource": { "register": "larp", "schema": "place" } }
}

Base maps and the layer switcher​

basemaps declares the switchable background map(s). The first entry is live on load; when more than one is given, a Leaflet layer switcher appears in the top-right corner:

<CnMapWidget
:center="[52.1326, 5.2913]"
:basemaps="[
{ name: 'Standard',
url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
attribution: '© OpenStreetMap contributors' },
{ name: 'Terrain',
url: 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png',
attribution: '© OpenStreetMap contributors, SRTM | © OpenTopoMap' },
]" />

Use basemaps instead of a tile entry in layers for the background — layers is then free to carry only overlays (WMS / WFS / GeoJSON). basemaps is empty by default, so consumers that already declare their background through layers are unaffected.

Base map tiles are <img> loads from a third-party host. A hardened Content-Security-Policy (img-src) may block hosts other than the one already allowed — verify before shipping a new basemap.

Controls​

Beyond Leaflet's own zoom and attribution controls, the widget mounts a control bar (top-left). Each button is individually switchable:

PropDefaultButton
fitControltrueFit all markers — re-centres and re-zooms to the full marker bounds, i.e. back to the frame the map opens at with autoFit.
locateControltrueShow my location — browser geolocation; warns (never throws) when denied or on an insecure origin.
fullscreenControltrueToggle fullscreen — a CSS overlay, so no Fullscreen-API permission prompt.

zoomControl (default true) switches Leaflet's own zoom in and zoom out buttons; turn it off for a small preview map that only shows where something is.

fitToMarkers() is also callable directly through a template ref:

<CnMapWidget ref="map" ... />
<!-- this.$refs.map.fitToMarkers() -->

autoFit and the user's view​

autoFit (default true) frames the map on every marker it is given — on load, and again whenever the marker set changes, so a consumer that narrows its markers with a filter re-frames on the result.

It stops at the first pan or zoom the visitor makes. From then on their framing is kept and the markers reload underneath it, because a map that jumps back to the whole country on every refresh cannot be read. Fit all markers is how they ask for the full frame again, and fitToMarkers() still works at any time.

Sizing​

height accepts any CSS length (default 500px). Pass height="100%" to fill a flex parent — the widget watches its own box with a ResizeObserver and re-flows Leaflet whenever it changes, so a map that grows, or that mounts while hidden behind a view toggle, still lays its tiles and markers out correctly.

Markers​

Pick one of:

  • markers.features — inline GeoJSON Feature[] (static maps).
  • markers.dataSource.url — fetched on mount; the response may be a GeoJSON FeatureCollection OR a flat array of rows (in which case latField, lngField, popupField drive the conversion).
  • markers.dataSource.{register, schema, filter?, limit?} — plots the objects of an OpenRegister schema. filter takes the shared tokens, so a record's page plots the objects that point at it ({ "case": "@objectId" }, read from the objectId and objectData props the detail host binds). An object at (0, 0) is not plotted: that is where an unset pair of numbers lands.

A record's places​

On a detail page the map can say why it shows no markers, and read them again when the app saves one:

{
"type": "map",
"content": {
"markers": {
"dataSource": { "register": "myapp", "schema": "location", "filter": { "item": "@objectId" } },
"latField": "latitude",
"lngField": "longitude",
"popupField": "label"
},
"height": "260px",
"ariaLabel": "Locations on this item",
"emptyText": "No locations linked to this item yet",
"errorText": "The locations could not be loaded.",
"refreshOn": "myapp:location:saved",
"refreshMatch": "itemId"
}
}
KeyMeaning
emptyTextA line under the map when the source answered no markers. Without it an empty map says nothing.
headerSubtitleThe line under the card title with the number of places: { "one": "{total} location", "other": "{total} locations" } or one string, through the app's translate ("1 locatie", the case "Locaties" card). Shown once the source answered with markers.
errorTextThe line, announced as an alert, when the source could not be read. Defaults to "The places could not be loaded."
refreshOnAn event-bus event that reads the markers again.
refreshMatchOnly when the event payload's field with this name holds the record's id.
ariaLabelThe map's accessible name, through the app's translate.

The objectId prop is the record's id and objectData the record, for the filter tokens.

markers.clustering: true (or the widget-level clustering prop) opts in to leaflet.markercluster. The cluster bundle lazy-loads only when first enabled — consumers without clustering pay zero extra bytes.

Legend​

Render a custom legend overlay via the #legend slot. It is positioned absolute (top-right) by default; consumers may override with their own container. Scoped props: { layers, markers }.

<CnMapWidget :layers="layers" :markers="markers">
<template #legend="{ layers }">
<ul class="my-legend">
<li v-for="layer in layers" :key="layer.type">{{ layer.type }}</li>
</ul>
</template>
</CnMapWidget>

Manifest mounting​

Don't mount this component directly from a manifest. Use CnMapPage (the type: "map" page renderer) which wraps this primitive with a header, filter slot, and event pass-through.

Fallback​

When Leaflet cannot be loaded (test envs, CSP-blocked CDNs), the #fallback slot renders instead. Default text uses unavailableLabel.

<CnMapWidget :center="[52, 5]">
<template #fallback>
<p>Map view unavailable.</p>
</template>
</CnMapWidget>

Reference​

OpenRegister reliance​

medium: this component relies on OpenRegister for part of what it does. 3 direct references, 2 files reached through imports.

See the reliance overview for the filterable list.

Props​

NameTypeRequiredDefaultDescription
center[number, number][52.13, 5.29]Initial map center as [latitude, longitude]. Optional: on a dashboard the centre arrives via content.center (see the cfg computed), and when neither source supplies a valid pair it defaults to [52.13, 5.29] (the Netherlands).
zoomnumber7Initial zoom level.
layersArray<object>[]Layer definitions. Each entry: { type: 'tile'|'wms'|'wfs'|'geojson'|'image', url, options }. geojson MAY supply inline data (FeatureCollection) instead of url. image is { type: 'image', url, width, height }: the map becomes a picture in flat pixel coordinates ((0, 0) top left); other layers beside it are skipped. Unknown types log a console.warn and are skipped.
markersunionnullMarker config. { features?, dataSource?, latField?, lngField?, xField?, yField?, popupField?, clustering?, iconColor?, iconUrl?, centerMarker? }. On an image map (a layer of type image) markers read xField / yField (default x / y, pixels from the picture's top left) instead of latField / lngField. features[] is inline; dataSource.url is HTTP-fetched on mount; dataSource.{register, schema} plots the objects of an OpenRegister register/schema via their @self.geo. centerMarker: true adds an extra pin at the map's center, alongside any source markers.
clusteringbooleanfalseEnable marker clustering. When true, lazy-loads leaflet.markercluster on first mount. markers.clustering overrides this prop when set.
heightunion'500px'Container height. Forwarded to the wrapper div's style.height.
autoFitbooleantrueFrame the map on every loaded feature. Applies on load and on each marker update until the user pans or zooms themselves, after which their view is kept and only the Fit all markers control re-frames.
fitControlbooleantrueShow the "fit all markers" control — re-centres and re-zooms the map so every marker is back in view (the position the map opens at).
zoomControlbooleantrueShow Leaflet's zoom in and zoom out buttons. Off for a small preview map that only shows where something is.
fullscreenControlbooleantrueShow the fullscreen toggle. Expands the widget to fill the viewport via a CSS overlay, so it needs no Fullscreen-API permission prompt.
locateControlbooleantrueShow the "locate me" control, which centres the map on the visitor's own position via the browser geolocation API. Warns (does not throw) if denied.
basemapsArray<object>[]Switchable base maps: [{ name, url, attribution, options }]. The first entry is active on load and a layer switcher appears when more than one is given. Supply these INSTEAD of a tile entry in layers for the background map. Empty by default, so consumers that declare their background through layers are unaffected.
ariaLabelstring() =&gt; t('nextcloud-vue', 'Map')Aria-label for the map application region.
unavailableLabelstring() =&gt; t('nextcloud-vue', 'Map library not available')Label shown when Leaflet is not available.
contentunionnullDashboard content blob. When this widget is placed on a dashboard, the grid stores its config here and each key (center, zoom, markers, clustering, height, autoFit, layers, basemaps) overrides the matching flat prop. Direct (non-dashboard) consumers omit this and pass the flat props instead. See the cfg computed for the merge rules. labelsBelow: true writes the markers' popupField values on a line under the map ("Fietspad Lindelaan, tussen nummer 2 en 40").
placementunionnullDashboard placement record. Declared so the grid's :placement binding is consumed as a prop instead of leaking onto the root element; unused here.
objectIdunion''The record of the page the map sits on: @objectId and @object.&lt;field&gt; in markers.dataSource.filter resolve against it, so a record's page can plot only the objects that point at it.
objectDataunionnullThe loaded record, for @object.&lt;field&gt; filter tokens.

Events​

NamePayloadDescription
map-ready—Map ready event. Fired once after Leaflet has loaded and the map is mounted.
marker-click—Marker click event. Fired when a marker is clicked.
bounds-change—Viewport bounds change event. Fired (debounced) after pan / zoom settles.
click—Map background click event. Fired when the user clicks the map outside any marker.
header—The card header's note at the right of the title.

Slots​

NameBindingsDescription
fallback—fallback
legendlayers, markerslegend