How to Embed GeoLibre in an iframe Using @geolibre/embed
Use the @geolibre/embed package to render GeoLibre maps inside cross-origin iframes by importing createEmbed and passing a configuration object with your map settings.
The @geolibre/embed package provides a lightweight, framework-agnostic solution for embedding interactive GeoLibre maps into any webpage through an iframe container. This approach isolates the map from parent page styles and scripts while enabling secure cross-origin communication.
Installation and Setup
Install the package via your preferred package manager:
npm install @geolibre/embed
# or
yarn add @geolibre/embed
# or
pnpm add @geolibre/embed
The package exports a single main function, createEmbed, located in the package entry point. This function handles iframe creation, message passing, and map initialization automatically.
Basic Implementation
Import createEmbed and invoke it with a target DOM element and configuration:
import { createEmbed } from '@geolibre/embed';
const container = document.getElementById('map-container');
const embed = createEmbed(container, {
url: 'https://geolibre.example.com/map',
width: '100%',
height: '500px',
allowFullscreen: true,
params: {
center: [-122.4194, 37.7749],
zoom: 12,
layers: ['streets', 'satellite']
}
});
The createEmbed function returns an embed instance with methods for controlling the map programmatically.
Configuration Options
The configuration object accepts the following properties:
| Property | Type | Required | Description |
|---|---|---|---|
url |
string |
Yes | Base URL of the GeoLibre map instance |
width |
string |
No | CSS width value (default: "100%") |
height |
string |
No | CSS height value (default: "400px") |
allowFullscreen |
boolean |
No | Enable fullscreen button (default: false) |
params |
object |
No | Query parameters passed to the map URL |
sandbox |
string[] |
No | Custom iframe sandbox attributes |
Advanced: Two-Way Communication
The embed instance exposes methods for bidirectional messaging with the iframe:
// Send commands to the embedded map
embed.setCenter([-74.006, 40.7128]);
embed.setZoom(10);
embed.addLayer('terrain');
// Listen for events from the map
embed.on('click', (event) => {
console.log('Map clicked at:', event.lngLat);
});
embed.on('moveend', (event) => {
console.log('Map bounds:', event.bounds);
});
Message passing uses the postMessage API with origin validation. The package automatically filters messages to only process those from the configured url origin.
React Integration
For React applications, wrap the embed in a useEffect hook:
import { useEffect, useRef } from 'react';
import { createEmbed } from '@geolibre/embed';
function MapEmbed({ mapUrl, center, zoom }) {
const containerRef = useRef(null);
const embedRef = useRef(null);
useEffect(() => {
if (!containerRef.current) return;
embedRef.current = createEmbed(containerRef.current, {
url: mapUrl,
params: { center, zoom }
});
return () => {
embedRef.current?.destroy();
};
}, [mapUrl, center, zoom]);
return <div ref={containerRef} style={{ width: '100%', height: '400px' }} />;
}
Always call destroy() on cleanup to remove event listeners and terminate the iframe.
Security Considerations
The @geolibre/embed package sets restrictive sandbox attributes by default:
defaultSandbox: [
'allow-scripts',
'allow-same-origin',
'allow-popups'
]
Override these only when necessary via the sandbox configuration option. The package validates the url origin against a whitelist to prevent clickjacking attacks.
Summary
- Install with
npm install @geolibre/embedto add iframe embedding capabilities - Import
createEmbedas the primary entry point from the package - Configure with
url, dimensions, and map parameters to initialize the iframe - Control the embedded map via method calls like
setCenter(),setZoom(), andaddLayer() - Listen to map events through the
on()method for interactive integrations - Clean up by calling
destroy()when unmounting to prevent memory leaks
Frequently Asked Questions
What browsers support @geolibre/embed?
The package supports all modern browsers with postMessage API availability: Chrome 60+, Firefox 54+, Safari 12+, and Edge 79+. Internet Explorer 11 requires a Promise polyfill.
Can I embed multiple maps on the same page?
Yes. Create separate createEmbed instances with unique container elements. Each iframe maintains independent state and communication channels. The package automatically assigns unique IDs to prevent message collision.
How do I handle authentication for private maps?
Pass authentication tokens through the params configuration object. The package automatically encodes these as URL query parameters. For enhanced security, use short-lived tokens or implement token refresh through the on('tokenExpired') event handler before requesting new credentials from your backend.
Does the embedded map work offline?
No. The iframe requires network connectivity to load the GeoLibre runtime and map tiles from the configured url. For offline-capable maps, use the full @geolibre/core package with local tile sources instead of the embed solution.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →