Using Leaflet.js to show maps in a webpage
Last Updated :
19 Jun, 2024
Maps are incredibly helpful for showing locations on a website. Use cases of maps include showing the location of an office address, which is a better option than just showing an image or a text address. It can also be used for marking points of interest in a tourist location so that the visitor can plan by looking at all the nearby areas. Leaflet.js is a JavaScript library that makes it extremely easy to show maps on a webpage and interact with it. This guide would attempt to give a simple introduction to using Leaflet.js to display map and display the required area on the map.
HTML portion
We will start by declaring the HTML needed to display the map. Using leaflet.js requires us to import a CSS file for the map styling and the JavaScript file for the functionality of the map. The latest version of both can be found at " https://leafletjs.com/download.html " We will start by defining the area where the map has to be displayed. We first create a div with an id of "map" so that it could be accessed by the script. We will then define the height and width of the map object. Otherwise, the map would not display. We can specify any dimension required here.
html
<!DOCTYPE html>
<html>
<head>
<title>Leaflet.js Guide</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Get the leaflet CSS file -->
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
integrity=
"sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
crossorigin="" />
</head>
<body>
<h1>My Leafletjs Map</h1>
<!-- Specify the map and it's dimensions -->
<div id="map" style="width: 960px; height: 500px"></div>
<!-- Get the leaflet JavaScript file -->
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"
integrity=
"sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
crossorigin=""></script>
</body>
</html>
Mobile Version
The map can be shown full screen on a mobile device, like a web application. This is possible by making the body element and the div containing the map fill both the height and width of the screen completely. This can be done by giving both these values as 100% or 100 view units.
JavaScript portion
We will be writing the JavaScript portion of the implementation here.
- We will start by initializing the map with the map() method. The id we have to declare earlier is given to this method as a parameter. This initialized map is stored in a variable, which can be used later to add more functionalities.
javascript
// Initialize the leaflet map
const map = L.map('map');
Map initialized by Leaflet.js - Running the code now would show an empty area with the map controls. This means that our plugin has been successfully initialized. The reason we don't see any map information is that we have to specify tile information.
- The whole map of the world is not possible to be loaded at once. Hence, it is divided into multiple tiles. Only the tiles in the user's current view are updated. This saves bandwidth and makes the entire process of loading maps faster.
- This is done through an API that keeps providing and updating the tile images for the given parameters. We will be using the OpenStreetMap API to get our tilemaps for the map.
- The L.tileLayer() method accepts a URL to the API and automatically gets the required tilemap for the current user position.
- Using OpenStreetMap requires one to attribute them for their work, hence we will be attributed for them in the attribution parameter of the method. This tile layer will be added to the map using the addTo() method in the end.
- The last step one has to do before setting up the map is setting a view, that is the area of the world that has to be displayed. This is done using the setView() method. This method takes in a pair of latitude and longitude and a zoom value. The zoom value determines how close the view is to the surface. Increasing this value gets the view more closer to the ground.
- Let us set the view to that of the Eiffel Tower which has the co-ordinates 48.8584 and 2.2945. The zoom value is set to 16 for a decent view.
javascript
// Get the tile layer from OpenStreetMaps
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
// Specify the maximum zoom of the map
maxZoom: 19,
// Set the attribution for OpenStreetMaps
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// Set the view of the map
// with the latitude, longitude and the zoom value
map.setView([48.8584, 2.2945], 16);
- Reopening the webpage, we will finally see a map that has all the information for the current location, and the Eiffel Tower at the center of the map.
A view is set with the coordinates of the Eiffel Tower
Show current user location
- The leaflet can also show the view based on the current location by using locate() method. It takes in an object that has setView property set to true and a maxZoom value set to a maximum value. This command will ask for the user's location and automatically set the view to that location.
javascript
// Ask for current location and navigate to that area
map.locate({setView: true, maxZoom: 16});
Asking for location permission so that the user's current location can be displayedShowing markers on the map
Leaflet can be used to mark points on the map. This is done using the marker() method. It accepts the coordinates where the marker would be shown.
javascript
// Show a market at the position of the Eiffel Tower
let eiffelMarker = L.marker([48.8584, 2.2945]).addTo(map);
// Bind popup to the marker with a popup
eiffelMarker.bindPopup("Eiffel Tower").openPopup();
We can also add a popup to the marker that would show the name of the marker by using the bindPopup() method. This popup can be opened by default using the openPopup() method. Hence, we have successfully created a map using the Leaflet.js library and learnt to view a specific position of the world.
Final Output:

Complete Code:
html
<!DOCTYPE html>
<html>
<head>
<title>Leaflet.js Guide</title>
<meta charset="utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<!-- Get the leaflet CSS file -->
<link rel="stylesheet" href=
"https://unpkg.com/[email protected]/dist/leaflet.css"
integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
crossorigin="" />
</head>
<body>
<h1>My Leafletjs Map</h1>
<!-- Specify the map and it's dimensions -->
<div id="map" style="width: 960px; height: 500px"></div>
<!-- Get the leaflet JavaScript file -->
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"
integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
crossorigin=""></script>
<script>
// Initialize the map
const map = L.map('map')
// Get the tile layer from OpenStreetMaps
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
// Specify the maximum zoom of the map
maxZoom: 19,
// Set the attribution for OpenStreetMaps
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// Set the view of the map
// with the latitude, longitude and the zoom value
map.setView([48.8584, 2.2945], 16);
// Set the map view to the user's location
// Uncomment below to set map according to user location
// map.locate({setView: true, maxZoom: 16});
// Show a market at the position of the Eiffel Tower
let eiffelMarker = L.marker([48.8584, 2.2945]).addTo(map);
// Bind popup to the marker with a popup
eiffelMarker.bindPopup("Eiffel Tower").openPopup();
</script>
</body>
</html>
Output:
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
What is DFD(Data Flow Diagram)? Data Flow Diagram is a visual representation of the flow of data within the system. It help to understand the flow of data throughout the system, from input to output, and how it gets transformed along the way. The models enable software engineers, customers, and users to work together effectively d
9 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read