The Wayback Machine - https://web.archive.org/web/20240817053502/https://www.geeksforgeeks.org/leafletjs-interacting-with-maps-using-javascript/
Open In App

LeafletJS – Interacting with Maps using JavaScript

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Maps have become an integral part of our everyday lives. From driving to a location to finding some restaurants or stores nearby or while planning travel, almost every type of app uses maps. Using maps helps us to add location-based services in our application.

One way to add maps in a web application is using Leaflet JS. Leaflet JS is an open-source JavaScript library for adding simple and interactive web maps. It can add the map data to the map layers and has features like panning, zooming, etc that most of the applications require. Though leaflet provides some core features required in any map application, an easy way to increase the functionality of maps is using third-party plugins. As leaflet is an open-source library i.e. its source code is available on GitHub, there have been a lot of contributions and there are a lot of plugins available. You can get the list of the plugins here.

So, Leaflet is a map API and it helps us to interact with the map data but it is not providing any data. Nor does it provide the map itself as it is not a mapping service. So how do we get the map? The answer is that Leaflet depends on third parties to provide the basemap i.e Leaflet is built in such a way that it can be used with multiple base map layers. Generally, Leaflet is used with OpenStreetMaps but we can even use other map providers like Mapbox, Ersi, Bing Map Layers, etc. You can check different basemap providers here.

So, let us understand how leaflet can be used to interact with maps step-by-step:

1. The Directory Structure

This is the directory structure that will be followed during this example. You can have a different directory structure as well but make sure it reflects in your code as well.

2. HTML Boilerplate and adding Leaflet References

HTML
<!DOCTYPE html>
<html>

<head>
    <title> Playing Around With Leaflet JS </title>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">

    <!-- Leaflet CSS -->
    <link rel="stylesheet" href=
"https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
        integrity=
"sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
        crossorigin="" />

    <!-- Leaflet JS -->
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
        integrity=
"sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
        crossorigin=""></script>
</head>

<body></body>

</html>

To add map to our web page, simple web technologies like HTML, CSS and JavaScript are required. To use Leaflet in your code, you need to add the Leaflet CSS and Leaflet JS. You can either download them or use them by including their CDNs (see above code sample).

3. Create a Map container and create a Map object

<div id="mymap"> </div>

We first define a container element where we want to load the map and provide it an id “mymap”.

let map = L.map('mymap').setView([19.5937, 78.9629], 5);

Now, we create a map object using which we’ll create a map and manipulate it. We instantiate the map object with the id of the container element created above i.e. “mymap”. The setview method is used to set the center of the map and the zoom level.

4. Add Map Tiles using TileLayer

JavaScript
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; OpenStreetMap contributors',
    maxZoom: 20,
    minZoom: 2,
    tileSize: 512,
    zoomOffset: -1
}).addTo(map);

To load and display our map, we use TileLayer class to create a layer and specify the URL of the map tiles. The map is divided into multiple tiles and we are using OpenStreetMap for displaying the map tiles. You can get the list of tile providers here. We do specify some additional parameters like min zoom level, max zoom level, tile size. As we are using the map tiles of OpenStreetMap, we need to provide proper attribution (or credits) to OpenStreetMap (or whichever map tile provider you are using) for using their map tiles. To add this layer on our map, we use the addTo() method. 

5. Making our dataset for including markers

https://github.com/OptimalLearner/Leaflet-JS-Example-Code/blob/master/assets/location-data.json

Now, we need to add some markers to the map which point to some location. We have saved the data in a different file named “location-data.json”. This file contains the marker details like latitude and longitude coordinates, etc.  You can access the data from the above link provided and save it along with your code. If you want to keep the data in your JS file itself, you can create a variable and assign it to the above data.

6. Creating marker, binding popups and event handling

JavaScript
let marker = L.marker([latitude, longitude]).bindPopup(`<h3> ${title} </h3> 
<p> ${description} </p>
`).on('click', () => {
    map.flyTo([latitude, longitude], zoomLevel);
}).addTo(map);

A marker is used to identify and highlight a location on a map. To add a marker in Leaflet, we initialize the marker class and pass the coordinates of the location we need the marker to point to. You may add as many markers as you want. Now to identify which location is marked by the marker, we can add a popup to the marker which will tell us the location information. We add a popup using bindPopup method to display the location name and a little description of the location.

