Using Leaflet.js to show maps in a webpage

08 May, 2020
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.
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.
<!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/leaflet@1.6.0/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/leaflet@1.6.0/dist/leaflet.js"    integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="    crossorigin=""></script></body>  </html>
Mobile VersionThe 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 portionWe 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.// Initialize the leaflet mapconst map = L.map('map');
// Initialize the leaflet mapconst map = L.map('map');
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.// Get the tile layer from OpenStreetMapsL.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 valuemap.setView([48.8584, 2.2945], 16);
// Get the tile layer from OpenStreetMapsL.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 valuemap.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.
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.
// Ask for current location and navigate to that areamap.locate({setView: true, maxZoom: 16});
Showing 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.
// Show a market at the position of the Eiffel Towerlet eiffelMarker = L.marker([48.8584, 2.2945]).addTo(map); // Bind popup to the marker with a popupeiffelMarker.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:
<!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/leaflet@1.6.0/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/leaflet@1.6.0/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:
javascript-map
JavaScript
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Factory method design pattern in Java