Leaflet.js is one of the most popular mapping libraries. It is a flexible, lightweight, open source JavaScript library for creating interactive maps.
The Leaflet is a framework for rendering map data. The data and base layers must be provided by the developer. Maps consist of slicing layers with browser support, default interactivity, panning, and zooming. You can also add more custom layers and plug-ins, as well as all the mappings in the Leaflet. The map library transforms your data into map layers and provides excellent support, making it the first choice for most developers. It runs well on major desktop and mobile platforms, making it the perfect JavaScript library for mobile and large-screen maps.
In this tutorial, I’ll show you how to create beautiful interactive maps of the South Pacific using HTML, CSS, and Leaflet to highlight the most popular beaches. I collected data from TripAdvisor and compiled the top 10 South Pacific beaches from the young Traveler’s Choice 2021 poll.
Have you ever seen some interesting online maps and wanted to create one yourself? Follow this exciting journey as I show you how to draw a cool map and highlight the top ten beaches using the Leaflet.
Create a basic flyer map in four steps
The process of building a simple map using flyers is simple. Some HTML and JavaScript background is helpful, but don’t worry if you’re a complete beginner. Using this JavaScript library is very simple, and I’ll walk you through every line of code as I create this amazing, insightful map.
Create a basic HTML page
First, I’ll create an HTML page to render the map object. Then I add one to save the map and give it an ID, map, for later reference. Next, I added some style details, where I specified a width and height of 100VW and 100vh. This will make the map take up the entire page:
<! DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Leaflet Map</title> <style type="text/css"> body{ margin: 0; padding: 0; } #map { width: 100vw; height: 100vh; } </style> </head> <body> <div id="map"></div> </body> </html>Copy the code
Refer to the open source Leaflet JavaScript library files
Since I’m using the Leaflet library, I need to include the necessary JavaScript and CSS files for that library. You can download the file directly, install the file locally using JavaScript Package Manager (NPM), or use a managed version in its CDN:
<! DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Leaflet Map</title> <link rel="stylesheet" Href = "https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" /> <style type="text/css"> body{ margin: 0; padding: 0; } #map { width: 100vw; height: 100vh; } < / style > < / head > < body > < div id = "map" > < / div > < script SRC = "https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script> <script> // All the code for the leaflet map will come here </script> </body> </html>Copy the code
Note: This integrity property allows the browser to examine the scripts it has fetched to ensure that the code is not loaded if the source has been manipulated.
To prepare data
To draw any map, I need coordinate values like latitude and longitude. Here I have collated the latitude and longitude of each data point from the site. In addition, for Leaflet development, I needed a base layer from a site called OpenStreetMap.
Set up flyers map
Now it’s time to create the fun part of the map by writing a few lines of code. You won’t believe it takes just a few lines of code to create a fully functional map using the Leaflet. This ease of development, combined with the fact that Leaflet is an open source JavaScript library, puts it near the top of the list of mapping libraries.
So, first of all, remember that everything in this JavaScript library is accessed through the letter “L,” and all functionality is extended through it.
Initialize the map
The first thing I do is declare the map variable and initialize it using Leaflet Map. The first parameter is theta
I used these parameters for my maps, but there are many different options for setting the state of maps, interactions, animations, and events, which you can view here:
Const map = "ap (' map '{center: [29.50, 145], zoom: 3.5});Copy the code
Add base layer
Next, I added the slice layer, which will be the base layer of the Leaflet map. A slice layer is a set of slices accessed via a direct URL request from the server. This slice layer adds geographical boundaries to the map.
Be sure to include attribution text for this, because most developers forget to do this:
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© < a href = "https://www.openstreetmap.org/copyright" > OpenStreetMap < / a > contributors'}) addTo (map);Copy the code
Add a Default tag
I added markers to indicate the beach. The Leaflet provides this function by default. Since I need to display ten beaches, I’ll add a tag, each with a latitude and longitude value for the corresponding beach:
Const marker1 = l.marker ([-37.699450, 176.279420]).addto (map); Const marker2 = l.Marker ([-27.643310, 153.305140]).addto (map); Const marker3 = l.marker ([-33.956330, 122.150270]).addto (map); Const marker4 = l.marker ([-34.962390, 117.391220]).addto (map); Const marker5 = l.marker ([-17.961210, 122.214820]).addto (map); Const marker6 = l.marker ([-16.505960, 151.751520]).addto (map); Const marker7 = l.marker ([-22.594400, 167.484440]).addto (map); Const marker8 = l.marker ([-37.977000, 177.057000]).addto (map); Const marker9 = l.marker ([-41.037600, 173.017000]).addto (map); Const marker10 = l.marker ([-37.670300, 176.212000]).addto (map);Copy the code
Look! An absolutely lovely and useful flyer map is all set up and ready to go. Isn’t this leaflet development a breeze?
The image below shows what it all looks like so far.
You can find the entire code in this Pen:
Custom flyer map
One useful feature of the Leaflet JavaScript library is that it can quickly build basic maps, and it also has a number of options for customizing maps. So let me show you four ways to make this leaflet map more informative and aesthetically pleasing.
1. Disable mouse scrolling and zooming
One of the main problems is accidentally scrolling the map while trying to navigate the page. To deal with this, I changed the code that DECLARED the map in the setup phase. I will add the scrollWheelZoom property and set it to false to ensure that the map can only be scaled using the Zoom button. I’ll also use different ways to set the center and zoom levels that work efficiently and are more readable:
Const map = l.map('map', {scrollWheelZoom:false}).setView([-29.50, 145], 3.5);Copy the code
2. Add layers to the map
Another exciting and useful feature of the Leaflet is the option to add multiple vector layers. Using Street View as one of the layers, I will add another two slice layers to the site that offers the free Web Mapping Service (WMS). I will add a topographic layer and a location layer:
const basemaps = { StreetView: L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: '© < a href = "https://www.openstreetmap.org/copyright" > OpenStreetMap < / a > contributors'}), Topography, L.tileLayer.wms('http://ows.mundialis.de/services/service?', {layers: 'TOPO-WMS'}), Places: L.tileLayer.wms('http://ows.mundialis.de/services/service?', {layers: 'OSM-Overlay-WMS'}) };Copy the code
The Leaflet also provides the ability for the user to control the layers to be rendered. Using this feature, I’ll add an options menu button in the upper right corner of the page that lets you choose which of the three layers you want to overlay on the map:
L.control.layers(basemaps).addTo(map);
Copy the code
Finally, I set the Bottom layer to the default layer to render. In the final version, I will revert to Streetview as the default option:
basemaps.Topography.addTo(map);
Copy the code
3. Customize tags
The default tag is great for indicating location, but custom tags give the map a personalized look and feel and are easy to set using the Leaflet library.
To define an icon, I need to specify the URL and size of the icon. I’ll download a free SVG icon and host it on my GitHub account, which provides the URL. I set the size to 40, but you can keep it more or less.
For now, I’ll simply add this icon to each of the previously defined tags, and that’s it. All markers that indicate a beach are now beach ICONS:
const basicBeachIcon = L.icon({ iconUrl: 'https://raw.githubusercontent.com/shacheeswadia/leaflet-map/main/beach-icon-chair.svg', iconSize: [40, 40], }); Const marker1 = l.marker ([-37.699450, 176.279420], {icon: basicBeachIcon}).addto (map); Const marker2 = l.marker ([-27.643310, 153.305140], {icon: basicBeachIcon}).addto (map); const marker2 = l.Marker ([-27.643310, 153.305140], {icon: basicBeachIcon}).addto (map); Const marker3 = l.marker ([-33.956330, 122.150270], {icon: basicBeachIcon}).addto (map); Const marker4 = l.marker ([-34.962390, 117.391220], {icon: basicBeachIcon}).addto (map); const marker4 = l.Marker ([-34.962390, 117.391220], {icon: basicBeachIcon}).addto (map); Const marker5 = l.marker ([-17.961210, 122.214820], {icon: basicBeachIcon}).addto (map); Const marker6 = l.marker ([-16.505960, 151.751520], {icon: basicBeachIcon}).addto (map); Const marker7 = l.marker ([-22.594400, 167.484440], {icon: basicBeachIcon}).addto (map); const marker7 = l.Marker ([-22.594400, 167.484440], {icon: basicBeachIcon}).addto (map); Const marker8 = l.marker ([-37.977000, 177.057000], {icon: basicBeachIcon}).addto (map); const marker8 = l.Marker ([-37.977000, 177.057000], {icon: basicBeachIcon}).addto (map); Const marker9 = l.marker ([-41.037600, 173.017000], {icon: basicBeachIcon}).addto (map); Const marker10 = l.marker ([-37.670300, 176.212000], {icon: basicBeachIcon}).addto (map);Copy the code
See what this personalized version looks like and use the code on CodePen here.
This icon is just one example, so keep an eye out for a more stylish icon when I change custom tags in the final version of the visualization.
4. Add pop-ups
As with tooltips, pop-ups can contain more information about the data. When clicked, a pop-up window in the map appears, and you can customize it to your liking. To use a Leaflet, you can use a name called bindPopup.
Since we were displaying beaches on the map object, I decided to display the name of each beach in a pop-up window. I just add text to the function and bind it to each tag:
Const marker1 = l.marker ([-37.699450, 176.279420], {icon: basicBeachIcon}) .bindPopup('Whitehaven Beach, Whitsunday Island') .addTo(map); Const marker2 = l.marker ([-27.643310, 153.305140], {icon: basicBeachIcon}) .bindPopup('Turquoise Bay Exmouth, Australia') .addTo(map); Const marker3 = l.marker ([-33.956330, 122.150270], {icon: basicBeachIcon}) .bindPopup('Cape Le Grand National Park Esperance, Australia') .addTo(map); Const marker4 = l.marker ([-34.962390, 117.391220], {icon: basicBeachIcon}) .bindPopup('Greens Pool Denmark, Australia') .addTo(map); Const marker5 = l.marker ([-17.961210, 122.214820], {icon: basicBeachIcon}) .bindPopup('Cable Beach Broome, Australia') .addTo(map); Const marker6 = l.marker ([-16.505960, 151.751520], {icon: basicBeachIcon}) .bindPopup('Matira Beach, Society Islands') .addTo(map); Const marker7 = l.marker ([-22.594400, 167.484440], {icon: basicBeachIcon}) .bindPopup('Piscine Naturelle Ile Des Pins, New Caledonia') .addTo(map); Const marker8 = l.marker ([-37.977000, 177.057000], {icon: basicBeachIcon}) .bindPopup('Ohope Beach Whakatane, New Zealand') .addTo(map); Const marker9 = l.marker ([-41.037600, 173.017000], {icon: basicBeachIcon}) .bindPopup('Kaiteriteri Beach, New Zealand') .addTo(map); Const marker10 = l.marker ([-37.670300, 176.212000], {icon: basicBeachIcon}) .bindPopup('Mt Maunganui Main Beach, New Zealand') .addTo(map);Copy the code
It’s a package! You can find the entire code on CodePen.
Other customization items of Leaflet maps
In addition to what I show you in this tutorial, Leaflet has a number of customization options — such as adding shapes such as circles or polygons, custom pop-ups, and adding events. You can check out the instructions in the official documentation and the numerous examples provided by the Leaflet.
A plug-in opens up an entire realm of customization, and as an open source Leaflet there are many third-party plug-ins that can extend functionality to the original map. You can search here for any plug-ins developed by the Leaflet community. You can use the Leaflet plug-in to add more map blocks, pages, URL templates, PNG images, map block images, advanced zoom options, and enhanced map block interaction. You can also choose to use Google’s API for location and search.
conclusion
As you can see, creating interactive maps using JS libraries such as Leaflet is quick and easy. Installation is worry-free, work is efficient, code is readable, and all mappings are handled easily by the library. It’s also a great choice for creating interactive maps for mobile devices, as it works on all mobile platforms. In addition to excellent usability, Leaflet supports a number of customization options. Please let me know if you have any questions or suggestions.
So take a walk on the beach or start mapping. Both options allow you to relax and have fun activities!
If this article has been helpful to you, don’t forget to give me a triple like, retweet, comment, and we’ll see you next time.
Collection is equal to white piao, praise is true feelings.
Dear friends, if you need JAVA interview documents, please click “like” and “forward”. After following me, I can get free information on 333