Sometimes, we want to embed OpenStreetMap map in webpage with JavaScript.
In this article, we’ll look at how to embed OpenStreetMap map in webpage with JavaScript.
How to embed OpenStreetMap map in webpage with JavaScript?
To embed OpenStreetMap map in webpage with JavaScript, we can use Leaflet.
For instance, we write
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"></script>
<link
href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"
rel="stylesheet"
/>
<div id="osm-map"></div>
to add the JavaScript and CSS files for Leaflet and the map container div.
Then we write
const element = document.getElementById("osm-map");
element.style = "height: 300px;";
const map = L.map(element);
L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {
attribution:
'© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
}).addTo(map);
const target = L.latLng("47.50737", "19.04611");
map.setView(target, 14);
L.marker(target).addTo(map);
to select the div with getElementById
.
Then we create the map with L.map
.
Next, we add a layer with L.tileLayer
.
We call addTo
to add the layer to the map
.
And then we set the location of the map with setView
.
And we call L.marker
with target
and addTo
to add the marker to the map.
Conclusion
To embed OpenStreetMap map in webpage with JavaScript, we can use Leaflet.