Interface

Maps

A building block for modules that need a place or a layout, such as a location picker, a plane layout editor, web and mobile viewers with live layers, and the schemas and helpers to store the values.

Maps is something other modules build with. It has no maps of its own, no tables, no routes and no admin pages. A module that needs a place (where an operation is) or a layout (where the bars, stations and seats of a venue are) stores the value in its own table. It edits the value on its own pages with the components Maps ships, and saves it through its own routes, which check access the module's own way.

The package is @frigear-nu/maps. It works with two kinds of value:

  • A location (MapLocation): a point on the earth, with an optional radius or an area around it. It is edited with the location picker on OpenStreetMap-style tiles.
  • A plane layout (PlaneFeatureCollection): a flat drawing in its own units, optionally on an underlay image. It is edited with the plane editor. Each feature has a stable id that other records point to.

Seat maps are layouts only: a seat has an id and a place, never a booking.

What you get

  • Components (auto-imported, they work on props and v-model only):
    • <MapLocationField>, the location picker form field.
    • <MapPlaneEditor>, the plane editor with underlay, grid snapping and allowed feature kinds.
    • <MapViewer>, a read-only viewer for the web, with live layers.
    • <MapMobileViewer>, the same viewer laid out for a mobile screen.
  • Types and schemas: GeoPoint, MapLocation, PlaneFeatureCollection and friends, and their zod schemas from @frigear-nu/maps/schemas.
  • Geometry helpers from @frigear-nu/maps/utils: haversine distance, radius and area checks, centroids and anchors, bounds.
  • Registries: extendMaps(nuxt, { kinds, layers }) for feature kinds (seat, station, container) and live layers.
  • Server utils (auto-imported): validatePlaneLayout, and storeMapUnderlay, serveMapUnderlay and deleteMapUnderlay for underlay images in NuxtHub Blob.
ServerClientMobile
Installed for you: UI, Module Kit, Leaflet and leaflet-geoman. You add:NuxtHub with Blob storage, when a module stores underlay images.

Quick setup

Install Maps

pnpm add @frigear-nu/maps

Most apps get Maps through a module that uses it, such as Operations.

Add it to nuxt.config.ts

nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@nuxthub/core', '@frigear-nu/maps'],
  hub: { blob: true },
  maps: {
    tiles: {
      url: 'https://tiles.example.com/{z}/{x}/{y}.png',
      attribution: '&copy; OpenStreetMap contributors',
    },
  },
})
What you should see:<MapLocationField v-model="location" /> on any page shows a map you can tap to place a point.

Options

Options go under the maps key.

OptionTypeDefaultPurpose
tiles.urlstringOpenStreetMap's tilesThe tile URL template of the picker and geographic viewers.
tiles.attributionstringOpenStreetMap's attributionThe attribution shown on geographic maps.
tiles.maxZoomnumber19The deepest zoom of the tiles.
defaultCenter{ center: [lat, lng], zoom }none: a world view ([0, 0], zoom 2)Where the picker and viewers open without a value. The app sets it to its own area.
maxUnderlayBytesnumber10 MBThe largest image storeMapUnderlay accepts.
kinds, layerslists[]The host's own feature kinds and live layers, the same as extendMaps.

tiles. The default is OpenStreetMap's public tile server. Its tile usage policy forbids heavy use, such as a festival where thousands of phones open the site map at once. Use a hosted tile provider, or tiles you serve yourself, in production. Keep the provider's attribution.

Storing a value

A module stores a location or a layout in a JSON column of its own table. Maps exports the types; the module types the column with them, in both dialects.

server/db/schema.sqlite.ts
import { sqliteTable, text } from 'drizzle-orm/sqlite-core'
import type { MapLocation, PlaneFeatureCollection } from '@frigear-nu/maps/utils'

export const venues = sqliteTable('venues', {
  id: text().primaryKey(),
  location: text({ mode: 'json' }).$type<MapLocation>(),
  layout: text({ mode: 'json' }).$type<PlaneFeatureCollection>(),
})
server/db/schema.postgresql.ts
import { jsonb, pgTable, text } from 'drizzle-orm/pg-core'
import type { MapLocation, PlaneFeatureCollection } from '@frigear-nu/maps/utils'

