In the expanding world of web development, data visualization and geographic information systems (GIS) have become crucial skills. One of the most powerful tools in this realm is Leaflet.js, an open-source JavaScript library designed for building interactive maps. This blog post will guide you through the basics of Leaflet.js and its core functionalities, enabling you to create visually appealing, user-friendly maps for your web applications.
Leaflet.js is a robust library that allows you to create interactive maps with just a few lines of code. To get started, include the Leaflet.js CSS and JavaScript files in your HTML.
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
Let's start by creating a simple map centered at a specific latitude and longitude.
<div id="mapid" style="height: 180px;"></div>
<script>
var map = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
}).addTo(map);
</script>
Markers are used to pinpoint locations on the map. Each marker can also have a popup with further information.
<script>
var marker = L.marker([51.5, -0.09]).addTo(map);
marker.bindPopup("<b>Hello world!</b><br>I am a popup.").openPopup();
</script>
Layers are objects on the map that can be manipulated independently. Overlays are layers that can be toggled on or off.
<script>
var cities = L.layerGroup();
L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.').addTo(cities),
L.marker([39.74, -104.99]).bindPopup('This is Denver, CO.').addTo(cities),
L.marker([39.73, -104.8]).bindPopup('This is Aurora, CO.').addTo(cities),
L.marker([39.77, -105.23]).bindPopup('This is Golden, CO.').addTo(cities);
var grayscale = L.tileLayer(mapLink, {id: 'MapID', tileSize: 512, zoomOffset: -1})
var streets = L.tileLayer(mapLink, {id: 'MapID', tileSize: 512, zoomOffset: -1});
var baseMaps = {
"Grayscale": grayscale,
"Streets": streets
};
var overlayMaps = {
"Cities": cities
};
L.map('map', {
center: [39.73, -104.99],
zoom: 10,
layers: [grayscale, cities]
}).addTo(map);
L.control.layers(baseMaps, overlayMaps).addTo(map);
</script>
Ready to start learning? Start the quest now