Without using Google Maps!
Photo by KOBU Agency on Unsplash
Adding an interactive map to your website can make it look more polished and also contribute to the user experience.
Maps can be added alongside an address as well as on the landing page to convey geographical information.
To add free, quick interactive maps we would be using Leaflet.js which is an open-source library for touch-friendly maps.
The size of the package is about 40kb and includes a comprehensive set of map features.
Installation
To install the library, we need to add a few things to the head section of our HTML file.
- CSS file
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin=""/>
- Leaflet JavaScript file (Should be placed after the above CSS file)
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
integrity="sha512-
XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin=""></script>
That’s all the files we needed to add.
Now we can element to help display the map. You can provide a unique ID to the div element.
This element would be used to display the map.
Also, make sure the element has a height property such as given below:
<div id="htmlmap" style="height:50vh"></div>
In this article, we will be using Mapbox to get apt tile layers. However, to get the tile layer, we need an access token (which is free to obtain). You can create an account and get the access token by going here.
Additionally, I will also be adding my custom CSS file as well as an index.js file.
The final HTML file should look something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Map Website</title>
<link rel="stylesheet"
href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
integrity="sha512-
xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin="" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
integrity="sha512-
XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin=""></script>
<link rel="stylesheet" href="./style.css" />
<script defer src="./index.js"></script>
</head>
<body>
<div id="htmlmap" style="height:50vh"></div>
</body>
</html>
Initialization
In your index.js file, we just need to initialize the map by using the following code:
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
The setView
method returns a map object. The first argument is an array containing the coordinates of the place you wish to display on the map and 13 is the zoom level.
This isn’t all though.
We need to add a tile layer to our map. As stated before, we will be using Mapbox to get the tile layer.
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution:
'Map data ©
<a href="https://www.openstreetmap.org/">OpenStreetMap</a>
contributors,
<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1,
accessToken:"your access token goes here"
}).addTo(mymap);
The first argument in the tileLayer
is the URL of the tile layer while the second argument is an object containing the properties.
As you can see, you need to pass your Mapbox access token as a string to the property ‘accessToken’.
You have an interactive map now!
Source: Author
Marker and Circle
Adding a marker is very easy.
Like the initialization of the map, we need to initialize the map with the coordinates and then use the addTo
method to add to our map.
The same goes for the circle.
var marker = L.marker([51.5, -0.09]).addTo(mymap);
var circle = L.circle([51.508, -0.11], {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5,
radius: 500
}).addTo(mymap);
You can customize the icons of the marker as well!
var greenIcon = L.icon({
iconUrl: 'leaf-green.png',
shadowUrl: 'leaf-shadow.png',
iconSize: [38, 95], // size of the icon
shadowSize: [50, 64], // size of the shadow
iconAnchor: [22, 94], // icon location
shadowAnchor: [4, 62], // the same for the shadow
popupAnchor: [-3, -76] // point from which the popup should //open relative to the iconAnchor
});
L.marker([51.5, -0.09], {icon: greenIcon}).addTo(map);
Source: Author
Events
To perform some operation every time the user interacts with the map, you can use the onMapClick
function which gets an event object every time something happens to the map.
You can use this to display important messages or run some code in the background.
In the example below, we have used the function to show a popup to the user.
var popup = L.popup();
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(mymap);
}
mymap.on('click', onMapClick);
We have used the event object to get the latitude and longitude using the latlng
which we have used to display the popup to inform the user of the coordinates of the place he has clicked on.
If you log the event, you will find all the properties it holds.
The event object. Source: Author
Satellite Map
Switching to the satellite view, you literally just need to change one single line of code.
Source: Author
We need to change the ‘id’ property when we initialize the map from ‘mapbox/streets-v11’ to ‘mapbox/satellite-v9’.
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: 'mapbox/satellite-v9',
tileSize: 512,
zoomOffset: -1,
accessToken: 'your token'
}).addTo(mymap);
Conclusion
Adding a map enhances the accessibility of your site as well as create a good, reputable first impression.
Leaflet.js provides an easy way to add beautiful, interactive maps to your website for free and quickly.
Besides this, you also get access to a lot of features and tools. The official guide covers all these aspects in great depth.