Skip to content

Instantly share code, notes, and snippets.

@maartenzam
Last active July 19, 2017 12:34
Show Gist options
  • Save maartenzam/7ef773bdf11999c9eebb to your computer and use it in GitHub Desktop.
Save maartenzam/7ef773bdf11999c9eebb to your computer and use it in GitHub Desktop.
Responsive map with Cartodb/Leaflet

CartoDB/Leaflet map that adapts map dimensions (height) and zoom level based on map width. Open in new window and resize to view responsiveness.

<!DOCTYPE html>
<html>
<head>
<title>Responsive map</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/3.15/themes/css/cartodb.css" />
</head>
<body>
<div id="map"></div>
<!-- include cartodb.js library -->
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js"></script>
<script>
function main() {
var bigmapheight = 650;
var smallmapheight = 300;
var mapbreakwidth = 720;
var highzoom = 8;
var lowzoom = 7;
var initzoom;
var vizjson = 'https://mediafin.cartodb.com/api/v2/viz/6a800846-5607-11e5-b2d0-0e4fddd5de28/viz.json';
//Set initial mapheight, based on the calculated width of the map container
if ($("#map").width() > mapbreakwidth) {
initzoom = highzoom;
$("#map").height(bigmapheight);
}
else {
initzoom = lowzoom;
$("#map").height(smallmapheight);
};
var map = new L.Map('map', {
center: [50.45,4.45],
zoom: initzoom
});
L.tileLayer('http://tile.stamen.com/toner/{z}/{x}/{y}.png', {
attribution: 'Stamen'
}).addTo(map);
cartodb.createLayer(map, vizjson)
.addTo(map)
.on('done', function(layer) {
layer.setInteraction(true);
layer.on('error', function(err) {
cartodb.log.log('error: ' + err);
});
})
.on('error', function() {
cartodb.log.log("some error occurred");
});
//Use Leaflets resize event to set new map height and zoom level
map.on('resize', function(e) {
if (e.newSize.x < mapbreakwidth) {
map.setZoom(lowzoom);
$("#map").css('height', smallmapheight);
};
if (e.newSize.x > mapbreakwidth) {
map.setZoom(highzoom);
$("#map").css('height', bigmapheight);
$("#map").css('height', bigmapheight);
};
});
}
// you could use $(window).load(main);
window.onload = main;
</script>
</body>
</html>
@maartenzam
Copy link
Author

CartoDB map that adapts map dimensions (height) and zoom level based on map width.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment