Core library for Geolonia Maps. Extends MapLibre GL JS with Geolonia Maps platform integration.
Designed to be side-effect-free and DOM-independent, serving as the shared foundation for downstream packages such as maps-embed and maps-react.
npm install @geolonia/maps-core maplibre-glmaplibre-gl is a peer dependency. v6.x is required (^6.0.0).
This package is ESM-only, following MapLibre GL JS v6. There is no require()
entry point. If you need a script-tag build, use the UMD bundle attached to each
GitHub Release — it is
self-contained and needs no worker setup. It does run its worker from a Blob
URL, so a page with a Content-Security-Policy needs worker-src blob:.
MapLibre GL JS v6 ships ESM-only and loads its worker from a real URL resolved
against import.meta.url. Most bundlers do not carry that file over on their
own, so the map silently never finishes loading unless you point MapLibre at
the worker yourself. Do this once, before the first map is created.
Two files are involved, not one: maplibre-gl-worker.mjs is a small shim that
imports ./maplibre-gl-shared.mjs as a sibling. That splits the setups in two.
Run the worker through the bundler's own worker pipeline and it comes out as a
self-contained chunk, with nothing else to place. Copy or serve the shim
verbatim instead, and the sibling has to sit next to it in the output — miss it
and the worker dies on its first import, with no exception and no console error.
Vite has such a pipeline, and ?worker&url is what routes the file through it:
// Vite
import workerUrl from 'maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url';
import { setWorkerUrl } from 'maplibre-gl';
setWorkerUrl(workerUrl);Plain ?url is not enough — it emits the shim verbatim, which puts you in the
second case without the sibling.
webpack is in that second case: copy both files into the output and point at the
copy. Note that new URL('maplibre-gl/dist/maplibre-gl-worker.mjs', import.meta.url)
does not work — webpack emits the shim on its own, leaving the sibling import
to 404.
npm install --save-dev copy-webpack-plugin// webpack.config.js
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
plugins: [
new CopyPlugin({
patterns: [
{
from: require.resolve('maplibre-gl/dist/maplibre-gl-worker.mjs'),
to: 'maplibre-gl-worker.mjs',
},
{
from: require.resolve('maplibre-gl/dist/maplibre-gl-shared.mjs'),
to: 'maplibre-gl-shared.mjs',
},
],
}),
],
};import { setWorkerUrl } from 'maplibre-gl';
setWorkerUrl('maplibre-gl-worker.mjs');For esbuild, Rollup and Turbopack, see the MapLibre docs — and work out which of the two cases above your setup lands in.
Loading MapLibre from a CDN as an ES module needs no setup: the worker URL is
derived from the module's own URL. Cross-origin, MapLibre starts that worker
from a same-origin Blob URL whose only content is an import of the CDN's
maplibre-gl-worker.mjs. Inside a module worker, imports are checked against
worker-src, not script-src. A page with a Content-Security-Policy therefore
has to allow both the Blob URL and the CDN origin in worker-src:
worker-src 'self' blob: https://unpkg.com
Use the origin of the CDN you actually load MapLibre from; unpkg is only an example here.
worker-src blob: alone is not enough: the worker starts, its import is
refused, and the map never finishes loading. The refusal happens inside the
worker, so the page sees no securitypolicyviolation event — in Chromium no
report-uri report and no console error either, apart from MapLibre's own
"Worker failed to load".
If your CSP cannot allow the CDN in worker-src, host the worker yourself and
name it explicitly before creating a map. That works with worker-src 'self'.
Without a bundler or an import map, import setWorkerUrl from the same CDN URL
as the rest of MapLibre:
import { setWorkerUrl } from 'https://unpkg.com/maplibre-gl@6.16.0/dist/maplibre-gl.mjs';
setWorkerUrl('/path/to/maplibre-gl-6.16.0/maplibre-gl-worker.mjs');The hosted worker has to come from the same MapLibre version as the module you
load from the CDN. Put the version in its path, as above, so that a browser
never pairs a cached worker with a newer module after an upgrade. From
MapLibre 6.13.0 on, maplibre-gl-worker.mjs is self-contained and is the only
file to host; up to 6.12.0 it imports maplibre-gl-shared.mjs, which has to
sit next to it.
import 'maplibre-gl/dist/maplibre-gl.css';
import '@geolonia/maps-core/css';
import { GeoloniaMap } from '@geolonia/maps-core';
const map = new GeoloniaMap({
container: '#map',
apiKey: 'YOUR-API-KEY',
style: 'geolonia/basic-v2',
center: [139.7671, 35.6812],
zoom: 14,
});const map = new GeoloniaMap({
container: '#map',
style: 'https://tile.openstreetmap.jp/styles/osm-bright/style.json',
center: [139.7671, 35.6812],
zoom: 14,
});Geolonia API key is only required when using Geolonia's hosted styles and tiles.
Extends maplibregl.Map. Accepts GeoloniaMapOptions.
const map = new GeoloniaMap({
container: '#map', // HTMLElement or CSS selector
apiKey: 'YOUR-API-KEY', // Geolonia API key
style: 'geolonia/basic-v2', // Style name or URL
center: [139.77, 35.68], // [lng, lat]
zoom: 12,
// All optional
lang: 'auto', // 'ja' | 'en' | 'auto'
stage: 'v1', // 'dev' | 'v1'
marker: true, // Show default marker at center
markerColor: '#E4402F',
openPopup: false, // Auto-open marker popup
customMarker: '#my-marker', // CSS selector for custom marker element
customMarkerOffset: [0, -15],
loader: true, // Loading animation
gestureHandling: true, // Gesture control on scrollable pages
navigationControl: true, // true | false | 'top-right' etc.
geolocateControl: false,
fullscreenControl: false,
scaleControl: false,
geoloniaControl: true, // Geolonia logo
projection: 'globe', // 'mercator' | 'globe' (see below)
geojson: 'https://example.com/data.geojson',
cluster: true,
clusterColor: '#ff0000',
choropleth: 'value', // Color polygons by a property (see below)
heatmap: 'weight', // Draw points as a heatmap (see below)
circle: { size: 'weight', color: 'category' }, // Size and color points (see below)
extrusion: 'population', // Extrude polygons by a property (see below)
simpleVector: 'my-tileset', // Vector tile URL or tileset ID
mask: './boundary.geojson', // Darken outside a boundary (see below)
rasterTiles: { url: 'https://example.com/{z}/{x}/{y}.png' }, // Overlay raster tiles (see below)
'3d': false,
errorMessage: undefined, // Message shown when the map fails to initialize
});The sources and layers added by geojson, simpleVector, mask and rasterTiles, and the layer visibility set by 3d, are applied again each time a new style is applied: by setStyle() (whether it is applied as a diff or rebuilt), and when MapLibre rebuilds the style after the WebGL context is lost or, from MapLibre 6.16, after its workers are restarted. When the new style already has all the sources and layers that geojson, simpleVector or mask added (carried over by transformStyle, or restored by MapLibre), they are kept as they are and the map does not fit to them again; the data of geojson (once fetched, when it is a URL) is written to the kept source again. Otherwise they are added again: geojson fits the map again when center is not given, and simpleVector fits the map to its tiles again unless the container has a data-lng or data-lat attribute.
When the map cannot be initialized (typically because WebGL is unavailable on the device), the container is replaced with a message telling the visitor what to try: restart the browser, restart the device, try another browser, update the graphics driver, and contact the site owner if it still fails. The message is shortened, and finally reduced to the headline alone, as the map container gets smaller.
Pass errorMessage to take that over:
// Replace the wording. The value is rendered as plain text, not as HTML.
new GeoloniaMap({ container: '#map', errorMessage: 'Sorry, the map is unavailable.' });
// Show nothing at all, e.g. when the page renders its own fallback.
new GeoloniaMap({ container: '#map', errorMessage: false });Show the map as a globe with projection: 'globe', or force a flat map with 'mercator'.
new GeoloniaMap({ container: '#map', apiKey: 'YOUR-API-KEY', projection: 'globe', zoom: 2 });- In MapLibre the projection is part of the style, so the option is applied again every time a style is applied: by
setStyle()(whether it is applied as a diff or rebuilt), and when MapLibre rebuilds the style after the WebGL context is lost or, from MapLibre 6.16, after its workers are restarted. - Where possible, the option is written into the
projectionof the style before it is applied, so the map does not switch to the projection of the style on the way. When that is not possible (for example, for the first style), the projection is set right after the style is loaded; if the projection of the style (mercator if the style has none) is different, the map switches to it first. - The option takes precedence over the
projectionof the style, including a style returned by yourtransformStyle. - A projection changed later with
map.setProjection()stays until a style is applied again, and then the option applies again. - Without the option, the projection of the style is used (mercator if the style has none). Any other value logs an error and is ignored.
- MapLibre limits the initial camera before the style is loaded, as for a flat map, so a
centernear a pole may be moved toward the equator (a flat map cannot show beyond about 85° of latitude).
Style the geojson data by the values of its properties, without writing MapLibre expressions.
// Color polygons by `value`. The range defaults to the min and max of the data.
new GeoloniaMap({ container: '#map', geojson, choropleth: 'value' });
new GeoloniaMap({
container: '#map',
geojson,
choropleth: { property: 'value', colors: ['#FFF2CC', '#B3261E'], range: [0, 100] },
});
// Draw points as a heatmap. `true` weights every point equally.
new GeoloniaMap({ container: '#map', geojson, heatmap: 'weight' });
// Size points by `weight` and color them by `category`.
// Numeric values get a color ramp, other values one color per category.
new GeoloniaMap({ container: '#map', geojson, circle: { size: 'weight', color: 'category' } });
// Fix the color of each value with an object instead of an array.
new GeoloniaMap({
container: '#map',
geojson,
circle: { color: 'status', colors: { normal: '#3b82f6', warning: '#eab308', danger: '#ef4444' } },
});
new GeoloniaMap({
container: '#map',
geojson,
choropleth: { property: 'zoning', colors: { residential: '#fde68a', commercial: '#f87171' } },
});- These options take precedence over simplestyle properties such as
fillandmarker-color. Features without a value that can be colored fall back to the simplestyle look. heatmapandcircleturn clustering off.heatmapalso hides the point markers.circledraws every point as a circle, including points withmarker-symbol, and hides the icons and titles.- The range and categories are computed again when the GeoJSON is loaded from a URL or replaced with
updateData(). colorsis optional. The defaults are Geolonia's orange ramp and a categorical palette.- With
choropleth, polygons without afill-opacityproperty are drawn at 0.7 opacity instead of 1, so that the base map shows through. - With
circle.color, a property is treated as numeric only when every value is a number. Numeric strings such as"12"count as categories. Unlesscolorsis an object, objects and arrays are not colored, and an empty-string category does not color features without the property or withnull. colorsmay also be an object that maps values to colors. It works withchoropleth.colors,circle.colorsandextrusion.color.colors. Each feature's value is converted to a string and looked up in the object, so the colors do not depend on the order of the data, and a key such as1matches both1and"1". Features whose value is not in the object get their simplestyle color (marker-colorforcircle,fillforchoroplethandextrusion), or the default color. If no entry is valid, no feature is colored by value (unlike an empty array, which falls back to the default palette). An empty-string key matches only features whose value is"", not features without the property or withnull. With an object,choroplethcolors by category instead of a numeric ramp, andrangeis ignored. The same applies toextrusion.color(see below).- Colors are not validated. If a color used in the expression is not a valid CSS color, MapLibre rejects the whole expression. With an object, every entry whose color is a non-empty string is used; entries with an empty or non-string color are ignored.
Draw the geojson polygons as 3D columns whose height follows a property. Set pitch as well, since the columns look flat from straight above.
// Height and color both follow `population`.
new GeoloniaMap({ container: '#map', geojson, pitch: 60, extrusion: 'population' });
// Height follows `population`, color follows `aged_ratio`.
new GeoloniaMap({ container: '#map', geojson, pitch: 60, extrusion: { height: 'population', color: 'aged_ratio' } });
// Fine-grained settings.
new GeoloniaMap({
container: '#map',
geojson,
pitch: 60,
extrusion: {
height: { property: 'population', heightScale: 0.1 }, // 0.1 m per unit
color: { property: 'aged_ratio', colors: ['#FFF2CC', '#B3261E'], range: [0, 0.4] },
},
});- Height is set in one of two ways:
maxHeight(meters, default3000): the range is mapped proportionally to 0 tomaxHeight, so the columns fit whatever the values are. The range defaults to 0 to the maximum of the data, or to the minimum and maximum when the minimum is negative. This is the default.heightScale: meters per unit of the value. The height does not depend on the data range, so maps with different grid sizes or years can be compared at the same scale. WhenheightScaleis set,maxHeightis ignored. Negative heights are drawn flat.
- A height
rangewhose minimum is not below its maximum is ignored, and the range is taken from the data. colordefaults to the height property. Likecircle.color, numeric values get a color ramp and other values one color per category, unlesscolorsis an object that maps values to colors. In that caserangeis ignored.extrusiontakes precedence overchoroplethand the simplestylefill. The flat polygon fill is not drawn, so the simplestylefill-opacityandstrokedo not apply either. The columns are drawn at 0.9 opacity.- Polygons without a numeric height value are drawn flat.
- The range is computed again when the GeoJSON is loaded from a URL or replaced with
updateData().
Overlay raster tiles from another provider, such as a hazard map or GSI tiles, without waiting for load and calling addSource and addLayer yourself.
new GeoloniaMap({
container: '#map',
rasterTiles: {
url: 'https://cyberjapandata.gsi.go.jp/xyz/seamlessphoto/{z}/{x}/{y}.jpg',
attribution: '<a href="https://maps.gsi.go.jp/development/ichiran.html">地理院タイル</a>',
opacity: 0.7, // 0 to 1. Defaults to 1
tileSize: 256, // Defaults to 256
minZoom: 2,
maxZoom: 18, // Highest zoom served. Tiles are stretched beyond it
},
});urlmust be a template containing{z},{x}and{y}. Any other URL, including a TileJSON URL, logs a warning and is not overlaid.tileSizedefaults to 256, the size of common XYZ tiles. With MapLibre's own default of 512, each 256-pixel tile would be stretched to twice its size and look blurry.attributionis added to the map's attribution. It may contain HTML, but it is sanitized before it is shown (the same allow list as MapLibre GL JS's own attribution control): links and basic formatting tags are kept, and scripts and event handlers are removed.hrefmay only usehttp:,https:ormailto:. The same applies to the attribution of every source and tocustomAttribution.- The tiles are placed below the first symbol layer of the style, so labels stay on top. In a style without symbol layers they are placed above the style's layers. Style layers below that position, such as 3D buildings (
fill-extrusion) in some styles, are covered by the tiles unlessopacityis lowered. - Layers added by
geojsonandsimpleVectorare drawn above the tiles, and so ismaskunless itsbeforeIdnames the tiles' layer or a layer below it. This order holds when the style is loaded withouttransformStyle. Layers thattransformStylecarries over into a new style keep the position it gave them, so a carried-overmaskmay end up below newly added tiles. - The source and the layer both have the ID
geolonia-raster-tiles. Use it asbeforeIdto place your own layers or themaskrelative to the tiles. - The overlay is added again when the style is replaced with
setStyle(), also whentransformStylecarries over only its source. WhentransformStylecarries over both the source and the layer, the carried layer is kept wheretransformStyleput it. opacityoutside 0 to 1 is clamped, and anopacitythat is not a finite number falls back to 1. AtileSizethat is not a positive finite number falls back to 256. AminZoomormaxZoomthat is not a finite number is ignored.
Works like MapLibre's transformRequest, and is also called for the requests that maps-core rewrites itself: Geolonia sources (api.geolonia.com and the Geolonia tile hosts) and Geolonia sprites. For those, the function receives the URL after maps-core has added key and sessionId, so the parameters are kept as long as you build on the URL you are given.
- Return a
RequestParametersobject to use it as is. - Return
undefinedto keep the request maps-core built. - A
Promisemay be returned. If it resolves toundefined, the request maps-core built is used.
new GeoloniaMap({
container: '#map',
transformRequest: (url, resourceType) => {
// Load another tileset from the Geolonia tile server
if (resourceType === 'Source' && url.includes('tileserver.geolonia.com/oneself/')) {
return { url: url.replace('/oneself/', '/my-tileset/') };
}
return undefined;
},
});Replacing the function later with map.setTransformRequest() also removes the maps-core rewriting, including key and sessionId.
Darken everything outside a boundary, such as a city's, so that the area inside stands out.
// A GeoJSON URL with the boundary polygons.
new GeoloniaMap({ container: '#map', mask: './boundary.geojson' });
// Fine-grained settings.
new GeoloniaMap({
container: '#map',
mask: {
geojson: boundary, // URL, Feature, FeatureCollection or a Polygon/MultiPolygon/GeometryCollection geometry
color: '#000000', // default
opacity: 0.3, // default
outline: true, // draw the boundary line too; or { color: '#333333', width: 3 }
beforeId: 'waterway-name', // optional: insert below this layer (the first label layer of geolonia/basic-v2)
},
});geojsonas a string is a URL starting withhttp://orhttps://, or a path starting with/or.(such as./boundary.geojson). The response may also be a bare Polygon, MultiPolygon or GeometryCollection geometry, and so may an object passed directly.- Every Polygon and MultiPolygon, including those inside a GeometryCollection, is cut out, so exclaves and islands work. Holes inside a polygon, such as another area enclosed by the boundary, stay dark, and polygons inside such a hole (an island in a lake) are cut out again. Other geometries are ignored. A polygon whose outer ring is broken is skipped.
- The polygons should not overlap each other, or the cut-out may be drawn incorrectly. Polygons that cross the antimeridian (longitude ±180°), and polygons with coordinates outside longitude ±180° or latitude ±90° (such as projected coordinates), are not supported. A polygon whose outer ring has coordinates outside that range is skipped, and such a hole is dropped. MapLibre fills at most 500 rings of one polygon per tile, so when a tile contains more than about 500 boundary polygons, small ones may not be cut out.
- By default the mask is drawn above every layer of the base map, labels included, and below the first layer whose ID contains
simple-style(the data of thegeojsonandsimpleVectoroptions), so place names outside the area are darkened too. To keep labels bright, setbeforeIdto the first label layer of the style; the mask is inserted below that layer, and every layer after it (including buildings and boundaries in some styles) stays bright. AbeforeIdthat is not in the map logs an error and the default position is used. Layers added later withoutbeforeIdare drawn above the mask. - The
geojsonlayers are found bysimple-stylein their ID. ASimpleStyleadded before the mask with a customidthat does not containsimple-styleis drawn below it. - The layers are
geolonia-mask(fill) and, only withoutline,geolonia-mask-outline(line), drawn right above the fill.beforeIdinserts a layer below the given layer, so these IDs place your own layers below the mask:beforeId: 'geolonia-mask'puts a layer below the whole mask, andbeforeId: 'geolonia-mask-outline'puts it between the fill and the outline. To draw a layer above the mask, add it after the mask withoutbeforeId; it goes on top of every layer. - Adjacent polygons that share an edge may show a faint seam along the shared edge inside the area. Merge them into one polygon to avoid it.
- If
remove()is called while the style is being reloaded or the WebGL context is lost (when the mask's source is temporarily gone), the mask's source and layer may come back when MapLibre restores the style, and they are no longer removed by thatMask. - With
3d: true, the mask is a flat fill drawn over the 3D buildings of the base map, so tall buildings inside the area may look darkened where they overlap the area outside. The look of 3D buildings with a mask is not guaranteed. - A polygon enclosed by a hole of another polygon (such as an area enclosed by a city) is detected when all its vertices and the midpoints of its edges are inside the hole or on its edge, within about 0.2 m. Adjacent polygons should share their vertices or use coordinates rounded to 6 or more decimal places; otherwise an enclosed polygon may be darkened. With very detailed boundaries that have both holes and polygons inside them, this check takes more time.
outline: truedraws a 2-pixel line in the maskcolor.- An
opacitythat is not a number from 0 to 1 logs an error and the default is used. If loading the URL (including the response body) does not finish within 30 seconds, it is aborted and an error is logged. Skipped polygons or holes are reported with a warning, or with an error when every polygon is skipped. If MapLibre rejects the fill layer (for example, a color it cannot parse), nothing is added and an error is logged. If only the outline is rejected, the fill is kept and an error is logged. - Without
center,bounds,geojsonandsimpleVector, the map fits to the boundary. This also happens again aftersetStyle(), since the mask is added again for the new style (unlesstransformStylecarried the mask's sources and layers over to the new style, including the outline when the mask draws one, in which case it is kept as is). As withgeojson, a position restored byhashor azoomwithoutcenterdoes not prevent the fit.
Extends maplibregl.Marker with Geolonia's default marker style.
import { GeoloniaMarker } from '@geolonia/maps-core';
new GeoloniaMarker({ color: '#0066FF' })
.setLngLat([139.77, 35.68])
.addTo(map);GeoJSON visualization based on simplestyle-spec.
import { SimpleStyle } from '@geolonia/maps-core';
const ss = new SimpleStyle(geojson, { cluster: true });
// Also accepts `choropleth`, `heatmap`, `circle` and `extrusion` (see GeoloniaMap options)
ss.addTo(map).fitBounds();Darkens everything outside a boundary on an existing map. Takes the same value as the mask option. Call addTo after the style has loaded. After map.setStyle(), the mask is gone with the old style; call addTo again to add it to the new style (the mask option of GeoloniaMap does this for you). Only one mask can be added to a map; a second one, or a mask on a map that already has a source or layer named geolonia-mask or geolonia-mask-outline (even without outline), is not added and logs an error. Calling addTo before the style has loaded throws, as addSource does. A removed mask can be added again, and calling addTo on a mask that is already added moves it (if adding to the new map throws, for example because its style has not loaded, the mask is left on neither map).
import { Mask } from '@geolonia/maps-core';
const mask = new Mask({ geojson: './boundary.geojson', outline: true });
mask.addTo(map).fitBounds();
mask.remove();API key and stage management.
import { keyring } from '@geolonia/maps-core';
keyring.setApiKey('YOUR-API-KEY');
keyring.setStage('v1');| Package | Description |
|---|---|
@geolonia/maps-embed |
HTML data-* attribute map embedding |
@geolonia/maps-react |
React components |
npm install
npm run build # ESM + DTS
npm run test # Vitest unit tests
npm run build:umd # UMD bundle (dist/umd/), required by e2e/umd.spec.ts
npm run e2e # Playwright E2E tests
npm run lint # Biome
npm run dev # Vite dev server (example/)MIT