Mit einem simpelen Beispiel möche ich hier demonstrieren dass mit wenigen Zeilen Code mit OpenStreetMap bereits eine Kartendarstellung und in Verbindung mit Leaflet eine Positionsmarke möglich ist.
HTML:
osm.htm HTML (498 Bytes) 21.05.2023 06:58
<!DOCTYPE html >
<html lang = "de" >
<head >
<meta charset = "utf-8" />
<title > OpenStreetMap </title >
<meta http-equiv = "Content-Security-Policy" content = "default-src 'self' data: https://nominatim.openstreetmap.org/; img-src 'self' data: https://tile.openstreetmap.org/" />
</head >
<body >
<div class = "map" data-type = "osm" data-lat = "54.499864" data-lon = "9.532111" data-title = "Udo Schmal" data-info = "Ellerndiek 26 24837 Schleswig, Deutschland" > </div >
<script src = "osm.js" > </script >
</body >
</html >
JavaScript:
osm.js JavaScript (1,94 kByte) 03.07.2024 19:57
(function () {
'use strict' ;
function OpenStreetMap (item) {
item.style.width = '100%' ;
item.style.height = '300px' ;
let lat = item.dataset.lat;
let lon = item.dataset.lon;
let zoom = item.dataset.zoom || 18 ;
let map = L.map(item, {scrollWheelZoom: false }).setView([lat, lon], zoom);
if (map) {
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png' , {
attribution: 'Map data © <a href="https://www.openstreetmap.org/" target="_blank" rel="nofollow noopener noreferrer">OpenStreetMap</a> and contributors <a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank" rel="nofollow noopener noreferrer">CC-BY-SA</a>' ,
maxZoom: 21 ,
}).addTo(map);
let title = item.dataset.title;
let info = item.dataset.info;
let marker = L.marker([lat, lon]).addTo(map);
marker.bindPopup("<strong>" + title + "</strong><br />" + info);
}
}
var maps = document .querySelectorAll( '.map' );
if (maps.length > 0 ) {
function init() {
for (let i= 0 ; i < maps.length; i++ ) {
new OpenStreetMap(maps[i]);
}
}
if (! document .getElementById( 'leaflet.css' )) {
let style = document .createElement( 'link' );
style.id = 'leaflet.css' ;
style.type = 'text/css' ;
style.rel = 'stylesheet' ;
style.href = '/code/OpenStreetMap/leaflet.css' ;
document .head.appendChild( style);
}
if (! document .getElementById( 'leaflet.js' )) {
let script = document .createElement( 'script' );
script.id = 'leaflet.js' ;
script.src = '/code/OpenStreetMap/leaflet.min.js' ;
script.addEventListener('load' , init);
document .body.appendChild( script);
} else {
init();
}
}
})();