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.


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

// Tile type: openstreetmap normal
var 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
})

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

// Tile type: openstreetmap Osm
var openstreetmapOsm = L.tileLayer(
  'http://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png', {
  attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">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
openstreetmap.addTo(map);

// Add baseLayers to map as control layers
L.control.layers(allOptions).addTo(map);

</script>

Related blocks →

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

  • Basic background with Leaflet - link