Skip to content

GeoLeaf-JS — Cookbook

Package: @geoleaf/coreVersion: 2.0.0 License: MIT Moteur cartographique: MapLibre GL JS ^5.0.0

Recettes pratiques pour les cas d'usage courants de GeoLeaf. Tous les exemples utilisent le nom de package correct @geoleaf/core et la vraie API publique.

Note v2.0.0 : GeoLeaf est basé sur MapLibre GL JS v5 (rendu WebGL, tuiles vectorielles natives, ESM-only). MapLibre GL JS est une peer dependency — à installer séparément.


Table of contents

  1. Minimal map
  2. Map with JSON profile
  3. Custom POI markers
  4. Filter panel
  5. Applying themes
  6. Data table
  7. Layer visibility toggle
  8. Loading all secondary modules
  9. Plugin health check
  10. Custom basemap

Recipe 1 — Minimal map

The simplest possible GeoLeaf map. MapLibre GL JS is loaded as a peer dependency.

ESM/npm (recommended):

bash
npm install @geoleaf/core maplibre-gl
ts
import { Core } from "@geoleaf/core";
import "maplibre-gl/dist/maplibre-gl.css";
import "@geoleaf/core/dist/geoleaf-main.min.css";

Core.init({
    mapId: "map",
    center: [2.3522, 48.8566], // [longitude, latitude] — MapLibre GL JS convention
    zoom: 12,
});

CDN/ESM (via unpkg) :

html
<!DOCTYPE html>
<html lang="fr">
    <head>
        <meta charset="UTF-8" />
        <!-- MapLibre GL JS (peer dependency) -->
        <link rel="stylesheet" href="https://unpkg.com/maplibre-gl@5/dist/maplibre-gl.css" />
        <!-- GeoLeaf styles -->
        <link
            rel="stylesheet"
            href="https://unpkg.com/@geoleaf/core@2.0.0/dist/geoleaf-main.min.css"
        />
        <style>
            #map {
                width: 100vw;
                height: 100vh;
                margin: 0;
            }
        </style>
    </head>
    <body>
        <div id="map"></div>
        <script type="module">
            import maplibregl from "https://unpkg.com/maplibre-gl@5/dist/maplibre-gl.js";
            import { Core } from "https://unpkg.com/@geoleaf/core@2.0.0/dist/geoleaf.esm.js";

            Core.init({
                mapId: "map",
                center: [2.3522, 48.8566],
                zoom: 12,
            });
        </script>
    </body>
</html>

Recipe 2 — Map with JSON profile

Load a full JSON configuration profile. All layers, styles, POI taxonomy, and UI settings are defined in the profile — no additional code required.

js
await GeoLeaf.loadConfig("/profiles/my-app.json");

Or pass directly in init:

js
GeoLeaf.Core.init({
    mapId: "map",
    configUrl: "/profiles/my-app.json",
});

See PROFILES_GUIDE.md for profile structure.


Recipe 3 — Custom POI markers

Load the POI module and initialize with a configuration:

js
// Load POI (lazy — produces a separate ESM chunk)
await GeoLeaf._loadModule("poi");

// Initialize POI (config from profile, or inline)
GeoLeaf.POI.init({
    taxonomy: {
        categories: [
            { id: "restaurant", label: "Restaurants", icon: "fork" },
            { id: "hotel", label: "Hotels", icon: "bed" },
        ],
    },
});

POI data is typically loaded as part of the JSON profile. The init() call configures the POI system — actual marker data comes from the configured GeoJSON or API source in the profile.


Recipe 4 — Filter panel

Filters are configured in the profile. The filter panel UI is managed automatically. Use the Filters facade for programmatic filtering:

js
// Filter a POI list by criteria
const allPois = GeoLeaf.POI.getAllPois();
const filtered = GeoLeaf.Filters.filterPoiList(allPois, {
    category: "restaurant",
});

// Update the map display with filtered results
GeoLeaf.POI.setFilteredDisplay(filtered);

// Get unique categories from the data
const categories = GeoLeaf.Filters.getUniqueCategories(allPois);

// Count POIs by category
const counts = GeoLeaf.Filters.countByCategory(allPois);

Recipe 5 — Applying themes

Apply a UI theme (light/dark):

js
// Apply via top-level API
GeoLeaf.setTheme("dark");
GeoLeaf.setTheme("light"); // default

// Apply via Core facade
GeoLeaf.Core.setTheme("dark");

// Get current UI theme
const current = GeoLeaf.Core.getTheme(); // → "dark"

For layer-specific theme switching (style presets), load the Themes module:

js
await GeoLeaf._loadModule("themes");
await GeoLeaf.Themes.applyTheme("rivers", "dark");
const available = await GeoLeaf.Themes.getAvailableThemes("rivers");

Recipe 6 — Data table

