Building Interactive Maps with Leaflet.js
This step-by-step guide will quickly get you started on Leaflet basics
Table of contents
Ever Since the advent of Google Maps on Mobile Devices way back in 2006, map based applications plays a pivotal role in our every day lives, whether you are travelling to new place or ordering a food online.
So if you are a Map Enthusiast like me or wanted to know how Map based applications works under the hood, then you are at the right place. The Secret is Javascript.
Leaflet.js
Leaflet js is an open source Javascript library for building mobile-friendly and interactive map based applications.
Getting Started
We are going to use Vanilla Javascript application, so the easiest way to install Leaflet js will be including the code from a CDN
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
Creating the Map
Open a Code Editor of your choice and create a new index.html file. Include the above links in the <head> section of the HTML
<Script> Tag
I'm gonna write the Javascript code directly in the page under the script tag. So Let's get started
1. Add an 'id' tag of 'map' to the body tag
<body id="map"></body>
- Make sure our body element has enough height to show the map
body {height: 100vh;}
- Now initialize the map in the <script> section
var map = L.map('map').setView([51.505, -0.09], 13);
- Next, we’ll add a tile layer to add to our map, in this case it’s a OpenStreetMap tile layer
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
That's it. You have working map in your application
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);