export const venues = pgTable('venues', {
  id: text().primaryKey(),
  location: jsonb().$type<MapLocation>(),
  layout: jsonb().$type<PlaneFeatureCollection>(),
})

Maps ships no column helper on purpose. registerDatabaseTable copies a schema file's columns into the app's generated schema as text, with the file's named imports. A helper call such as mapColumn() survives that copy, but its import then has to resolve from the app's root. In a pnpm app, a package that only came in through another module does not resolve there, so the app's database build would fail. The plain column above has no such import, only types.

Validate what a client sends with the schemas, in the route that saves it:

server/routes/admin/venue.patch.ts
import { z } from 'zod'
import { mapLocationSchema } from '@frigear-nu/maps/schemas'
import { validationError } from '@frigear-nu/module-kit/server'

export default defineEventHandler(async (event) => {
  await authorize(event, venuesAccess.permissions.manage)
  const body = await readValidatedBody(event, z.object({ location: mapLocationSchema.nullable(), layout: z.unknown() }).parse)
  const layout = validatePlaneLayout(body.layout, { kinds: ['venues.bar', 'maps.area'] })
  if (!layout.success) throw validationError(layout.issues)
  // ... load the venue, authorize again with it (venuesAccess.permissions.manage, venue),
  // then save body.location and layout.data on it
})
Schema (@frigear-nu/maps/schemas)What it accepts
geoPointSchema{ lat, lng } within -90..90 and -180..180.
mapLocationSchema{ point, radiusMeters? } or { point, area }: a radius up to 50 km, or an area of 3 to 500 corners. Never both.
planeGeometrySchemaA Point, LineString or Polygon in plane units. An open polygon ring is closed.
planeFeatureCollectionSchema({ kinds?, maxFeatures? })A layout. Feature ids are unique and safe, and the kinds are among kinds. 2000 features by default.
planeLayoutSchemaThe same with no options.
planeGeoreferenceSchema{ origin, rotation, metersPerUnit }: the rotation is normalised to -180..180, the scale is 0.001 to 1000 m per unit.
planePlacementSchemaA PlanePlacement (see On the map). Map tiles and a metre grid need the georeference.

validatePlaneLayout(value, options) runs planeFeatureCollectionSchema and checks each feature against the registry. The kind must be registered and the geometry one the kind may have. The properties are parsed with the kind's zod schema. It returns the cleaned layout, or the issues with paths such as features.3.properties.capacity.

A location field

pages/admin/venues/[id].vue
<script setup lang="ts">
import type { MapLocation } from '@frigear-nu/maps/utils'

const location = ref<MapLocation | null>(venue.value.location)
</script>

<template>
  <UFormField name="location" :label="t('location', 'Location')">
    <MapLocationField v-model="location" :modes="['point', 'radius']" />
  </UFormField>
</template>
PropDefaultWhat it does
v-modelnullThe MapLocation, or null.
modes['point', 'radius', 'area']The kinds of location offered.
defaultRadius100The radius a new circle starts with, in metres.
height20remThe map's height.
disabledfalseShows the value without handles.

Tap the map to place the point, and drag the pin to move it. A radius is set in metres under the map. An area is drawn corner by corner, and its corners can be dragged afterwards. With an area, point is the area's centroid.

A plane editor

<script setup lang="ts">
import type { PlaneFeatureCollection, PlaneUnderlay } from '@frigear-nu/maps/utils'

const layout = ref<PlaneFeatureCollection>(venue.value.layout ?? { type: 'FeatureCollection', features: [] })

async function upload(file: File) {
  const body = new FormData()
  body.append('file', file)
  return await $fetch<PlaneUnderlay>(`/api/admin/venues/${venue.value.id}/layout/underlay`, { method: 'POST', body })
}
</script>

