Demonstrates overlays.
The popups are created using Popovers from Bootstrap.
import Map from 'ol/Map.js';
import OSM from 'ol/source/OSM.js';
import Overlay from 'ol/Overlay.js';
import TileLayer from 'ol/layer/Tile.js';
import View from 'ol/View.js';
import {fromLonLat, toLonLat} from 'ol/proj.js';
import {toStringHDMS} from 'ol/coordinate.js';
const layer = new TileLayer({
source: new OSM(),
});
const map = new Map({
layers: [layer],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
const pos = fromLonLat([16.3725, 48.208889]);
// Popup showing the position the user clicked
const popup = new Overlay({
element: document.getElementById('popup'),
});
map.addOverlay(popup);
// Vienna marker
const marker = new Overlay({
position: pos,
positioning: 'center-center',
element: document.getElementById('marker'),
stopEvent: false,
});
map.addOverlay(marker);
// Vienna label
const vienna = new Overlay({
position: pos,
element: document.getElementById('vienna'),
});
map.addOverlay(vienna);
const element = popup.getElement();
map.on('click', function (evt) {
const coordinate = evt.coordinate;
const hdms = toStringHDMS(toLonLat(coordinate));
popup.setPosition(coordinate);
let popover = bootstrap.Popover.getInstance(element);
if (popover) {
popover.dispose();
}
popover = new bootstrap.Popover(element, {
animation: false,
container: element,
content: '<p>The location you clicked was:</p><code>' + hdms + '</code>',
html: true,
placement: 'top',
title: 'Welcome to OpenLayers',
});
popover.show();
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Overlay</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
#marker {
width: 20px;
height: 20px;
border: 1px solid #088;
border-radius: 10px;
background-color: #0FF;
opacity: 0.5;
}
#vienna {
text-decoration: none;
color: white;
font-size: 11pt;
font-weight: bold;
text-shadow: black 0.1em 0.1em 0.2em;
}
.popover-body {
min-width: 276px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<div style="display: none;">
<!-- Clickable label for Vienna -->
<a class="overlay" id="vienna" target="_blank" href="https://en.wikipedia.org/wiki/Vienna">Vienna</a>
<div id="marker" title="Marker"></div>
<!-- Popup -->
<div id="popup"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script type="module" src="main.js"></script>
</body>
</html>
{
"name": "overlay",
"dependencies": {
"ol": "10.2.1"
},
"devDependencies": {
"vite": "^3.2.3"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}