How to Create an Interactive Map With Mapbox and Leafletjs

Published: | Last Edited:
Category: tech


Recently I created an interactive map page of all the places that I visited. This post provides an overview of how to create such interactive map.


List of libraries that I used:

First thing we need to do is obtain an access token by signing up for Mapbox. Once you have the token, we are ready to build our first map.

Basic Map with Data Source

Add leafletjs by including these in the head of your HTML code:

<link rel="stylesheet" href=""
<script src=""

Add a div tag to the body of HTML code:

<div id='map' style="width:100%; height:100vh;"></div>

Render a map with some overlay. The overlay data are GeoJSON. We will use a sample data (custom.geo.js) as a demonstration.

<script src="" type="text/javascript"></script> // load geojson data
<script type="text/javascript">

var geojson = L.geoJson(countries).addTo(map);
var map ='map').setView([0, 0], 2);
L.tileLayer('{id}/{z}/{x}/{y}.webp?access_token={accessToken}', {
  maxZoom: 18,
  attribution: 'Map data &copy; <a href="">OpenStreetMap</a> contributors, ' +
    '<a href="">CC-BY-SA</a>, ' +
    'Imagery © <a href="">Mapbox</a>',		
  id: 'mapbox.streets-basic',
  accessToken: // Paste your mapbox access token here

Here is how it looks in action:

See the Pen Basic Map by Jason Thai (@zirius-the-reactor) on CodePen.

Custom Styling and Interaction

Define a style for our custom overlay with a random fillColor

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  return color;

function style(feature) {
    return {
        fillColor: getRandomColor(),
        weight: 2,
        opacity: 1,
        color: 'white',
        fillOpacity: 0.7
var geojson = L.geoJson(countries, {style: style}).addTo(map);

Add interactions to our map by displaying the color of the areas when we click on them.

geojson.eachLayer(function (layer) {
    layer.bindPopup('<p style="color:' + layer.options.fillColor + '">'  + +'</p>');

Voila! Try clicking on the map and see the result! Now the map looks like this:

See the Pen Basic Map with Color by Jason Thai (@zirius-the-reactor) on CodePen.



Here we create a sample map with interactions using Mapbox and Leafletjs. I encourage everyone to try out and make new maps with your own twist. Looking forward to seeing what you make!

Next Post: Thoughts on Being Multilingual
Previous Post: How to Create a Secure Password