All pages on this website are written by myself, (C) Peter Thomson. I am a real person, not AI.
Leaflet map tutorial - how to change the image displayed on zoom
pageid = 5338 parentid = 7710We can extend this simple image display to change the image as we zoom in or out. In this next example we have two images, one showing flowers in close focus and one with the mountains behind in distant focus. As we zoom the image we can switch the focus from one image to the other.
This frame shows a live view of the map we are creating:
The HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="leaflet.css" />
<title>Swapping between images on zoom with leaflet</title>
<script type='text/javascript' src='leaflet.js'></script>
</head>
<body>
<h1>Swapping between images on zoom with leaflet</h1>
<div id="image-map" style="width: 1152px; height: 864px; border: 1px solid #AAA;"></div>
<script>
var map = L.map('image-map', {
minZoom: 1,
maxZoom: 4,
center: [0, 0],
zoom: 1,
maxBoundsViscosity: 1,
crs: L.CRS.Simple
});
//zoom 4 full size image is 4608px * 3456 px
//zoom 3 2304 * 1728
//zoom 2 1152 * 864
//zoom 1 576 * 432
var diagramLayerGroup = new L.LayerGroup();
var midimage= L.imageOverlay("P1100060.JPG", [[0,0],[432,576]]);
var nearimage= L.imageOverlay("P1100059.JPG", [[0,0],[432,576]]);
var imgset = 'near';
diagramLayerGroup.addLayer(nearimage);
var markerGroup = diagramLayerGroup.addTo(map);
// tell leaflet that the map is exactly as big as the image
map.setMaxBounds(new L.LatLngBounds([0,0], [432,576])); // prevent panning outside the image area
map.on('zoomend', function(){
var z = map.getZoom();
console.log('zoom = ' + z + imgset);
if (z > 3 && imgset == 'near') {
diagramLayerGroup.clearLayers();
diagramLayerGroup.addLayer(midimage);
var markerGroup = diagramLayerGroup.addTo(map);
imgset='middle';
console.log('set middle = ' + z + imgset);
return;
}
if (z <2 && imgset == 'middle') {
diagramLayerGroup.clearLayers();
diagramLayerGroup.addLayer(nearimage);
var markerGroup = diagramLayerGroup.addTo(map);
imgset='near';
console.log('set near = ' + z);
return;
}
});
</script>
</body>
</html>
This time we have added the images inside a LayerGroup so that we can manipulate them. We are using the same coordinates as in our previous simple image example.
The switching is done when the user changes the zoom, using the zoomend function