Leaflet also has the ability to react to events generated by us. We can add an event listener using “on” function for a particular event (in our case “click”) which listens to a function containing some set of operations. At the end, we add this marker to our map.

7. Customizing the marker icon

JavaScript
let iconOption = {
    iconUrl: './assets/location-marker.svg',
    iconSize: [30, 30]
};
let ourCustomIcon = L.icon(iconOption);

let marker = L.marker([latitude, longitude], 
  {icon: ourCustomIcon}).bindPopup(`<h3> ${title} </h3> 
<p> ${description} </p>
`).on('click', () => {
    map.flyTo([latitude, longitude], zoomLevel);
}).addTo(map);

Not everyone would like to use the same default marker icon. So, here comes the feature of custom marker icons to the rescue. You need to use the Icon class and pass the URL of the icon which you want to use as the marker and add the size of icon [width, height] in pixels(px). Now we need to add the icon to the marker. In the Marker class after adding the coordinates, we can pass the custom marker icon for rendering the marker.

8. What’s best for you: flyTo or setView?

JavaScript
map.setView([latitude, longitude], zoomLevel);
map.flyTo([latitude, longitude], zoomLevel);

Both are doing the same work of changing the location to specific coordinates but flyTo() method provides some animation that will fly to the location specified using coordinates. If you need some animation then you can use flyTo() method else setView() also works to change the location.

There is another method called panTo([latitude, longitude]) which is just calling setView() keeping the zoom level to current map’s zoom level. setView() method allows you to even set the zoom level but that’s not the case with panTo().

9. Complete Code and Result

HTML
<!DOCTYPE html>
<html>

<head>
    <title> Playing Around With LeafletJS </title>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
        
    <!-- Leaflet CSS -->
    <link rel="stylesheet" href=
        "https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
        integrity=
"sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
        crossorigin="" />

    <!-- Leaflet JS -->
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
        integrity=
"sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
        crossorigin=""></script>
        
    <!-- Custom Styles -->
    <link rel="stylesheet" type="text/css" href="css/styles.css">
</head>

<body>
    <h2 class="heading"> Some Indian Monuments </h2>
    <div id="mymap"> </div>
    <div class="button-group flex-style">
        <div class="component1">
            <button class="map-zoom-out-btn">Map Zoom Out</button>
        </div>
        <div class="component2">
            <select class="select-dropdown" name="dropdown">
                <option> Select any monument </option>
            </select>
            <button class="search-btn"> Search </button>
        </div>
    </div>
    <footer class="footer flex-style"> Made Using Leaflet JS | 
        <a href=
"https://github.com/OptimalLearner/Leaflet-JS-Example-Code" 
            target="_blank"> Source Code</a> <a href=""
            target="_blank"> <img src="assets/github-icon.png" /> 
        </a> 
    </footer>

    <script type="text/javascript" src="js/script.js"></script>
</body>

</html>
CSS
body {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: sans-serif;
}
.heading {
    font-family: monospace;
    font-size: 40px;
    text-align: center;
    margin: 2.5vh 0;
}
#mymap {
    width: 90vw;
    height: 70vh;
    margin: 0 5vw 2vh;
    border: 3px solid #888;
}
.button-group {
    justify-content: space-evenly !important;
}
.map-zoom-out-btn, .search-btn {
    background-color: #0072B5;
    color: #FFF;
    padding: 10px 35px;
    border: none;
    font-size: 17px;
    border-radius: 5px;
    cursor: pointer;
}
.select-dropdown {
    display: inline-block;
    margin: 0 15px 0 0;
    padding: 10px 35px;
    border: 1px solid #AAA;
    font: inherit;
    -webkit-appearance: none;
    -moz-appearance: none;
    -ms-appearance: none;
    appearance: none;
    background: #FFF;
    background-repeat: no-repeat;
    background-image: 
        linear-gradient(45deg, transparent 50%, currentColor 50%), 
        linear-gradient(135deg, currentColor 50%, transparent 50%);
    background-position: right 15px top 1em, right 10px top 1em;
    background-size: 5px 5px, 5px 5px;
}
.footer {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    font-size: 17px;
    padding-bottom: 8px;
}
.footer a {
    padding: 0 5px 0 5px;
    color: #000;
    cursor: pointer;
}
.flex-style {
    display: flex;
    justify-content: center;
    align-items: center;
}
JavaScript
let map = L.map("mymap").setView([19.5937, 78.9629], 5);
let ourData = [];