<template>
  <MapPlaneEditor v-model="layout" :kinds="['venues.bar', 'maps.area', 'maps.label']" :upload="upload" />
</template>
PropDefaultWhat it does
v-modelan empty layoutThe PlaneFeatureCollection.
kindsevery registered kindThe feature kinds that may be drawn. The drawing tools follow their geometries.
uploadnone(file) => Promise<PlaneUnderlay>. Without it, the underlay cannot be changed in the editor.
grid10The grid to snap to, in plane units; 0 turns snapping off.
height32remThe canvas height.
disabledfalseShows the layout read-only.
  • Feature ids. The editor gives every new feature an id (ftr_..., from newFeatureId()). The id never changes, so other records can point to a feature, such as a shift's featureId. Deleting a feature asks first, because those records lose their place. It works on a plain-http origin too (a phone testing against http://192.168.x.x:3000), where the browser has no crypto.randomUUID.
  • Properties. The side panel shows a form generated from the kind's zod schema, and flags what the schema refuses. The form supports strings, numbers, booleans, enums, .optional(), .default() and translated texts (translatedProperty). Labels and help come from .meta({ label, help }).
  • Underlay. One plane unit is one pixel of the image, placed at the origin. Store the image with storeMapUnderlay(event, { prefix }). It accepts a PNG, JPEG or WebP (by its bytes) up to maxUnderlayBytes and at most MAX_UNDERLAY_DIMENSION (100 000) pixels each way, which a layout can store (400 image_too_large above), and answers { pathname, contentType, width, height }. Keep the pathname on your record and serve it from your own route with serveMapUnderlay(event, stored, { cache }). The url you return points at that route.
  • Underlay URL. A layout's underlay.url must be a path on this app (/api/..., see isSameAppPath): the schemas and validatePlaneLayout refuse an external URL (https://..., //host/..., data:), and the viewers do not load one, so a stored layout can never show a third party's image or leak the viewers' addresses to it.
  • After an upload the plane takes the image's size as its extent (withPlaneUnderlay), so an older extent never clips the new image, and the editor fits the view to it.

On the map

A layout lies on the earth in one of two ways.

  • A placed plane. The layout keeps its plane units and its grid, and a PlanePlacement says where it lies: plane [0, 0] is at georeference.origin, its +y axis points rotation degrees clockwise from north, and one unit is metersPerUnit metres (with a floor plan image, metres per pixel). Store the placement apart from the layout, in a JSON column of its own, and save it with its own route: moving the plan and drawing on it never overwrite each other.
  • A geo layout. crs: 'geo' on the layout: its positions are [lng, lat], drawn directly on the map tiles. It has no extent, image or placement.
type PlanePlacement = {
  georeference?: { origin: GeoPoint, rotation: number, metersPerUnit: number } | null
  underlayMode?: 'none' | 'tiles' | 'image' | null // one underlay at a time
  underlayOpacity?: number | null // 0.1 to 1
  gridUnit?: 'plane' | 'metres' | null // metres once placed
  gridSize?: number | null // 0.5 or 1 in metres
}
<MapPlaneEditor
  v-model="layout"
  v-model:placement="placement"
  :location="venue.location"
  :kinds="['venues.bar', 'maps.area']"
  :upload="upload"
  allow-geo
>
  <template #no-location>
    <UEmpty title="This venue has no location yet" :actions="[{ label: 'Set the location', to: detailsLink }]" />
  </template>
