How to embed openstreetmap map in a webpage with JavaScript?

Estimated read time 2 min read

To embed an OpenStreetMap map in a webpage using JavaScript, you can use a library such as leaflet.js. Here is a basic example:

  1. Include the leaflet.js library in your HTML file:
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
   integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
   crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
   integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
   crossorigin=""></script>
  1. Create a div container to hold the map in your HTML file:
<div id="mapid" style="height: 400px; width: 100%;"></div>
  1. Initialize the map and set the view in your JavaScript file:
var map = L.map('mapid').setView([51.505, -0.09], 13);
  1. Add a tile layer to the map:
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

This code will create a basic map centered at latitude 51.505 and longitude -0.09 with zoom level 13 and a default OpenStreetMap tile layer. You can find more information and examples in the leaflet.js documentation.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply