How To Add Interactive Maps In HTML Using Leaflet?

Most of the websites require Map features to be integrated and adding interactive maps can greatly boost the user experience and provide valuable information for your website.

One such popular Javascript library that provides this feature is Leaflet which helps in creating interactive maps easily. This blog will guide you on how we can add maps in our website using Leaflet.

Steps To Add Map Using Leaflet

  • First, we need to include the Leaflet library in your project. The leaflet can directly be included using CDN itself to access its functionality.
  • Add the CSS for Leaflet using the <link> tag in the head section
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"      integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="      crossorigin=""/>
Code language: HTML, XML (xml)
  • Add the Javascript for Leaflet as well in the <script> tag
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"      integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo="      crossorigin=""></script>
Code language: HTML, XML (xml)
  • Now create a container in your HTML where you want to show the map. We can use <div> tag for the same and give it an id say ‘mapid’.
<body>      <div id="mapid"></div> ... ... ... </body>
Code language: HTML, XML (xml)
  • Next, we will write a script to initialize the Leaflet instance to display the map.
let mapInstance = L.map("mapid", {        center: [28.5, 77.1],        zoom: 10,      });
Code language: JavaScript (javascript)

In the above code, L  is used to refer to the leaflet library. We are using the .map() function to initialize the Leaflet map, providing the ID of the container in which we need to display the map, the latitude and longitude of the center point of the map, and the zoom level.

  • After this, we need to add the tile layer in order to actually display the map.
L.tileLayer(        "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",        {          attribution:            '&copy; OpenStreetMap contributors',          maxZoom: "19",        }      ).addTo(mapInstance);
Code language: JavaScript (javascript)

We can use various other tile providers to add the tile layer. In the above example, we have used the OpenStreetMap tile provider that adds a tile layer and added the map instance we created. The {z},{x},{y} and {s} are different placeholders for zoom level, coordinates, and subdomain required for the tile layer.

That is it, now run your project and you’ll be able to see the map at the respective mapid div position.

Now we might want to add a marker to show some important locations according to our project.

And we might want to delete a marker as well.

To add or delete a marker using a leaflet, follow the below steps.

Steps To Add The Markers On the Map

  • To add a marker, we will be using the marker() function of Leaflet.

But before that, there might be an issue that the marker icon is not being displayed.

For that add the following code before adding a marker. This will resolve the issue.

delete L.Icon.Default.prototype._getIconUrl;        L.Icon.Default.mergeOptions({        iconRetinaUrl: require("leaflet/dist/images/marker-icon-2x.png"),        iconUrl: require("leaflet/dist/images/marker-icon.png"),        shadowUrl: require("leaflet/dist/images/marker-shadow.png"),      });
Code language: CSS (css)
  • To add the marker, create an array named markers. Make the scope of this array such that it can be accessed in both add and remove markers functions.
var markers = [];
Code language: JavaScript (javascript)
  • Create an array of latitudes and longitudes and the name of that location.
var locations = [  ["LOCATION_1", 22.8166, 77.0942],  ["LOCATION_2", 22.9804, 77.9189],  ["LOCATION_3", 22.7202, 77.5621],  ["LOCATION_4", 22.3889, 77.6277],  ["LOCATION_5", 22.5929, 77.6325] ];
Code language: JavaScript (javascript)
  • Now add a for loop on the array provided and add a marker on each of the location
for (var i = 0; i < this.locations.length; i++) {        let marker = new L.marker([          this.locations[i][1],          this.locations[i][2],        ])          .bindPopup(this.locations[i][0])          .addTo(mapInstance);          markers.push(marker);      }
Code language: JavaScript (javascript)

In the above code, we used the marker() function to add the markers on the map and iterated through the locations array.

The bindPopup is used to display the name of the location whenever the user clicks on the marker of that location.

The add () function will tell that the marker belongs to the Leaflet map instance named mapInstance declared at the start.

Lastly, we pushed the marker into the markers array. This will be used when you want to delete the markers.

Step to delete the Markers

  • To delete the marker, we will use the markers array we defined in the above section.
  • We will iterate through the markers array and remove the marker.
for(var m = 0; m < this.markers.length; m++){      this.map.removeLayer(this.markers[m]);      }
Code language: JavaScript (javascript)

In the above code, we used the removeLayer() function that will remove all the markers.

Conclusion

This is it. I hope you learned how to integrate interactive maps using the leaflet library. The leaflet is a beginner-friendly package that helps in adding maps in very easy steps.

This blog helps in understand how we can initialize a map using Leaflet. It also guides on adding and deleting the markers on the map created. Go ahead and use this easy-to-embed feature in your projects and enhance your user experience. You can explore further on Leaflet’s official documentation which provides various other options to customize your map and add other features.

Recent Post

  • Future Trends in AI Chatbots: What to Expect in the Next Decade

    Artificial Intelligence (AI) chatbots have become indispensable across industries. The absolute conversational capabilities of AI chatbots are enhancing customer engagement, streamlining operations, and transforming how businesses interact with users. As technology evolves, the future of AI chatbots holds revolutionary advancements that will redefine their capabilities. So, let’s start with exploring the AI chatbot trends: Future […]

  • Linguistics and NLP: Enhancing AI Chatbots for Multilingual Support

    In today’s interconnected world, businesses and individuals often communicate across linguistic boundaries. The growing need for seamless communication has driven significant advancements in artificial intelligence (AI), particularly in natural language processing (NLP) and linguistics. AI chatbots with multilingual support, are revolutionizing global customer engagement and service delivery. This blog explores how linguistics and NLP are […]

  • How Reinforcement Learning is Shaping the Next Generation of AI Chatbots?

    AI chatbots are no longer just about answering “What are your working hours?” or guiding users through FAQs. They’re becoming conversation partners, problem solvers and even reporting managers and sales agents. What’s driving this transformation? Enter Reinforcement Learning (RL)—a type of machine learning that’s changing the way chatbots think, learn, and respond. At Codalien Technologies, […]

  • AI Chatbots for Sales Team Automation: The Critical Role of AI Sales Assistants in Automating Your Sales Team

    Sales teams are the heart of any successful business, but managing them effectively can often feel like trying to juggle flaming swords. The constant pressure to generate leads, maintain relationships, and close deals leaves your team overwhelmed, spending more time on administrative tasks than actual selling. Here’s where AI-powered sales assistants step in to completely […]

  • Transforming HR with AI Assistants: The Comprehensive Guide

    The role of Human Resources (HR) is critical for the smooth functioning of any organization, from handling administrative tasks to shaping workplace culture and driving strategic decisions. However, traditional methods often fall short of meeting the demands of a modern, dynamic workforce. This is where our Human Resource AI assistants enter —a game-changing tool that […]

  • How Conversational AI Chatbots Improve Conversion Rates in E-Commerce?

    The digital shopping experience has evolved, with Conversational AI Chatbots revolutionizing customer interactions in e-commerce. These AI-powered systems offer personalized, real-time communication with customers, streamlining the buying process and increasing conversion rates. But how do Conversational AI Chatbots improve e-commerce conversion rates, and what are the real benefits for customers? In this blog, we’ll break […]

Click to Copy