block by nitaku 3e007eb2d4f553ce9859

Leaflet with CartoDB tiles

Full Screen

An example that shows a CartoDB layer with Leaflet.js. A lot of different tile services are compatible with Leaflet: click here for a list with live previews.

index.js

// Generated by CoffeeScript 1.10.0
(function() {
  var base_layer, body, height, map, mbAttr, mbUrl, width;

  body = d3.select('body');

  width = body.node().getBoundingClientRect().width;

  height = body.node().getBoundingClientRect().height;

  d3.select('#map').style({
    width: width,
    height: height
  });

  mbAttr = '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>';

  mbUrl = 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';

  base_layer = L.tileLayer(mbUrl, {
    id: 'mapbox.streets',
    attribution: mbAttr
  });

  map = L.map('map', {
    center: [30, 0],
    zoom: 2,
    layers: [base_layer]
  });

}).call(this);

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Leaflet with CartoDB tiles</title>
  <script src="//d3js.org/d3.v3.min.js"></script>
  <script src="//cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
  <link rel="stylesheet" href="//cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
  <link rel="stylesheet" href="index.css">
</head>
<body>
  <div id="map"></div>
  <script src="index.js"></script>
</body>
</html>

index.coffee

body = d3.select 'body'

width = body.node().getBoundingClientRect().width
height = body.node().getBoundingClientRect().height

d3.select('#map')
  .style
    width: width
    height: height

mbAttr = '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>'
mbUrl = 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png'

base_layer = L.tileLayer(mbUrl, {id: 'mapbox.streets', attribution: mbAttr})

map = L.map 'map',
  center: [30, 0],
  zoom: 2,
  layers: [base_layer]

index.css

html, body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

body {
  display: flex;
}

#map {
  flex-grow: 1;
}