### Install Dependencies and Start Development Server Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/README.md Installs project dependencies using npm and starts the GeoGirafe development server. This command is essential for local development. ```bash npm install npm start ``` -------------------------------- ### Development Setup for GeoGirafe Source: https://context7.com/geogirafe/gg-viewer/llms.txt Steps to set up the development environment for GeoGirafe. Includes cloning the repository, installing dependencies, generating certificates, and starting the development server. ```bash # Clone the repository git clone https://gitlab.com/geogirafe/gg-viewer.git cd gg-viewer # Install dependencies npm install # Generate development certificates (Linux/macOS) npm run generate-dev-certs-nix # Start the development server npm start ``` -------------------------------- ### Build GeoGirafe for Production Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/README.md Installs dependencies and builds the GeoGirafe application for production deployment. The output is placed in the `dist/app` folder. ```bash npm install npm run build ``` -------------------------------- ### Configure Onboarding Tour Steps (JSON) Source: https://context7.com/geogirafe/gg-viewer/llms.txt Defines the steps for an onboarding tour, specifying the HTML element to target, a title, and a description for each step. This helps guide new users through the application's features. ```json { "onboarding": { "steps": [ { "element": "[data-tour='theme-selection']", "title": "Theme Selection", "description": "Choose a theme to load map layers" }, { "element": "[data-tour='basemap-selection']", "title": "Basemap Selection", "description": "Switch between different background maps" }, { "component": "treeviewroot", "element": "[data-tour='treeview-filter']", "title": "Layer Filter", "description": "Filter layers in the tree view" } ] } } ``` -------------------------------- ### Install GeoGirafe Library via npm Source: https://context7.com/geogirafe/gg-viewer/llms.txt Installs the GeoGirafe library using npm. This is the first step for integrating GeoGirafe into a project. ```bash npm install @geogirafe/lib-geoportal ``` -------------------------------- ### Build GeoGirafe NPM Package Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/README.md Installs dependencies and builds the library part of GeoGirafe, outputting a transpiled version into the `dist/lib` folder. Requires prior `npm login`. ```bash npm install npm run build-lib ``` -------------------------------- ### Run GeoGirafe Viewer Docker Container Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/README.md Starts a Docker container from the GeoGirafe viewer image. It maps ports 8080 and 8443 on the host to the corresponding ports in the container, allowing access to the viewer. ```bash docker run -p 8080:80 -p 8443:443 /viewer ``` -------------------------------- ### MapFish Print Setup Configuration Source: https://context7.com/geogirafe/gg-viewer/llms.txt Sets up the print service configuration, including the print server URL, supported output formats, and layout options. Defines default format and layout, available scales, and attribute names for print output. Also configures legend printing behavior and custom scale support. ```json { "print": { "url": "https://your-server.com/printproxy/", "formats": ["pdf", "png"], "defaultFormat": "pdf", "layouts": ["A4 portrait", "A4 landscape", "A3 portrait"], "defaultLayout": "A4 portrait", "scales": [500, 1000, 2500, 5000, 10000, 25000], "defaultScale": 5000, "attributeNames": ["title", "comments", "legend"], "printLegend": { "useBbox": true, "showGroupsTitle": true }, "customScale": true } } ``` -------------------------------- ### Clone GeoGirafe Viewer Repository Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/README.md Clones the GeoGirafe Viewer project repository from GitLab. Requires Git to be installed. ```bash git clone https://gitlab.com/geogirafe/gg-viewer.git ``` -------------------------------- ### Generate Development Certificates (Windows) Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/README.md Generates development certificates required for features like service workers on Windows. Assumes Node.js is installed. ```bash npm run generate-dev-certs-win ``` -------------------------------- ### Project Build Commands (Bash) Source: https://context7.com/geogirafe/gg-viewer/llms.txt Provides common npm commands for managing the GeoGirafe project. Includes commands for starting a development server, building for production, creating library packages, building an Android APK, running tests, linting code, and configuring for a demo environment. ```bash # Development server npm start # Production build npm run build # Build library package npm run build-lib # Build Android APK npm run build-apk # Run tests npm run test # Lint code npm run lint # Configure for demo environment npm run configure-demo mapbs ``` -------------------------------- ### Activate Pre-commit Hooks with Git Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/CONTRIBUTING.md This command configures Git to use the specified directory for hook scripts, ensuring code consistency before commits. It's a one-time setup for developers contributing to the project. ```bash git config core.hookspath buildtools/git-hooks ``` -------------------------------- ### Generate Development Certificates (Linux/macOS) Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/README.md Generates development certificates required for features like service workers on Linux and macOS. Assumes Node.js is installed. ```bash npm run generate-dev-certs-nix ``` -------------------------------- ### Trust Default Development Certificates (Windows) Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/README.md Trusts the pre-generated development certificates on Windows, necessary for features like service workers if custom certificates were not generated. Assumes Node.js is installed. ```bash npm run trust-default-dev-certs-win ``` -------------------------------- ### Manage Layers in GeoGirafe (JavaScript) Source: https://context7.com/geogirafe/gg-viewer/llms.txt Provides code examples for managing layers within the GeoGirafe map. It covers retrieving all layers, finding specific layers by name, toggling their visibility, and adjusting opacity. ```javascript const context = document.geogirafe.context; const layerManager = context.layerManager; // Get all layers as a flat list const allLayers = layerManager.getFlattenedLayerTree(state.layers.layersList); // Find a layer by name const layer = layerManager.getTreeItemByLayerName('Buildings'); // Toggle a layer on/off layerManager.toggleLayer(layer, 'on'); // Activate layerManager.toggleLayer(layer, 'off'); // Deactivate // Change layer opacity layer.opacity = 0.5; // 50% opacity // Access layer properties console.log(layer.name); console.log(layer.active); console.log(layer.queryable); console.log(layer.opacity); ``` -------------------------------- ### Add WMS/WMTS External Layer Sources Source: https://context7.com/geogirafe/gg-viewer/llms.txt Configures predefined sources for external map layers, supporting both Web Map Service (WMS) and Web Map Tile Service (WMTS). Each source includes a user-friendly label, the service type, and the service URL. Examples provided include Swiss Federal Geodata, Swiss WMTS, and OpenStreetMap WMS. ```json { "externalLayers": { "predefinedSources": [ { "label": "Swiss Federal Geodata", "type": "WMS", "url": "https://wms.geo.admin.ch" }, { "label": "Swiss WMTS", "type": "WMTS", "url": "https://wmts.geo.admin.ch/1.0.0/WMTSCapabilities.xml" }, { "label": "OpenStreetMap WMS", "type": "WMS", "url": "https://ows.terrestris.de/osm/service" } ] } } ``` -------------------------------- ### Check Authentication Status and User Info Source: https://context7.com/geogirafe/gg-viewer/llms.txt Provides JavaScript code to check the current OAuth authentication status and retrieve user information. It demonstrates how to access the status ('not-initialized', 'loggedIn', 'loggedOut', 'loginFailed') and user details like username, email, and roles. Includes an example of subscribing to authentication status changes. ```javascript // Check login state console.log(state.oauth.status); // Values: 'not-initialized', 'loggedIn', 'loggedOut', 'loginFailed' // Get user info if (state.oauth.userInfo) { console.log(state.oauth.userInfo.username); console.log(state.oauth.userInfo.email); console.log(state.oauth.userInfo.roles); } // Subscribe to auth changes context.stateManager.subscribe('oauth.status', (oldStatus, newStatus) => { if (newStatus === 'loggedIn') { console.log('User logged in:', state.oauth.userInfo.username); } }); ``` -------------------------------- ### Configure Demo Environment (Windows) Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/README.md Automatically copies a `config.json` file for a demo environment and downloads necessary mock objects on Windows. Requires Node.js. ```bash npm run configure-demo-win ``` -------------------------------- ### Configure Demo Environment (Linux) Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/README.md Automatically copies a `config.json` file for a demo environment and downloads necessary mock objects on Linux. Requires Node.js. ```bash npm run configure-demo ``` -------------------------------- ### Serve Production Build with Docker Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/README.md Serves the production-ready GeoGirafe application using an Nginx Docker container. Mounts the `dist/app` folder as the web server root. Requires Docker. ```bash docker run --rm -p 8088:80 -v $(pwd)/dist/app:/usr/share/nginx/html nginx:latest ``` -------------------------------- ### Run Linting with npm Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/CONTRIBUTING.md This command executes the linting process for the project using npm. It checks the code for style and potential errors according to the project's defined rules. Successful execution is a prerequisite for validating a merge request. ```bash npm run lint ``` -------------------------------- ### Deploy GeoGirafe using Docker Source: https://context7.com/geogirafe/gg-viewer/llms.txt Instructions for deploying GeoGirafe using Docker. This includes pulling the official Docker image and running it with custom configurations. ```bash # Pull and run the Docker container docker pull geogirafe/viewer # Run with custom configuration docker run -p 8080:80 -p 8443:443 \ -v $(pwd)/config.json:/usr/share/nginx/html/config.json \ geogirafe/viewer ``` -------------------------------- ### Conditional Drawing Button Rendering Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/edit/template.html This code snippet controls the display of drawing-related buttons, specifically a 'Cancel editing' button or a 'Start drawing' button with an icon and text. The rendering is determined by whether the user is currently in a drawing mode, managed by `this.displayDrawingCancelButton()`. ```javascript `${this.layer ? uHtml` ${this.displayDrawingCancelButton() ? uHtml` ![cancel-drawing-icon](icons/close.svg) Cancel editing ` : uHtml` ![start-drawing-icon](${this.getButtonIcon()}) ${this.getButtonText()} `} ` : uHtml```} ``` -------------------------------- ### Create a Custom Web Component Source: https://context7.com/geogirafe/gg-viewer/llms.txt Demonstrates how to create a custom web component using TypeScript and the GirafeHTMLElement base class. It shows how to define template and style URLs, register event listeners for state changes (e.g., zoom level), and implement rendering logic. The component is then registered with the customElements registry. ```typescript import GirafeHTMLElement from '@geogirafe/lib-geoportal/base'; class MyCustomComponent extends GirafeHTMLElement { templateUrl = './template.html'; styleUrls = ['./style.css']; constructor() { super('my-custom-component'); } protected override connectedCallback() { super.connectedCallback(); this.render(); this.registerEvents(); } private registerEvents() { // Subscribe to state changes this.subscribe('position.zoom', (oldZoom, newZoom) => { this.onZoomChanged(newZoom); }); } private onZoomChanged(zoom: number) { console.log('Zoom changed to:', zoom); this.refreshRender(); } render() { super.render(); // Additional rendering logic this.girafeTranslate(); } } // Register the custom element customElements.define('my-custom-component', MyCustomComponent); ``` -------------------------------- ### Build Docker Image for GeoGirafe Viewer Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/README.md Builds a Docker image containing the GeoGirafe viewer application. This command uses a Dockerfile located in 'buildtools/Dockerfile' and the 'dist' directory as the build context. The image is tagged with '/viewer'. ```bash docker build -t /viewer -f buildtools/Dockerfile dist ``` -------------------------------- ### Publish GeoGirafe Library Package to npmjs.com Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/README.md Publishes the built GeoGirafe library package to npmjs.com with public access. Requires prior `npm login` and `npm run build-lib`. ```bash npm run publish-lib --access public ``` -------------------------------- ### Build Android Application with npm Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/README.md Builds the Android application for production using npm. It requires a prior production build and utilizes the 'config.json' file from the 'dist/app' directory. The output is an APK package located in 'dist/apk'. ```bash npm run build-apk ``` -------------------------------- ### GeoGirafe Basic Configuration (config.json) Source: https://context7.com/geogirafe/gg-viewer/llms.txt A sample JSON configuration file for GeoGirafe, demonstrating basic settings for locale, languages, map properties, themes, basemaps, search, print, and projections. ```json { "general": { "locale": "en-US" }, "languages": { "translations": { "en": ["i18n/en.json"], "de": ["i18n/de.json"], "fr": ["i18n/fr.json"] }, "defaultLanguage": "en" }, "map": { "srid": "EPSG:2056", "scales": [200000, 100000, 50000, 25000, 10000, 5000, 2500, 1000, 500], "startPosition": "2600000,1200000", "startZoom": "4", "maxExtent": "2420000,1030000,2900000,1350000", "showScaleLine": true }, "themes": { "url": "https://your-server.com/themes?interface=desktop", "defaultTheme": "Default Theme", "selectionMode": "add" }, "basemaps": { "defaultBasemap": "Base Map", "OSM": true, "SwissTopoVectorTiles": false, "emptyBasemap": true }, "search": { "url": "https://your-server.com/search?query=###SEARCHTERM###&lang=###SEARCHLANG###", "objectPreview": true, "layerPreview": true, "minResolution": 0.5 }, "print": { "url": "https://your-server.com/printproxy/", "defaultLayout": "A4 portrait", "formats": ["pdf", "png"] }, "crs": [ { "code": "EPSG:2056", "definition": "+proj=somerc +lat_0=46.9524055555556 +lon_0=7.43958333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +units=m +no_defs" } ], "projections": { "EPSG:4326": "WGS84", "EPSG:2056": "LV95" } } ``` -------------------------------- ### Render Themes with Icons using uHtmlFor Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/themes-mobile/themes-select/template.html This snippet demonstrates how to iterate over all themes in the application state and generate HTML for each theme, including its icon. It uses the `uHtmlFor` utility to create the HTML structure for each theme, displaying its icon using an image tag. ```typescript Object.values(this.state.themes._allThemes).map((theme: ThemeLayer) => uHtmlFor(theme, theme.id)\` ![Theme icon](${theme.icon}) \`) ``` -------------------------------- ### Configure GeoGirafe Map with Full API Attributes (HTML) Source: https://context7.com/geogirafe/gg-viewer/llms.txt Illustrates the full API configuration for the `` element, including detailed settings for center, zoom, basemap, and basemap selector. ```html ``` -------------------------------- ### Display Contact Reasons in HTML Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/contact/template.html Renders a list of contact reasons dynamically within an HTML structure. It maps over an array of reasons provided by the configuration manager and formats them using a template literal tagged with `uHtml`. ```javascript `${this.context.configManager.Config.contact?.reasons.map((reason) => uHtml` ${reason} `)}` ``` -------------------------------- ### Render Basemaps with Thumbnails using uHtmlFor Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/themes-mobile/themes-select/template.html This snippet shows how to render basemaps available in the application state, each accompanied by its thumbnail image. It iterates through the `basemaps` object and uses `uHtmlFor` to generate the HTML for each basemap, displaying its thumbnail. ```typescript Object.values(this.state.basemaps).map(basemap => uHtmlFor(basemap, basemap.id)\` ![Basemap thumbnail](${basemap.thumbnail}) \`) ``` -------------------------------- ### Create Mailto Link for Contact Email Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/contact/template.html Generates a clickable 'mailto:' link using the contact email address from the configuration. This allows users to directly email the support team with their email client. ```javascript `${'mailto:' + this.context.configManager.Config.contact?.email}` ``` -------------------------------- ### Add a Simple Map View Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/api.html Demonstrates how to add a basic map view using the GeoGirafe API. ```APIDOC ## Add a Simple Map View ### Description This example shows how to add a basic map component to your webpage. ### Method HTML Web Component ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```html ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Format and Join Coordinates (JavaScript) Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/context-menu/default-context-menu/template.html Formats and joins coordinate data for display. It calls a `printCoordinate` function with coordinate, format, and precision, then joins the resulting array elements with a comma and space. Assumes `printCoordinate` returns an array. ```javascript this.printCoordinate(f.coordinate, f.format, f.precision).join(', ') ``` -------------------------------- ### Display Loading or No Data State (JavaScript) Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/context-menu/default-context-menu/template.html Conditionally displays a loading indicator or 'No data' message based on the `loading` state. If `loading` is true, it shows a progress icon; otherwise, it displays the `content` or a localized 'No data' string. Relies on `uHtml` for rendering and `i18nManager` for translations. ```javascript f.loading ? uHtml`![${this.context.i18nManager.getTranslation('Loading')}](icons/progress.svg) ` : '' f.content ? f.content : this.context.i18nManager.getTranslation('No data') ``` -------------------------------- ### Initialize GeoGirafe API and Format Content Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/api.html This JavaScript code initializes the GeoGirafe API by setting the API origin based on the current window location. It also formats content from a 'left' div into a 'pre' element and appends it to a 'right' div, cleaning up whitespace. ```javascript document.addEventListener('DOMContentLoaded', () => { const apiOrigin = `${window.location.origin}${window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/'))}`; const elem = document.getElementById('include-code'); elem.textContent = elem.textContent.replace('src="/geogirafe-api.js"', `src="${apiOrigin}/geogirafe-api.js"`); const sections = document.querySelectorAll('section'); sections.forEach((section) => { const leftDiv = section.querySelector('.left'); const rightDiv = section.querySelector('.right'); if (leftDiv && rightDiv) { let content = leftDiv.innerHTML; content = content.replace(/\s+/g, ' ').replace(/>\s+/g, '>').replace(/\s+ uHtml` `) this.mapContextMenuState.sources.map(f => uHtml` `) ``` -------------------------------- ### Theme Management in GeoGirafe (JavaScript) Source: https://context7.com/geogirafe/gg-viewer/llms.txt Details how to work with themes in GeoGirafe, including finding themes and layers by name, cloning themes, and merging them into the layer tree. This allows for organized management of map content. ```javascript const themesHelper = context.themesHelper; // Find a theme by name const theme = themesHelper.findThemeByName('Transport'); // Find a layer within themes const layer = themesHelper.findLayerByName('Roads'); // Add a theme to the layer tree const clonedTheme = theme.clone(); clonedTheme.isExpanded = true; hemesHelper.mergeThemeInLayerTree(clonedTheme, true); // true = activate layers ``` -------------------------------- ### Enable 3D View Configuration Source: https://context7.com/geogirafe/gg-viewer/llms.txt Configures the 3D map view, including terrain data, imagery, and 3D tilesets. Specifies terrain URL, imagery details (URL, SRID, LODs, coverage), and paths to 3D tileset JSON files. Also sets the maximum zoom distance for the 3D view. ```json { "map3d": { "terrainUrl": "https://your-server.com/terrain/", "terrainImagery": { "url": "https://wmts.example.com/tiles/{z}/{y}/{x}.png", "srid": 3857, "minLoD": 8, "maxLoD": 17, "coverageArea": [6.0, 47.0, 10.0, 48.0] }, "tilesetsUrls": [ "https://your-server.com/3dtiles/buildings/tileset.json", "https://your-server.com/3dtiles/terrain/tileset.json" ], "maximumZoomDistance": 25000 } } ``` -------------------------------- ### Render Print Format Options in HTML Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/print/template.html Renders a list of print format options using the uHtml template literal. It iterates over the 'printFormats' array and displays each format in uppercase. ```javascript Format ${this.printFormats.map((format) => uHtml` ${format.toUpperCase()} `)} ``` -------------------------------- ### Render DPI Options in HTML Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/print/template.html Renders a list of DPI (dots per inch) options for printing using the uHtml template literal. It iterates over the 'dpis' array and displays each DPI value. ```javascript DPI ${this.dpis.map((dpi) => uHtml` ${dpi} `)} ``` -------------------------------- ### Render Print Job List in HTML Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/print/template.html Renders a list of print jobs using the uHtml template literal. Each item displays the selected layout, format, time, and status icons (close, loading, download, error). ```javascript ${this.printList.map((printItem) => uHtml` ![close-icon](icons/close.svg)![loading-icon](icons/loading.svg) ![loading-icon](icons/download.svg) ![loading-icon](icons/error.svg) ${printItem.selectedLayoutName} (${printItem.selectedFormat.toUpperCase()}) ${printItem.time} `)} ``` -------------------------------- ### Render Map Scales from Configuration using JavaScript Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/scale/template.html This JavaScript code iterates over the map scales defined in the application's configuration. It uses a helper function `getFormatedScale` to format each scale and then renders it using a tagged template literal `uHtml`. This is typically used for dynamically updating UI elements based on configuration. ```javascript `${this.context.configManager.Config.map.scales.map((scale) => uHtml` ${this.getFormatedScale(scale)} `)}` ``` -------------------------------- ### Add a Map with Center Coordinates Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/api.html Shows how to initialize the map centered on specific geographical coordinates. ```APIDOC ## Add a Map with Center Coordinates ### Description Initialize the GeoGirafe map component with specific center coordinates. ### Method HTML Web Component Attribute ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```html ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Render Layout Options in HTML Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/print/template.html Renders a list of available map layouts using the uHtml template literal. It iterates over the 'layouts' array and displays the 'name' property of each layout. ```javascript Layout ${this.layouts.map((layout) => uHtml` ${layout.name} `)} ``` -------------------------------- ### Access and Modify Application State (JavaScript) Source: https://context7.com/geogirafe/gg-viewer/llms.txt Shows how to access the global GeoGirafe instance and its state manager in JavaScript. It covers reading and modifying map position, interface panel visibility, language, and projection. ```javascript // Access the global geogirafe instance const geogirafe = document.geogirafe; // Get the state manager const state = geogirafe.state; // Read current map position console.log(state.position.center); // [x, y] console.log(state.position.zoom); // zoom level console.log(state.position.scale); // current scale // Change map position state.position.center = [2600000, 1200000]; state.position.zoom = 8; // Toggle interface panels state.interface.drawingPanelVisible = true; state.interface.printPanelVisible = true; state.interface.sharePanelVisible = true; // Change language state.language = 'de'; // Change projection state.projection = 'EPSG:4326'; ``` -------------------------------- ### GeoGirafe Desktop HTML Structure (index.html) Source: https://context7.com/geogirafe/gg-viewer/llms.txt The main HTML file for the GeoGirafe desktop application. It includes meta tags, script imports, and defines the structure of the web application using custom web components. ```html My Geoportal
``` -------------------------------- ### Subscribe to State Changes in GeoGirafe (JavaScript) Source: https://context7.com/geogirafe/gg-viewer/llms.txt Demonstrates how to subscribe to various state changes within the GeoGirafe application using the state manager. It covers subscribing to position changes, layer activation, and basemap updates. ```javascript // Get the context from document const context = document.geogirafe.context; // Subscribe to position changes context.stateManager.subscribe('position.center', (oldValue, newValue) => { console.log('Map center changed:', newValue); }); // Subscribe to zoom changes context.stateManager.subscribe('position.zoom', (oldValue, newValue) => { console.log('Zoom changed from', oldValue, 'to', newValue); }); // Subscribe to layer activation with regex pattern context.stateManager.subscribe(/layers.layersList..*.activeState/, (oldActive, newActive, layer) => { console.log(`Layer ${layer.name} ${newActive ? 'activated' : 'deactivated'}`); }); // Subscribe to basemap changes context.stateManager.subscribe('activeBasemaps', (oldBasemaps, newBasemaps) => { console.log('Active basemaps:', newBasemaps.map(b => b.name)); }); ``` -------------------------------- ### Update GeoGirafe Version Display (JavaScript) Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/demo/index.html This JavaScript function fetches version and build information from a 'about.json' file and updates an HTML element with the formatted version. It uses the Fetch API to make the request and DOM manipulation to display the result. This is useful for dynamically showing the current version of a GeoGirafe instance. ```javascript function updateVersion(elementId) { fetch('mapbs/about.json') .then((response) => response.json()) .then((data) => { const version = data.version.split('-')[0]; document.getElementById(elementId).innerHTML = `(v. ${version}.${data.build})`; }); } window.addEventListener('DOMContentLoaded', (event) => { updateVersion('gg-version'); }); ``` -------------------------------- ### Render External Links with Icons (JavaScript) Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/context-menu/default-context-menu/template.html Renders a list of external links, each with a localized title and an 'open in new' icon. It iterates over a `links` array, extracting translation keys and content URLs. Uses `uHtml` for rendering and `i18nManager` for text localization. ```javascript this.mapContextMenuState.links.map(f => uHtml` [${this.context.i18nManager.getTranslation(f.translation)}](${f.content}) ![](icons/open_in_new.svg) `) ``` -------------------------------- ### OAuth/OIDC Configuration Source: https://context7.com/geogirafe/gg-viewer/llms.txt Configures OAuth/OIDC authentication settings for the application. Specifies the issuer URL, client ID, algorithm, scopes, and login requirements for the identity provider. Also defines URLs for user info, login, logout, and the authentication mode for the Geomapfish integration. ```json { "oauth": { "issuer": { "url": "https://auth.example.com/realms/geoportal", "clientId": "geoportal-client", "algorithm": "oidc", "scope": "openid profile email", "loginRequired": false, "checkSessionOnLoad": true, "audience": ["api.example.com"] }, "geomapfish": { "userInfoUrl": "https://api.example.com/loginuser", "loginUrl": "https://api.example.com/login", "logoutUrl": "https://api.example.com/logout", "authMode": "cookie" } } } ``` -------------------------------- ### Render Preference Groups and Preferences (JavaScript) Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/userpreferences/template.html This snippet iterates through preference groups and their associated preferences to render UI elements. It uses a template literal tagged with `uHtml` for HTML generation and `uHtmlFor` for rendering individual preferences. It handles different UI element types like 'select', 'checkbox', and 'color'. ```javascript `${this.preferenceGroups.map(group => uHtml` ${group} ${this.getPreferencesByGroup(group).map((\[preference, key\]) => uHtmlFor(preference, key)` ${preference.uiElement === 'select' ? uHtml` ${key} ${preference.options.map(option => uHtml` ${option.label} `)} ` : uHtml``} ${preference.uiElement === 'checkbox' ? uHtml` ${key} ` : uHtml``} ${preference.uiElement === 'color' ? uHtml` ${key} ` : uHtml``} `)} `)} Reset All ` ``` -------------------------------- ### Search API Configuration Source: https://context7.com/geogirafe/gg-viewer/llms.txt Configures the search API endpoint and its parameters. Includes the search URL with placeholders for the search term and language, SRID for results, and settings for object/layer previews, minimum resolution, and default styling for search results. ```json { "search": { "url": "https://your-server.com/search?limit=50&query=###SEARCHTERM###&lang=###SEARCHLANG###", "resultsSrid": "EPSG:2056", "objectPreview": true, "layerPreview": true, "minResolution": 0.5, "defaultFillColor": "#3388ff7f", "defaultStrokeColor": "#3388ff", "defaultStrokeWidth": 2, "paintSearchResults": true } } ``` -------------------------------- ### Perform Batch State Changes in GeoGirafe (JavaScript) Source: https://context7.com/geogirafe/gg-viewer/llms.txt Explains how to group multiple state changes into a single batch operation to optimize performance and prevent excessive re-renders. This is useful for updating several properties simultaneously. ```javascript // Batch multiple state changes to prevent excessive re-renders context.stateManager.batchChanges((state) => { state.position.center = [2600000, 1200000]; state.position.zoom = 10; state.interface.drawingPanelVisible = false; }); ``` -------------------------------- ### Feature Selection and Highlighting (JavaScript) Source: https://context7.com/geogirafe/gg-viewer/llms.txt Demonstrates how to manage feature selection within the GeoGirafe map. This includes clearing selections, accessing selected features, highlighting features, and focusing the map view on selected features. ```javascript // Clear current selection state.selection.selectedFeatures = []; state.selection.selectionParameters = []; // Access selected features const selectedFeatures = state.selection.selectedFeatures; selectedFeatures.forEach(feature => { console.log(feature.getProperties()); console.log(feature.getGeometry()); }); // Highlight features state.selection.highlightedFeatures = [feature1, feature2]; // Focus on features (zoom to) state.selection.focusedFeatures = [feature]; ``` -------------------------------- ### Rendering Grouped Results with Icons in GG-Viewer Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/search-mobile/template.html This code demonstrates the dynamic rendering of grouped search results. It iterates over object keys, displays an icon for each group, and then lists the labels for each result within that group. It assumes a UI framework (uHtml) for template creation and component methods for icon retrieval. ```JavaScript ${Object.keys(this.groupedResults).map(group => uHtml` ![result icon](${this.getIcon(group)}) ${this.groupedResults[group].map(result => uHtml` ${result.get('label')} `)} `)} ``` -------------------------------- ### Render Layer Tree HTML in JavaScript Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/themes-mobile/theme/template.html Generates HTML for layer tree items, handling both group layers and individual layers. It recursively calls itself for nested group layers. Dependencies include the `uHtmlFor` function and potentially a `_GroupLayer` class. ```javascript ${(this.theme?.children ?? []).map(layer => (layer instanceof _GroupLayer) ? uHtmlFor(layer, layer.treeItemId) : uHtmlFor(layer, layer.treeItemId))} ``` -------------------------------- ### Render Scale Options in HTML Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/print/template.html Renders a list of predefined map scales using the uHtml template literal. It iterates over the 'scales' array and displays each scale in the format '1 : scale'. ```javascript Scale ${this.scales.map((scale) => uHtml` 1 : ${scale} `)} ``` -------------------------------- ### Render Layer Name and Icon Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/treeview/treeviewtheme/template.html Renders the layer name and an associated theme icon. It conditionally displays a remove icon if the layer is removable. ```javascript ![theme-icon](icons/theme.svg) ${this.layer.name} ${this.layer.isRemovable ? uHtml` ![Remove theme](icons/trash.svg) ` : ``} ``` -------------------------------- ### Add a Map with Custom Basemap Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/api.html Explains how to specify a custom basemap for the map component. ```APIDOC ## Add a Map with Custom Basemap ### Description Set a custom basemap for the GeoGirafe map component. ### Method HTML Web Component Attribute ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```html ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Conditional Widget Rendering with uHtml Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/timerestriction/template.html This snippet demonstrates conditional rendering of UI elements based on widget type. It iterates through a list of widgets, rendering a datepicker for 'datepicker' widgets and a default rendering for others, using the uHtml template literal. The exact behavior of uHtml and the default rendering is not specified. ```javascript ${ [this.widget].map(widget => widget === 'datepicker' ? uHtml` ` : uHtml` `) } ``` -------------------------------- ### Map Operations with Map Manager (JavaScript) Source: https://context7.com/geogirafe/gg-viewer/llms.txt Illustrates how to use the Map Manager to interact with the underlying OpenLayers map instance. It covers retrieving map view properties, zooming to specific extents, setting center and zoom levels, and rotating the map. ```javascript const mapManager = context.mapManager; const olMap = mapManager.getMap(); // Get current view properties const view = olMap.getView(); console.log(view.getCenter()); console.log(view.getZoom()); console.log(view.getResolution()); console.log(view.getProjection().getCode()); // Zoom to an extent const extent = [2590000, 1190000, 2620000, 1220000]; mapManager.zoomToExtent(extent); // Set map center view.setCenter([2600000, 1200000]); // Set zoom level view.setZoom(12); // Rotate the map (in radians) view.setRotation(Math.PI / 4); // 45 degrees ``` -------------------------------- ### Render Layers in GG Viewer Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/treeview/treeviewroot/template.html Renders a list of layers based on their visibility and type. It uses a mapping function to generate HTML for different layer types (ThemeLayer, GroupLayer) and falls back to a default rendering for other layer types. The function `this.sortedLayers()` is assumed to provide the layers. ```javascript ${this.sortedLayers().filter(layer => layer.isVisible).map(layer => (layer instanceof ThemeLayer) ? uHtmlFor(layer, layer.treeItemId)\` \` : (layer instanceof GroupLayer) ? uHtmlFor(layer, layer.treeItemId)\` \` : uHtmlFor(layer, layer.treeItemId)\` \` )} ``` -------------------------------- ### Displaying Search and Close Icons in GG-Viewer Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/search-mobile/template.html This snippet shows how search and close icons are referenced and displayed within the GG-Viewer UI. It utilizes component properties for icon paths, assuming a framework that supports template interpolation. ```JavaScript ![search-icon](${this.searchIcon}) ![close-icon](icons/close.svg) ``` -------------------------------- ### Embed GeoGirafe Map with Basic Configuration (HTML) Source: https://context7.com/geogirafe/gg-viewer/llms.txt Demonstrates how to embed a GeoGirafe map into an HTML page using the `` custom element. It shows basic attributes like center, zoom, and basemap selection. ```html ``` -------------------------------- ### Render Grouped Results with Icons (JavaScript) Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/search/template.html Renders grouped search results with corresponding icons. It iterates through object keys to display icons and labels for each group. Assumes 'uHtml' is a templating function and 'this' context provides necessary data like 'groupedResults' and 'searchIcon'. ```javascript `${Object.keys(this.groupedResults).map(group => uHtml` ![result icon](${this.getIcon(group)}) ${this.groupedResults[group].map(result => uHtml` ${result.get('label')} `)} `)} ` ``` -------------------------------- ### Handle OAuth Callback and Errors with JavaScript Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/tools/auth/silentlogincallback.html This JavaScript code parses URL search parameters to determine if an OAuth error occurred or if a successful callback is received. It then sends a message to the parent window using `window.parent.postMessage`. Dependencies include the browser's `URL` and `URLSearchParams` APIs. ```javascript try { const url = new URL(window.location.href); const params = url.searchParams; if (params.has('error')) { window.parent.postMessage( { type: 'OAUTH_ERROR', error: `${params.get('error')}: ${params.get('error_description')}` }, '*' ); } else { window.parent.postMessage({ type: 'OAUTH_CALLBACK', data: Object.fromEntries(params.entries()) }, '*'); } } catch (error) { window.parent.postMessage({ type: 'OAUTH_ERROR', error: error.message }, '*'); } ``` -------------------------------- ### Display User Icon and Name (JavaScript) Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/auth/template.html Renders a user icon, defaulting to 'icons/user.svg' if not specified, and displays the user's given and family names. It also includes a method 'getDisplayName' for potentially alternative name formatting. This snippet is likely part of a larger UI component. ```javascript ![menu-icon](icons/user.svg) Login ![menu-icon](${this.userIconUrl ?? 'icons/user.svg'}) ${this.state.oauth.userInfo?.given_name + ' ' + this.state.oauth.userInfo?.family_name} ${this.getDisplayName()} ``` -------------------------------- ### Display Properties in Viewer Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/selectionwindow/template.html Displays key-value pairs of properties within the GeoGirafe viewer. It iterates through displayed properties, formatting them with labels and values, and uses htmlUnsafe for rendering potentially complex values. ```javascript ${this.displayedProperties.map((keyValue) => uHtml` `)} Label Value ${this.htmlUnsafe(keyValue[1] as string)} ``` -------------------------------- ### Configure Custom Context Menu Links (JSON) Source: https://context7.com/geogirafe/gg-viewer/llms.txt Defines custom links that appear in the context menu of the map. It specifies coordinate reference systems (CRS) and corresponding URLs with placeholders for map coordinates (###MAPX###, ###MAPY###). ```json { "contextmenu": { "crs": [ { "code": "EPSG:2056", "translation": "LV95", "format": "decimal", "precision": 1 }, { "code": "EPSG:4326", "translation": "WGS84", "format": "decimal", "precision": 7 }, { "code": "EPSG:4326", "translation": "WGS84 DMS", "format": "dms", "precision": 2 } ], "links": [ { "translation": "Google Street View", "crs": "EPSG:4326", "url": "https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=###MAPY###,###MAPX###" }, { "translation": "OpenStreetMap", "crs": "EPSG:4326", "url": "https://www.openstreetmap.org/#map=16/###MAPY###/###MAPX###" }, { "translation": "Swiss Geo Admin", "crs": "EPSG:2056", "url": "https://map.geo.admin.ch/#/map?center=###MAPX###,###MAPY###&z=10" } ] } } ``` -------------------------------- ### Render Layer Groups and Active Layers with uHtmlFor Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/themes-mobile/themes-select/template.html This code snippet illustrates the process of rendering active layers grouped by their respective categories. It iterates through the keys of `activeLayersByGroup`, displaying the group name as a heading and then listing each active layer within that group using `uHtmlFor`. ```typescript Array.from(this.activeLayersByGroup.keys()).map(group => uHtmlFor(group, group.treeItemId)\`\n\n### ${group.name}\n\n${this.activeLayersByGroup.get(group)!.map(layer => uHtmlFor(layer, layer.treeItemId)\` \`)}\n\`) ``` -------------------------------- ### Render Group Name and Child Layers in GG Viewer Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/themes-mobile/group/template.html This snippet demonstrates how to render a group's name and its associated child layers using the uHtmlFor function. It assumes the existence of 'this.group' for the group name and 'this.childLayers' for the layers, with a fallback to an empty array if childLayers is not defined. The output is an HTML string. ```javascript ### ${this.group?.name} ${(this.childLayers ?? []).map(layer => uHtmlFor(layer, layer.treeItemId))} ``` -------------------------------- ### Navigation and Index Display in JavaScript Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/selectionpanel-mobile/template.html This JavaScript snippet displays the current index and total number of selected features, likely for navigation purposes within the GG Viewer. It also includes placeholders for navigation buttons. ```javascript ![Fast previous button](icons/arrow_left.svg) ![Previous button](icons/arrow_left.svg) ![Fast next button](icons/arrow_right.svg) ![Fast next button](icons/arrow_right.svg) ${`${this.currentIndex + 1}/${this.state.selection.selectedFeatures.length}`} ``` -------------------------------- ### Render Active Themes using uHtmlFor Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/themes/template.html This snippet shows the use of `uHtmlFor` to iterate through `this.activeThemes`. For each theme, it generates HTML including an icon and the theme name, identified by its unique ID. ```javascript `${Object.values(this.activeThemes).map(theme => uHtmlFor(theme, theme.id)` ![${'Icon for ' + theme.name}](${theme.icon}) ${theme.name} `)}` ``` -------------------------------- ### Render Visible Layers and Groups Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/treeview/treeviewtheme/template.html Iterates through sorted child layers, filtering for visible ones. It then renders each layer or group layer using `uHtmlFor`, ensuring proper UI representation for nested structures. ```javascript ${this.sortedChildren().filter(layer => layer.isVisible).map(layer => (layer instanceof GroupLayer) ? uHtmlFor(layer, layer.treeItemId)` ` : uHtmlFor(layer, layer.treeItemId)` `)} ``` -------------------------------- ### Render Theme Types using uHtml Source: https://gitlab.com/geogirafe/gg-viewer/-/blob/main/src/components/themes/template.html This snippet demonstrates how to iterate over `ThemeTypes` and render them using the `uHtml` templating function. It's used to display available theme options. ```javascript `${Object.values(ThemeTypes).map((themeType) => uHtml` `)}` ```