L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  attribution: "&copy; OpenStreetMap contributors",
  maxZoom: 20,
  minZoom: 2,
  tileSize: 512,
  zoomOffset: -1,
}).addTo(map);

let iconOption = {
  iconUrl: "./assets/location-marker.svg",
  iconSize: [30, 30],
};
let ourCustomIcon = L.icon(iconOption);

fetch("./assets/location-data.json")
  .then((response) => response.json())
  .then((data) => {
    ourData = data;
    for (let i = 0; i < data.length; i++) {
      let option = document.createElement("option");
      option.value = i + 1;
      option.text = data[i].title;
      document.querySelector(".select-dropdown").appendChild(option);

      let marker = L.marker([data[i].latitude, data[i].longitude], {
        icon: ourCustomIcon,
      })
        .bindPopup(
          `<h3> ${data[i].title} </h3> 
<p> ${data[i].description} </p>
`
        )
        .on("click", () => {
          map.flyTo([data[i].latitude, data[i].longitude], data[i].zoomLevel);
        })
        .addTo(map);
    }
  })
  .catch((error) => alert(error));

document.querySelector(".map-zoom-out-btn").addEventListener("click", () => {
  map.flyTo([19.5937, 78.9629], 5);
});

document.querySelector(".search-btn").addEventListener("click", () => {
  let select = document.querySelector(".select-dropdown");
  let value = select.options[select.selectedIndex].value;
  map.flyTo(
    [ourData[value - 1].latitude, ourData[value - 1].longitude],
    ourData[value - 1].zoomLevel
  );
});

Using the HTML Boilerplate, we have added a map container, a button for zooming out the map, and a dropdown that will contain the locations marked on the map. We have applied some styles to our components using external CSS by adding references to the external style sheet. In the script file, we create a map object and add map tiles to the object. Then we create our custom icon object and add the size and the URL of the icon to the icon options which we will add to the marker while creating the marker for each location.

Using Fetch API, we request our data by providing the URL of data. We get the response object which is then converted to json. Using this json data which contains the information about locations, we dynamically add the options for the locations to the dropdown list using DOM and we create markers for every location along with popups and onclick event listener. In case of any errors, the error message is alerted to the user.

We added an onclick event listener on the Zoom Out button which flies us to the initial coordinates and zoom level. We also added an event listener on the Search button which gets the value of the dropdown list and using the value we select the location and zoom the map to that selected location.

The result of the above example can be seen below:

To run your webpage locally, you need to run the webpage through local server. You can either use WAMP or XAMPP or simpleNode.js http-server. If you get stuck somewhere in between, you can refer this GitHub Repository.



Similar Reads

