Sitemap
Allen

Allen

Starting with Leaflet Map

2 min readSep 15, 2023

Are you looking to seamlessly integrate a Leaflet map into your HTML website? This step-by-step tutorial will guide you through the process to make it happen.

Step 1: Create an HTML File

Begin by creating an HTML file for your project.

Step 2: Add Leaflet Stylesheet

In the <head> section of your HTML file, include the Leaflet stylesheet:

<link rel=”stylesheet” href=”https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity=”sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==” crossorigin=”” />

Step 3: Include Leaflet JavaScript Library

Add the Leaflet JavaScript library to the <body> section:

<script src=”https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity=”sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==” crossorigin=””></script>

Step 4: Create a Map Container

Within the <body>, create a <div> with an id of “map” and set the desired height:

<div id=”map” style=”height: 800px”></div>

Step 5: Initialize the Map

Get Allen’s stories in your inbox

Join Medium for free to get updates from this writer.

In a <script> tag, initialize the map and add an OpenStreetMap Belgium baselayer:

const map = L.map(‘map’);

L.tileLayer(‘https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: ‘© <a href = ”https://www.openstreetmap.org/copyright"> OpenStreetMap </a> contributors’}).addTo(map);

// Customize the initial view

map.setView([<%= lat %>, <%= lon %>], 12);

Step 6: Add a Marker (Optional)

To add a marker to the map, use the following code:

let myMarker = L.marker([<%= lat %>, <%= lon %>]).addTo(map);

myMarker.bindPopup(“Currently entered location”).openPopup();

Make sure to replace <%= lat %> and <%= lon %> with your desired latitude and longitude.

Feel free to adjust the maxZoom and other parameters according to your specific requirements. Enjoy mapping on your HTML website!

The complete code :

Press enter or click to view image in full size
Leaflet map code html, javascript

That’s it! You’ve successfully integrated a Leaflet map into your HTML website. Feel free to customize and enhance it further based on your project needs.

--

--