js
// Load the table module (not in Lite bundle)
await GeoLeaf._loadModule("table");

// Initialize with POI data from the profile
GeoLeaf.Table.init({ visible: true });

// Show/hide table
GeoLeaf.Table.show();
GeoLeaf.Table.hide();
GeoLeaf.Table.toggle();

Recipe 7 — Layer visibility toggle

LayerManager creates a UI control panel for toggling layer visibility:

js
await GeoLeaf._loadModule("layerManager");

// Initialize the LayerManager on the map
GeoLeaf.LayerManager.init({ map });

// Add a custom section with items
GeoLeaf.LayerManager.addSection({
    id: "custom",
    label: "Custom Layers",
    order: 10,
    items: [{ id: "regions", label: "Regions", checked: true }],
});

// Refresh the panel display
GeoLeaf.LayerManager.refresh();

// Toggle the panel collapsed/expanded state
GeoLeaf.LayerManager.toggleCollapse();

Layer visibility is toggled via the UI toggle buttons in the panel. Layers must be defined in the profile. Layer ids come from the profile layers[].id field.


Recipe 8 — Loading all secondary modules

For full-featured applications, load all secondary modules at startup:

js
// After Core.init()
await GeoLeaf._loadAllSecondaryModules();

// Now all modules are available:
GeoLeaf.POI.init(poiConfig);
GeoLeaf.Route.init(routeConfig);
GeoLeaf.Table.init(tableConfig);
GeoLeaf.Legend.init();

For optimized code splitting, load modules individually on demand:

js
// Only when user opens route panel
document.getElementById("btn-route").addEventListener("click", async () => {
    if (!GeoLeaf.plugins.isLoaded("route")) {
        await GeoLeaf._loadModule("route");
    }
    GeoLeaf.Route.show();
});

Available module names for _loadModule() :

NameDescription
poiPOI complet (core + renderers)
poiCorePOI core uniquement
poiRenderersPOI renderers uniquement
poiExtrasPOI extras (sidepanel, etc.)
routeModule itinéraire
layerManagerGestionnaire de couches
legendLégende cartographique
labelsLabels dynamiques
themesSélecteur de thèmes
tableVue tableau des POIs
searchRecherche plein-texte
basemapSelectorSélecteur de fond de carte

Recipe 9 — Plugin health check

Verify that required plugins and modules are correctly loaded:

js
// Check a plugin (CDN / global namespace)
GeoLeaf.plugins.isLoaded("storage"); // → boolean
GeoLeaf.plugins.isLoaded("addpoi"); // → boolean

// List all loaded plugins
console.log(GeoLeaf.plugins.getLoadedPlugins());
// → ["core", "storage", "labels", "legend", ...]

// Check if a plugin's dependencies are met
GeoLeaf.plugins.canActivate("addpoi"); // → true if "storage" is loaded

// APIController health
console.log(GeoLeaf.getHealth());
// → { initialized: true, modules: {...}, errors: [] }

ESM import : import { PluginRegistry } from "@geoleaf/core" pour les bundlers.


Recipe 10 — Custom basemap

Register and activate a custom vector or raster basemap.

Basemap vectoriel (style MapLibre GL JS) :

js
// Register a vector tile basemap (MapLibre GL JS style spec)
GeoLeaf.Baselayers.registerBaseLayer("my-vector-map", {
    style: "https://tiles.myserver.com/style.json",
});

// Activate it
GeoLeaf.Baselayers.setBaseLayer("my-vector-map");

Register multiple basemaps at once :

js
GeoLeaf.Baselayers.registerBaseLayers({
    "osm-standard": {
        url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
        attribution: "© OpenStreetMap contributors",
        maxZoom: 19,
    },
    satellite: {
        style: "https://tiles.myserver.com/satellite-style.json",
    },
});

// Activate one
GeoLeaf.Baselayers.setBaseLayer("satellite");

// Get current active key
console.log(GeoLeaf.Baselayers.getActiveKey());

Basemaps are typically defined in the JSON profile. Use the programmatic API for dynamic basemap switching.


Named ESM exports reference

Imports directs disponibles depuis @geoleaf/core (bundler moderne) :

ts
import {
    // High-level facades
    Core,
    UI,
    POI,
    Route,
    Table,
    Legend,
    LayerManager,
    Filters,
    Baselayers,
    Themes,
    Search,
    Notifications,
    Permalink,
    Events,
    PWA,
    GeoLeafAPI,

    // API sub-modules
    APIController,
    APIFactoryManager,
    APIInitializationManager,
    APIModuleManager,
    PluginRegistry,
    BootInfo,
    showBootInfo,

    // Utilities
    Log,
    Errors,
    CONSTANTS,
    Utils,
    Config,
    Helpers,
    Validators,
} from "@geoleaf/core";

Released under the MIT License.