Background map 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

Steps:

  • List of tiles?
    • https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png
    • http://{s}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png
    • http://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png
    • http://{s}.tile.openstreetmap.fr/hot/{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="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js" integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA==" crossorigin=""></script>

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

<style>
#mapid { height: 400px; }
</style>

<script>

// 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 mymap = L
  .map('mapid')
  .setView([50, -0.1], 4);

// Add a tile to the map = a background. Comes from OpenStreetmap
L.tileLayer(
    'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a>',
    maxZoom: 6,
    }).addTo(mymap);


</script>

Related blocks →

  • World Choropleth - link

  • Projection Transitions - link