What is the use of the Get method in Maps in JavaScript ?
In JavaScript, the get() method is used with Map objects to retrieve the value associated with a specific key. The key is passed as an argument to the get() method, and the method returns the corresponding value if the key is found. If the key is not present in the Map, undefined is returned. Syntax:myMap.get(key);myMap: The Map from which you want
1 min read
What is the use of the Map.prototype.clear method in JavaScript Maps ?
In JavaScript, the Map.prototype.clear method is used to remove all key-value pairs from a Map, effectively making the Map empty. It does not take any arguments and does not return any value. Syntax:myMap.clear();myMap: The Map from which you want to remove all key-value pairs.Example: Here, a map object “myMap” has been created with a single [key,
1 min read
What is the use of the Map.prototype.keys method in JavaScript Maps ?
In JavaScript, the Map.prototype.keys method is used to get an iterator object that contains the keys of a Map. The iterator object follows the iterable protocol, allowing you to loop through the keys using methods like next() or using a for...of loop. Syntax:myMaps.key();myMap: The Map for which you want to obtain an iterator for its keys.Example:
1 min read
Top 10 JavaScript Libraries for Creating Interactive Maps
Have you ever been curious about how to make those extraordinary maps on websites that you can tap and interact with? It is all about using JavaScript libraries. Nowadays, maps are a core part of web development, offering clients responsive ways to explore and interact with information. In this article, we are going to explore in depth into the bes
9 min read
JavaScript Program to Combine Values of Two Maps having Same Key
In this article, we are going to learn about combining the values of two maps having the same keys in JavaScript, Combining values of two maps with the same key involves merging corresponding values from each map, creating a new map that retains unique keys while accumulating shared values. There are different approaches to Combining the values of
4 min read
Less.js Maps-Using variable variables in lookups
LESS is a preprocessor of CSS that provide it with some more features to work and with the help of that, we can write more efficient CSS code. Let us have brief information about the lookups, it's just a pair of capital brackets [@lookups], the content inside the bracket is called lookups which are basically variables. Note that the value inside th
2 min read
Developing a Budget Travel Planner using React and Interactive maps (Mapbox)
The Budget Travel Planner app is an app that aids users in planning and managing their trips within a specified budget. It helps users curate their bookings of flights, hotels, transport, etc., and also develop a schedule/itinerary to follow for their trip. This project makes use of ReactJS, Sass, and Mapbox API to come up with a beautiful frontend
15+ min read
Using Leaflet.js to show maps in a webpage
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.
6 min read
Explain source maps in jQuery
Source maps are a powerful tool for debugging and troubleshooting code, particularly when working with large or complex codebases. They allow developers to easily understand the relationships between the original, unminified code and the compiled or minimized code that is actually running in the browser. In other words, source maps provide a way to
6 min read
Google Maps | Types
To customize the Google map, there are four types of maps provide. ROADMAP: This type of map shows the street view of the specific area. It is the default type map. SATELLITE: This type of map shows the satellite images of the specific area. HYBRID: This type of map shows the major streets of the specific area. TERRAIN: This type of map shows the t
3 min read
Google Maps | Localization
The localization is a process to provide information in different languages. The default language is English in google maps. All the information provided in English like; city, option names, road, etc. To customize or localize the maps mention the language while loading the google maps API. Syntax: &lt;script src= "https://maps.googleapis.com/maps/
1 min read
Google Maps | Zoom
The Zoom attribute is used to increase or decrease the zoom level on a specific point in maps. To customize the zoom level change the zoom value. The default value of zoom is 10. Syntax: var CustomOp = { zoom:zoom value }; Example 1: This example sets the zoom level at 10. &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt; Google Maps |
2 min read
Google Maps Markers
The process of drawing objects on the map and bind them to a desired latitude and longitude is called overlays. Various overlays Google Maps provides. MarkersPolylinesPolygonsCircle and rectangleInfo windowSymbols Google Maps markers are provided to mark a single location on the map. These markers use a standard symbol that is customizable. Syntax:
2 min read
Google Maps Info Windows
Google Maps Info Windows is used to add a window to display the information of the specific area. Usually, the info window is attached to a marker. You can attach an info window by instantiating the google.maps.InfoWindow class. Syntax: var infowindow = new google.maps.InfoWindow({content: "Content String"}); infowindow.open(map, marker); Property
2 min read
How to make image maps in HTML5 ?
The HTML &lt;map&gt; tag is used to define image maps in HTML. The areas inside the image which are clickable are defined by using the &lt;area&gt; tag. The main idea of this concept is that whenever we click on the image it should perform any action. For creating an image map we have to add usemap as an attribute to the &lt;img&gt; tag. Syntax:
1 min read
Semantic-UI Icon Set Maps
Semantic UI is an open-source development framework that provides pre-defined classes to make our website look beautiful, amazing, and responsive. It is similar to Bootstrap which has predefined classes. It uses jQuery and CSS to create the interfaces. It can also be directly used via CDN like bootstrap. Semantic UI provides the users with various
14 min read
How To Add Google Maps With A Marker to a Website
Google Maps is a web mapping service developed by Google. It offers satellite imagery, street maps, 360° panoramic views of streets (Street View), real-time traffic conditions (Google Traffic), and route planning for traveling by foot, car, bicycle (in beta), or public transportation. To add a Google Maps with a marker on a website there are three
3 min read
Google Maps Introduction
Google Maps is a web mapping service developed by Google, that provides interactive maps and satellite imagery. Users can find locations, get directions, view street-level imagery, and explore businesses and points of interest worldwide. Also, we can get the traffic information of a specific area or view street-level images of cities. Google Maps h
2 min read
How to Add Google Maps to a Website ?
Integrating Google Maps into a website is a common and useful feature. We can use Google Maps API to add it to our website. Follow the below steps to Add Google Maps to a Website1. Generate/Obtain Google Maps API KeyTo fetch the location data from Google Maps first we need a Google Maps API Key. It is required to authorize the collection of the dat
3 min read
Introduction to JavaScript Course - Learn how to build a task tracker using JavaScript
This is an introductory course about JavaScript that will help you learn about the basics of javascript, to begin with, the dynamic part of web development. You will learn the basics like understanding code structures, loops, objects, etc. What this course is about? In this course we will teach you about the basics of the scripting language i.e) Ja
4 min read
How to compare two JavaScript array objects using jQuery/JavaScript ?
In this article, we are given two JavaScript array/array objects and the task is to compare the equality of both array objects. These are the methods to compare two JavaScript array objects: Using jQuery not() methodUse the sort() functionUse JSON.stringify() functionUsing every() and indexOf()Using Lodash _.isEqual() MethodApproach 1: Using jQuery
3 min read
How to Delay a JavaScript Function Call using JavaScript ?
When we want to call a function after a described amount of time, we use a delay function in JavaScript. There are several ways to delay the execution of a function. This can be useful for various purposes, such as creating animations, implementing debounce in search inputs, or simply delaying an action until a certain condition is met. Table of Co
2 min read
JavaScript Program to find Length of Linked List using JavaScript
Given a linked list, the task is to determine its length using various methods. The linked list is a fundamental data structure consisting of nodes connected in a chain, offering efficient data organization. Different approaches, including Iterative and Recursive Methods, enable us to compute the length of a linked list easily. Use the below approa
3 min read
Largest Rectangle Area under Histogram using JavaScript | Without using Stacks
Find the largest rectangular area possible in a given histogram where the largest rectangle can be made of a number of contiguous bars. For simplicity, assume that all bars have the same width and the width is 1 unit. For example, consider the following histogram with 7 bars of heights {6, 2, 5, 4, 5, 1, 6}. The largest possible rectangle possible
2 min read
JavaScript Course Understanding Code Structure in JavaScript
Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used to add JavaScript in HTML are &lt;script&gt; and &lt;/script&gt;. The code surrounded by the &lt;script&gt; and &lt;/script&gt; tags is called a script blog. The 'type' attribute was the most important attribute of &lt;script&gt; tag. However, it is no
4 min read
JavaScript Course Loops in JavaScript
Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. For example, suppose we want to print “Hello World” 10 times. Example: In this example we will print the same things, again and again, to understand the work of Loops. &lt;script&gt; cons
4 min read
JavaScript Course Logical Operators in JavaScript
logical operator is mostly used to make decisions based on conditions specified for the statements. It can also be used to manipulate a boolean or set termination conditions for loops. There are three types of logical operators in Javascript: !(NOT): Converts operator to boolean and returns flipped value &amp;&amp;:(AND) Evaluates operands and retu
3 min read
JavaScript Course What is JavaScript ?
JavaScript is a very famous programming language that was originally started in the year of 1995 with the motive of making web pages alive. It is also an essential part of the web developer skillset. In simple terms, if you want to learn web development then learn HTML & CSS before starting JavaScript. HTML: HTML is used to create the structure of
3 min read
JavaScript Course Operators in JavaScript
An operator is capable of manipulating a certain value or operand. Operators are used to performing specific mathematical and logical computations on operands. In other words, we can say that an operator operates the operands. In JavaScript, operators are used for comparing values, performing arithmetic operations, etc. There are various operators
7 min read
JavaScript Course Functions in JavaScript
Javascript functions are code blocks that are mainly used to perform a particular function. We can execute a function as many times as we want by calling it(invoking it). Function Structure: To create a function, we use function() declaration. // Anonymous function function(){ // function...body } // function with a name function displayMessage(){
4 min read
three90RightbarBannerImg