Skip to content

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.

A collection of posts, each with an optional point location, and a map on every post that has one.

  1. 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, optional description and updatedDate, and an optional location.

  2. Give a post a location in its frontmatter, for example src/collections/posts/paris.md:

    ---
    title: "My trip to Paris"
    pubDate: 2024-03-15
    location:
    coordinates: [2.3522, 48.8566] # [longitude, latitude]
    name: "Paris, France"
    zoom: 12
    ---
    We arrived in Paris on a crisp spring morning...
  3. 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.

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:

HelperFieldGood for
getCollectionItemWithLocationSchema()locationOne place: a review, a spotlight
getCollectionItemWithLocationsSchema()locationsSeveral places: an itinerary, a city guide
getCollectionItemWithRegionSchema()regionAn area: a neighbourhood, a coverage area
getCollectionItemWithRouteSchema()routeA line: a hike, a road trip
getCollectionItemWithGeoSchema()all fourMixed content
getCollectionItemWithFeatureRefSchema()feature_refA 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"

Only coordinates is required. As a guide for zoom: 10–12 shows a city, 13–15 a neighbourhood, 16–18 a building.

If your collection already has a schema, add the fields to it instead. Each is optional, so entries without one still validate:

src/content.config.ts
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:

src/pages/projects/[slug].astro
---
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).

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.

  1. Add feature_ref to the schema. getCollectionItemWithFeatureRefSchema() gives you a whole schema that rejects an entry with both feature_ref and 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
    }),
    }),
    };
  2. Reference the feature from the frontmatter, by its top-level id or by a property value:

    ---
    title: "Gowanus rezoning area"
    feature_ref:
    source: "./src/data/gowanus.geojson"
    featureId: "area-1"
    ---

    source is a path from the project root. Exactly one feature must match. Frontmatter name, description and the style fields override the feature’s own properties.

  3. Build the map with buildMapConfigFromEntry, as above, or with buildFeatureMapConfig to 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.

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).

src/content.config.ts
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):

src/collections/maps/headquarters.yaml
type: map
id: headquarters
config:
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:

examples/astro/site/src/content.config.ts
/** 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).

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.

GeometryBuilt with
Point, MultiPointbuildPointMapConfig, buildMultiPointMapConfig
LineString, MultiLineStringbuildRouteMapConfig, buildMultiLineStringMapConfig (every segment)
Polygon, MultiPolygonbuildPolygonMapConfig, buildMultiPolygonMapConfig (every polygon)
GeometryCollection with one memberthat member’s builder
GeometryCollection with severalan 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.

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): pass mapStyle to 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_ref under output: 'server'; prerender the page.
  • Entry ids end in .md on Astro 4: the collection’s base is inside src/content/ (Supported versions).
  • A few maps, no collection: YAML files in public/ shown with <Map src> (Astro).
  • Your own component around <ml-map>: pass JSON.stringify(entry.data) as its config attribute (Alternatives).