Background map and tile selector using leaflet.js

This post describes how to build a very basic background map using leaflet.js. We will then be able to use d3.js to add markers, annotation and more on top of this map.

Background map section


  • List of tiles?
    • https://{s}{z}/{x}/{y}.png
    • http://{s}{z}/{x}/{y}.png
    • http://{s}{z}/{x}/{y}.png
    • http://{s}{z}/{x}/{y}.png

  • In this example the world country boundaries are used. Data comes from here. They are provided at geojson format. If you have a shapefile format, visit the background map section to see how to proceed.

  • Note that the geo.projection plugin is used. It allows to represent the world using different projection. See this page of the gallery to see the possibilities.

  • Note: I don't understand the logic behind the .scale part.
<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load Leaflet -->
<link rel="stylesheet" href="" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin=""/>
<script src="" integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA==" crossorigin=""></script>

<!-- Create an element where the map will take place -->
<div id="mapid"></div>

#mapid { height: 400px; }


// Initialize the map
// [50, -0.1] are the latitude and longitude
// 4 is the zoom
// mapid is the id of the div where the map will appear
var map = L
  .setView([50, -0.1], 4);

// Tile type: openstreetmap normal
var openstreetmap = L.tileLayer(
  'https://{s}{z}/{x}/{y}.png', {
  attribution: 'Map data &copy; <a href="">OpenStreetMap</a>',
  maxZoom: 6

// Tile type: openstreetmap Hot
var openstreetmapHot = L.tileLayer(
  'http://{s}{z}/{x}/{y}.png', {
  attribution: 'Map data &copy; <a href="">OpenStreetMap</a>',
  maxZoom: 6

// Tile type: openstreetmap Osm
var openstreetmapOsm = L.tileLayer(
  'http://{s}{z}/{x}/{y}.png', {
  attribution: 'Map data &copy; <a href="">OpenStreetMap</a>',
  maxZoom: 6

//Base layers definition and addition
var allOptions = {
	"Open streetmap": openstreetmap,
  "Open streetmap: Hot": openstreetmapHot,
  "Open streetmap: Osm": openstreetmapOsm

// Initialize with openstreetmap

// Add baseLayers to map as control layers


Related blocks →

  • Leaflet.js multiple basemap tiles example - by Camilo Cruz

  • Basic background with Leaflet - link