Astro content collections
Put a map on every page of an Astro content collection: each entry (a blog post, a project, a trail guide) carries a location, region or route in its frontmatter, and its page builds a map from it. You can also keep whole map documents as collection entries, validated when the site builds.
This page assumes the package is installed (Astro: Install) and that you know how a content collection works.
Quick start
Section titled “Quick start”A collection of posts, each with an optional point location, and a map on every post that has one.
-
Define the collection in
src/content.config.ts:src/content.config.ts import { defineCollection } from "astro:content";import { glob } from "astro/loaders";import { getCollectionItemWithLocationSchema } from "@maplibre-yaml/astro/utils";export const collections = {posts: defineCollection({loader: glob({ pattern: "**/*.md", base: "./src/collections/posts" }),schema: getCollectionItemWithLocationSchema(),}),};The schema has
title,pubDate, optionaldescriptionandupdatedDate, and an optionallocation. -
Give a post a location in its frontmatter, for example
src/collections/posts/paris.md:---title: "My trip to Paris"pubDate: 2024-03-15location:coordinates: [2.3522, 48.8566] # [longitude, latitude]name: "Paris, France"zoom: 12---We arrived in Paris on a crisp spring morning... -
Build the map on each post’s page,
src/pages/posts/[...slug].astro:src/pages/posts/[...slug].astro ---import { getCollection, render } from 'astro:content';import { Map, buildPointMapConfig } from '@maplibre-yaml/astro';export async function getStaticPaths() {const posts = await getCollection('posts');return posts.map((post) => ({ params: { slug: post.id }, props: { post } }));}const { post } = Astro.props;const { Content } = await render(post);const mapConfig = post.data.location? buildPointMapConfig({location: post.data.location,mapStyle: 'https://tiles.openfreemap.org/styles/liberty',}): null;---<html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>{post.data.title}</title></head><body><article><h1>{post.data.title}</h1>{mapConfig && <Map config={mapConfig} height="300px" />}<Content /></article></body></html>
Open /posts/paris/ and you see the post with a map centred on Paris and a
marker labelled with its name. A post without location gets no map.
The builder turns the frontmatter into a full map document at build time.
Every map needs a basemap: pass mapStyle, or a
global configuration as the
builder’s second argument. Without either, the builder throws
ConfigResolutionError (missing required fields: mapStyle) and the build
stops at that page.
The glob() loader works as written on Astro 5, 6 and 7. Astro 4 needs three
changes (Supported versions).
Entries have an id (the file name without its extension) and render with
render() from astro:content; the legacy post.slug and post.render()
are gone in Astro 6.
Common tasks
Section titled “Common tasks”Choose a schema
Section titled “Choose a schema”Each helper builds a whole schema for posts (title, pubDate and so on)
plus one geographic field. Pass your own fields to it as an object:
| Helper | Field | Good for |
|---|---|---|
getCollectionItemWithLocationSchema() | location | One place: a review, a spotlight |
getCollectionItemWithLocationsSchema() | locations | Several places: an itinerary, a city guide |
getCollectionItemWithRegionSchema() | region | An area: a neighbourhood, a coverage area |
getCollectionItemWithRouteSchema() | route | A line: a hike, a road trip |
getCollectionItemWithGeoSchema() | all four | Mixed content |
getCollectionItemWithFeatureRefSchema() | feature_ref | A feature in a GeoJSON file (below) |
import { z } from "astro/zod";import { getCollectionItemWithGeoSchema } from "@maplibre-yaml/astro/utils";
const schema = getCollectionItemWithGeoSchema({ category: z.enum(["travel", "hiking", "food"]), tags: z.array(z.string()).default([]),});The frontmatter for each field:
location: coordinates: [-73.9857, 40.6892] name: "Devoción Coffee" description: "Open from 7am" zoom: 16 markerColor: "#8B4513"locations: - coordinates: [139.6917, 35.6895] name: "Tokyo" description: "Days 1-4" - coordinates: [135.7681, 35.0116] name: "Kyoto" description: "Days 5-7"region: name: "Brooklyn Heights" coordinates: # a polygon: rings of [lng, lat], first point repeated last - [[-73.998, 40.698], [-73.985, 40.698], [-73.985, 40.692], [-73.998, 40.692], [-73.998, 40.698]] fillColor: "#3388ff" fillOpacity: 0.3 strokeColor: "#1d4ed8"route: name: "SF to LA via PCH" coordinates: # at least two [lng, lat] points - [-122.4194, 37.7749] - [-121.8947, 36.6002] - [-118.2437, 34.0522] color: "#e74c3c" width: 4Only coordinates is required. As a guide for zoom: 10–12 shows a city,
13–15 a neighbourhood, 16–18 a building.
Add map fields to an existing schema
Section titled “Add map fields to an existing schema”If your collection already has a schema, add the fields to it instead. Each is optional, so entries without one still validate:
import { defineCollection } from "astro:content";import { z } from "astro/zod";import { glob } from "astro/loaders";import { LocationPointSchema, RegionPolygonSchema, RouteLineSchema,} from "@maplibre-yaml/astro/utils";
const projects = defineCollection({ loader: glob({ pattern: "**/*.md", base: "./src/collections/projects" }), schema: z.object({ title: z.string(), summary: z.string().optional(), location: LocationPointSchema.optional(), // a point region: RegionPolygonSchema.optional(), // a polygon route: RouteLineSchema.optional(), // a line }),});
export const collections = { projects };Use z from astro/zod, so the helpers nest on every Astro major
(why).
Build one map per entry, whatever its geometry
Section titled “Build one map per entry, whatever its geometry”buildMapConfigFromEntry looks at an entry’s fields and calls the right
builder, falling back to a default when the entry has none:
---import { getCollection } from "astro:content";import { Map, buildMapConfigFromEntry } from "@maplibre-yaml/astro";import { globalMapConfig } from "../../lib/map-config";
export async function getStaticPaths() { const entries = await getCollection("projects"); return entries.map((entry) => ({ params: { slug: entry.id }, props: { entry } }));}
const { entry } = Astro.props;const mapConfig = await buildMapConfigFromEntry(entry.data, globalMapConfig, { label: entry.data.title, description: entry.data.summary, fallback: { coordinates: globalMapConfig.defaultCenter!, name: entry.data.title },});---<Map config={mapConfig} height="300px" />globalMapConfig is the site-wide file loaded with loadGlobalMapConfig
(Global configuration); it
supplies the basemap and the defaultCenter used for the fallback.
The first field set wins, in this order: feature_ref, region, route,
locations, location, then options.fallback. The function is async
because feature_ref reads a file. It knows only these field names; if your
collection names them differently, call the builders yourself
(Map builder functions).
GeoJSON feature references
Section titled “GeoJSON feature references”When many entries share geometry from one GeoJSON file, point at the feature instead of copying its coordinates. At build time the file is read, the feature found, and the builder for its geometry type called.
-
Add
feature_refto the schema.getCollectionItemWithFeatureRefSchema()gives you a whole schema that rejects an entry with bothfeature_refand inline geometry. To add it to your own schema:src/content.config.ts import { defineCollection } from "astro:content";import { z } from "astro/zod";import { glob } from "astro/loaders";import { FeatureRefSchema, LocationPointSchema } from "@maplibre-yaml/astro/utils";export const collections = {areas: defineCollection({loader: glob({ pattern: "**/*.md", base: "./src/collections/areas" }),schema: z.object({title: z.string(),feature_ref: FeatureRefSchema.optional(), // either this...location: LocationPointSchema.optional(), // ...or inline geometry}),}),}; -
Reference the feature from the frontmatter, by its top-level
idor by a property value:---title: "Gowanus rezoning area"feature_ref:source: "./src/data/gowanus.geojson"featureId: "area-1"------title: "Gowanus rezoning area"feature_ref:source: "./src/data/gowanus.geojson"match:property: "area_id"equals: 1fillColor: "#3388ff"fillOpacity: 0.25---sourceis a path from the project root. Exactly one feature must match. Frontmattername,descriptionand the style fields override the feature’s own properties. -
Build the map with
buildMapConfigFromEntry, as above, or withbuildFeatureMapConfigto handle feature references yourself.
Feature references are read at build time. With output: 'server',
prerender the pages that use them (Server output).
The file is parsed once and cached; after editing it in astro dev, reload
the page (or add the integration,
which does it for you). The feature reference details
cover geometry types, path rules, errors and file sizes.
Map documents as collection entries
Section titled “Map documents as collection entries”For a site with many maps that should be checked at build time, keep each
map’s YAML file in a collection. A mistake in any file then fails
astro build (and shows in astro dev) instead of appearing as an error card
in the browser. For a handful of maps, YAML files in public/ with
<Map src> are simpler (Astro).
import { defineCollection } from "astro:content";import { glob } from "astro/loaders";import { getMapSchema } from "@maplibre-yaml/astro/utils";
const maps = defineCollection({ loader: glob({ pattern: "**/*.yaml", base: "./src/collections/maps" }), schema: getMapSchema(), // the whole map document: every key a map takes});
export const collections = { maps };Each file in src/collections/maps/ is one map document. Entries can be
JSON or TOML too (pattern: "**/*.{yaml,json,toml}"),
but Astro reads collection files itself, so a mistake is reported with its
field path and no line or column (In Astro):
type: mapid: headquartersconfig: center: [-122.4194, 37.7749] zoom: 15 mapStyle: "https://tiles.openfreemap.org/styles/liberty"layers: - id: office type: circle source: type: geojson data: type: Feature geometry: { type: Point, coordinates: [-122.4194, 37.7749] } properties: { name: "Headquarters" } legend: { label: Headquarters, color: "#3b82f6" } paint: circle-radius: 12 circle-color: "#3b82f6"Show an entry with <Map>:
---import { getEntry } from 'astro:content';import { Map } from '@maplibre-yaml/astro';
const headquarters = await getEntry('maps', 'headquarters');if (!headquarters) throw new Error('maps/headquarters.yaml not found');---<Map config={headquarters.data} height="500px" />A collection entry can use the
GeoJSON shorthands (location:,
locations:, region: and route: on a source), as a map file can:
getMapSchema() expands them into data:, so the entry’s data holds full
GeoJSON. This needs @maplibre-yaml/astro 0.7.1 or later; on 0.7.0 the
entry fails with GeoJSON source requires at least one of: url, data, or
prefetchedData, and you write the GeoJSON in full (data: or url:).
To add fields of your own (a title, a blurb), wrap the schema in
extendSchema(). The example site’s content config does this, next to a
Markdown collection with a point location:
/** Whole map documents as YAML data entries, plus two fields of our own. */const maps = defineCollection({ loader: glob({ pattern: "*.yaml", base: "./src/collections/maps", generateId: stripExtension }), schema: extendSchema(getMapSchema(), { title: z.string(), blurb: z.string(), }),});Hand <Map> only the map document, not your extra fields, or each one
reaches the map as an unknown key and logs a warning:
---import { getCollection } from 'astro:content';import { Map } from '@maplibre-yaml/astro';
const maps = await getCollection('maps');---{maps.map((entry) => { const { title, blurb, ...mapDocument } = entry.data; return ( <section> <h2>{title}</h2> <p>{blurb}</p> <Map config={mapDocument} /> </section> );})}Stories work the same way with getScrollytellingSchema()
(Stories as a content collection).
Reference
Section titled “Reference”Map builder functions
Section titled “Map builder functions”Each builder returns a map document for <Map config>. All take mapStyle
(a style URL or a Protomaps { pmtiles, flavor } basemap), id, and
interactive (default true; false makes a map that can’t be panned or
zoomed, for a purely illustrative map), plus a
global configuration as their
second argument.
import { buildPointMapConfig, buildMultiPointMapConfig, buildPolygonMapConfig, buildRouteMapConfig,} from "@maplibre-yaml/astro";
const MAP_STYLE = "https://tiles.openfreemap.org/styles/liberty";
// A marker, centred. zoom: this option, else location.zoom, else 12.buildPointMapConfig({ location: { coordinates: [-74.006, 40.7128], name: "NYC" }, mapStyle: MAP_STYLE });
// Several markers, framed to fit them.buildMultiPointMapConfig({ locations: [ { coordinates: [-74.006, 40.7128], name: "NYC" }, { coordinates: [-87.6298, 41.8781], name: "Chicago" }, ], mapStyle: MAP_STYLE,});
// A filled polygon.buildPolygonMapConfig({ region: { coordinates: [[[-74.0, 40.7], [-73.9, 40.7], [-73.9, 40.8], [-74.0, 40.8], [-74.0, 40.7]]], name: "Manhattan" }, mapStyle: MAP_STYLE,});
// A line with start and end markers, framed to fit it.buildRouteMapConfig({ route: { coordinates: [[-122.4194, 37.7749], [-118.2437, 34.0522]], name: "California trip" }, mapStyle: MAP_STYLE,});buildMultiPointMapConfig and buildRouteMapConfig also take padding, the
pixels kept between the data and the map edge (default 50; applied from
@maplibre-yaml/astro 0.7.1). buildMultiPolygonMapConfig and
buildMultiLineStringMapConfig take several polygons or lines,
buildFeatureMapConfig a feature reference, and buildMapConfigFromEntry
picks one for you (above).
calculateCenter(coordinates) and calculateBounds(coordinates) return the
centre and the [[west, south], [east, north]] bounds of a list of
[lng, lat] points, for building your own maps.
Feature reference details
Section titled “Feature reference details”| Geometry | Built with |
|---|---|
Point, MultiPoint | buildPointMapConfig, buildMultiPointMapConfig |
LineString, MultiLineString | buildRouteMapConfig, buildMultiLineStringMapConfig (every segment) |
Polygon, MultiPolygon | buildPolygonMapConfig, buildMultiPolygonMapConfig (every polygon) |
GeometryCollection with one member | that member’s builder |
GeometryCollection with several | an error: split it into separate features |
Match. featureId matches the feature’s top-level id (RFC 7946);
match: { property, equals } matches a value in properties (as MapLibre’s
promoteId does). Zero or several matches throw GeoJSONLoadError, naming
the file, its feature count and sample ids or values.
Overrides. name, description and the style fields (markerColor,
fillColor, strokeColor, fillOpacity, color, width, zoom) override
the feature’s properties. A style field that doesn’t fit the geometry (say
markerColor on a polygon) is ignored, with one console warning in
astro dev per file, geometry and set of fields.
Paths. source is resolved from the project root (process.cwd()).
Paths that leave the project with .., symlinks that point outside it, and
absolute paths are refused before anything is read, so frontmatter from an
untrusted source can’t read other files. To change that, pass loadOptions
to buildFeatureMapConfig, buildMapConfigFromEntry or loadFeatureFile:
import type { FeatureLoadOptions } from "@maplibre-yaml/astro";
const loadOptions: FeatureLoadOptions = { projectRoot: "/absolute/path/to/astro/project", // when the build runs elsewhere, as in a monorepo allowAbsolutePaths: true, // only when no frontmatter comes from untrusted content};Errors. InvalidFeatureRefError means the reference has neither or both
of featureId and match. GeoJSONLoadError covers everything else: a
missing file or feature, malformed JSON, an unsupported geometry, a refused
path, a file too large. Its message says what to fix, filePath is the
resolved path, and cause the underlying error.
File size. Up to 50 MB is read as is (with a one-time parse cost above
10 MB), 50–100 MB adds a build warning, and over 100 MB is an error. For data
that large, load it in the browser instead: a PMTiles, FlatGeobuf or
GeoParquet file in public/ is read in parts as the map needs it
(Large data).
Lower level. loadFeatureFile(path) and findFeature(collection, ref)
load a file once and pick features from it yourself; clearFeatureCache()
empties the cache between tests.
Troubleshooting
Section titled “Troubleshooting”Problems every map shares are in Troubleshooting.
- Cannot read properties of undefined (reading ‘get’) and Content
config not loaded in
astro dev: the content config imports from@maplibre-yaml/astro; import from@maplibre-yaml/astro/utils. - missing required fields: mapStyle (
ConfigResolutionError): passmapStyleto the builder or a global configuration as its second argument. - Keys missing from a collection map (no legend, a layer naming a source
that isn’t there): the schema is hand-written; use
getMapSchema(). - A 500 with ENOENT on a server:
feature_refunderoutput: 'server'; prerender the page. - Entry ids end in
.mdon Astro 4: the collection’sbaseis insidesrc/content/(Supported versions).
Alternatives
Section titled “Alternatives”- A few maps, no collection: YAML files in
public/shown with<Map src>(Astro). - Your own component around
<ml-map>: passJSON.stringify(entry.data)as itsconfigattribute (Alternatives).