</MapPlaneEditor>
PropDefaultWhat it does
v-model:placementunboundThe PlanePlacement. Bound, the panel offers Place on map, the underlay picker and the metre grid.
locationnoneThe site (MapLocation). Every map view opens on it and shows it, dashed, while staff place or draw.
allow-geofalseAn empty layout offers "Draw on a plane" or "Draw on the map"; a placed plane can be converted to a geo layout (one way, after a confirm).
#no-location slotan empty stateShown instead of the map when a map view has nothing to open on: no location, no placement and no drawn geo features. A map view never opens on a blank world view.
  • Placing. Place on map puts the plane over the tiles, centred on the location and scaled to the site's size. A middle handle moves it, a handle above it turns it, and a corner handle scales it; the floor plan image turns with it. The panel has the same values as numbers (latitude, longitude, turn in degrees, metres per unit) and the plan's size in metres. Remove placement turns the map tiles underlay and the metre grid off; the features stay on the plane.
  • Underlay. One at a time: none, the map tiles (needs the placement) or the floor plan image, with an opacity slider. With the tiles, the editor draws on the map and turns every position back into plane units through the placement before it snaps, so the grid stays the plane's.
  • Metres. Once placed, the grid can snap to 0.5 m or 1 m on the ground (gridUnit: 'metres'), converted to plane units through the scale. A selected line shows its length, an area its width and height, in metres.

Validate a placement in its route with planePlacementSchema. The helpers are pure (@frigear-nu/maps/utils):

HelperWhat it does
planeToGeo(position, georeference), geoToPlane(position, georeference)A plane position as [lng, lat] and back.
geometryToGeo, geometryToPlane, layoutToGeo(layout, placement)The same for a geometry, and a placed plane as a geo layout.
initialGeoreference(extent, center, spanMeters), placeGeoreference(extent, center, rotation, metersPerUnit)A placement centred on a point.
extentCorners(extent, georeference), placedCenter(layout, georeference)Where the plane's corners and centre lie.
underlayModeOf(layout, placement), underlayOpacityOf(placement), gridOf(placement, planeGrid)What is under the plane, how opaque, and the grid in plane units.
isPlacedLayout(layout, placement), canvasBase(layout, placement)Whether a layout can be drawn on a geographic map, and whether a viewer is a plane or a map.

Feature kinds

A feature kind is what can be drawn: its geometry, its properties form, an icon and a colour. Maps registers maps.marker (point), maps.line, maps.area (polygon) and maps.label (a text). Modules add their own from setup():

src/module.ts
import { defineMapFeatureKind, extendMaps } from '@frigear-nu/maps/utils'

extendMaps(nuxt, {
  kinds: [defineMapFeatureKind({
    id: 'seating.seat',
    label: { da: 'Sæde', en: 'Seat' },
    icon: 'i-lucide-armchair',
    geometry: 'Point',
    color: 'success',
    properties: resolver.resolve('./runtime/maps/seat'),
  })],
})
src/runtime/maps/seat.ts
import { z } from 'zod'

