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
license: mit |
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
<!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 src="https://d3js.org/d3.v4.min.js"></script> | |
<script> | |
var projection = d3.geoConicConformal().center([2.287592, | |
48.862725 | |
]).scale( | |
10000); | |
var path = d3.geoPath() // d3.geo.path avec d3 version 3 | |
.projection(projection); | |
var tooltip = d3.select('body').append('div') | |
.attr('class', 'hidden tooltip'); | |
function known(d, week) { | |
if (d.properties.tab != undefined) { | |
var val = d.properties.tab[week]; | |
} | |
return val | |
}; | |
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> |