CartoDB/Leaflet map that adapts map dimensions (height) and zoom level based on map width. Open in new window and resize to view responsiveness.
forked from maartenzam's block: Responsive map with Cartodb/Leaflet
xxxxxxxxxx
<html>
<head>
<title>Responsive map</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" href="https://libs.cartocdn.com/cartodb.js/v3/3.15/themes/css/cartodb.css" />
</head>
<body>
<div id="map"></div>
<!-- include cartodb.js library -->
<script src="https://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('https://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>
Modified http://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js to a secure url
https://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js