export default z.object({
  row: z.string().max(8).meta({ label: { da: 'Række', en: 'Row' } }),
  number: z.number().int().min(1).meta({ label: { da: 'Nummer', en: 'Number' } }),
})
  • The properties file default-exports a zod object. It is bundled into the browser (the editor's form) and into the server (validatePlaneLayout), so it imports only zod and @frigear-nu/maps/properties.
  • component (optional) is a Vue component shown in the viewers' details of a feature of the kind, with feature (the MapSelection) as its prop.
  • Ids are prefixed with the module. A later registration with the same id replaces an earlier one, so a host can override a module's kind from its maps.kinds option. An invalid registration fails the build.

Live layers

A live layer is drawn over a viewer from a module's own route, refreshed while the viewer is open. Nothing is stored.

src/module.ts
extendMaps(nuxt, {
  layers: [defineMapLayer({
    id: 'shifts.on-duty',
    label: { da: 'På vagt nu', en: 'On duty now' },
    appliesTo: 'operations.venue-layout',
    endpoint: '/api/shifts/operations/:operationId/on-duty',
    refreshInterval: 120,
    permission: 'shifts:read',
  })],
})
FieldWhat it is
id, labelThe layer, shown in the viewer's toggles.
appliesToOne or more surface names. A viewer with that surface draws the layer. The module that shows the viewer names its surface (operations.venue-layout).
endpointThe route that returns the GeoJSON, with :params. The viewer fills them from its params prop and skips the layer when one is missing.
refreshIntervalSeconds between fetches, at least 5.
permissionThe permission the route checks. The route enforces it; the viewer hides a layer whose route answers 401 or 403.
visible, colorShown when the viewer opens (default true); the colour of its markers (default info). A layer with visible: false starts hidden in the viewers and is fetched only once someone shows it.

The route returns a MapLiveFeatureCollection, in the units of the surface (plane units on a layout). A feature's properties.label (or name) shows in its popup, and a numeric properties.count on its marker. Features with a geometry that is not valid are dropped.

Viewers

<!-- web -->
<MapViewer :layout="operation.venueLayout" surface="operations.venue-layout" :params="{ operationId: operation.id }" />

<!-- a mobile screen -->
<MapMobileViewer :layout="operation.venueLayout" surface="operations.venue-layout" :params="{ operationId: operation.id }" />

<!-- the site map, with the venue layout over it -->
<MapViewer
  :locations="[{ id: operation.id, location: operation.location }]"
  :overlays="[{ id: 'venue', layout, placement, label: 'Venue layout', surface: 'operations.venue-layout', params: { operationId: operation.id } }]"
/>
PropWhat it does
layoutA layout to show: a plane, or a geo layout on the map.
placementThe plane layout's PlanePlacement: its underlay and opacity, and with underlayMode: 'tiles' the plane is shown on the map tiles.
locationsGeographic locations to show on a map: { id, location, label?, color? }[].
overlaysLayouts drawn over a geographic map: { id, layout, placement?, label?, opacity?, image?, surface?, params? }[]. A placed plane is drawn through its placement (with its floor plan image when its underlay is the image), a geo layout as it is, and a plane without a placement is skipped. Each gets a toggle.
surface, params, liveLayersThe live layers to draw: those of the surface, with these endpoint params, narrowed to these ids.
focusA feature or location id to focus when the map opens.
heightThe map's height. <MapMobileViewer> fills the page without it.

The map refits when what it shows moves elsewhere (another layout's extent, other locations, overlays), and switches between a plane and a geographic map when layout or its placement changes that (canvasBase). Without a surface of its own, a geographic viewer draws the live layers of the first overlay with a surface, placed through that overlay's placement: the site map shows who is on duty on the venue layout to readers the layer's route allows. A live layer's answers for older params are dropped once the params change, so a slow answer never replaces the current one.

Both emit select with a MapSelection ({ source, id, label, kind?, layer?, overlay?, properties }) or null. <MapViewer> shows the selection under the map, with toggles for the live layers. <MapMobileViewer> follows the Mobile screens. The map fills the space the page gives it, the layer and recentre buttons float over it as large touch targets, and the selection opens in a bottom sheet above the tab bar. Leaflet loads in the browser only; the server renders the frame and a skeleton.

Geometry helpers

From @frigear-nu/maps/utils, pure and usable on the server, in the app and in tests:

HelperWhat it does
haversineMeters(a, b)The great-circle distance between two GeoPoints.
isWithinRadius(point, center, meters)Whether a point is within a radius.
isInsideArea(point, corners), isInLocation(point, location, tolerance?)Whether a point is in an area, or in a location of any kind.
areaCentroid(corners), geoBounds(points), locationBounds(location)The centroid of an area, and bounds as [[south, west], [north, east]].
geometryAnchor(geometry)The point to draw a plane feature at: a point, a line's middle, a polygon's centroid.
geometryBounds(geometries), planeExtentOf(layout)Bounds in plane units, and a layout's extent.
withPlaneUnderlay(layout, underlay)The layout with a new underlay, its extent set to the image's size.
isSameAppPath(url)Whether a URL is a path on this app, the only underlay URL a layout may hold.
newFeatureId(prefix?)A new feature id (ftr_ and 20 hex digits).
validateGeometry(value, allowed?), snapGeometry(geometry, size)Checks and snaps a plane geometry.

Translations

Override any string in your app's i18n/locales/<code>.json, under the maps key. Maps ships Danish and English.

Next steps

  • Operations – the location and venue layout of an operation, edited with these components.
  • Shifts – the on-duty live layer and shift locations on the venue layout.
Copyright © 2026