Reputation: 7199
I try to limit moving map out of focus but the map is fixed to centre and can't be moved.
var mapSW = [1000, 0],
mapNE = [1000, 0];
var map = L.map('map', {
crs: L.CRS.Simple,
zoomControl: true,
zoom: 1,
minZoom: 0,
maxZoom: 4
});
var bounds = [[-250,-500], [800,800]];
var image = L.imageOverlay('uqm_map_full.png', bounds).addTo(map);
map.fitBounds(bounds);
map.setMaxBounds(new L.LatLngBounds(
map.unproject(mapSW, map.getMaxZoom()),
map.unproject(mapNE, map.getMaxZoom()),
));
If I enable setmaxBounds() map's background image fix to centre and can be moved elastically. Map move, until it is dragged, after drag end map back to its centre.
I tried to follow few examples but still no success. Do you see where I make mistake?
Upvotes: 1
Views: 2750
Reputation: 53185
Your mapSW
and mapNE
coordinates are identical, so the LatLngBounds that you can build out of them is of null area.
Furthermore, I am not sure why you carefully build bounds
for your Image Overlay (image
) and to have the map
fit those bounds, then using complicated unproject
with different coordinates to specify to setMaxBounds
?
Live example using the same bounds
for setMaxBounds
, enabling navigation to the same bounds as the Image Overlay:
var map = L.map('map', {
crs: L.CRS.Simple,
zoomControl: true,
zoom: 1,
minZoom: 0,
maxZoom: 4
});
var bounds = [
[-250, -500],
[800, 800]
];
var image = L.imageOverlay('https://a.tile.openstreetmap.org/0/0/0.png', bounds, {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
map.fitBounds(bounds);
/*map.setMaxBounds(new L.LatLngBounds(
map.unproject(mapSW, map.getMaxZoom()),
map.unproject(mapNE, map.getMaxZoom()),
));*/
map.setMaxBounds(bounds);
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css">
<script src="https://unpkg.com/[email protected]/dist/leaflet-src.js"></script>
<div id="map" style="height: 200px"></div>
If you wish to restrict user navigation to a different area than your image
's bounds, you can easily do so by building similar bounds, without having to resort to unproject
at all:
var map = L.map('map', {
crs: L.CRS.Simple,
zoomControl: true,
zoom: 1,
minZoom: 0,
maxZoom: 4
});
var bounds = [
[-250, -500],
[800, 800]
];
var image = L.imageOverlay('https://a.tile.openstreetmap.org/0/0/0.png', bounds, {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
map.fitBounds(bounds);
/*map.setMaxBounds(new L.LatLngBounds(
map.unproject(mapSW, map.getMaxZoom()),
map.unproject(mapNE, map.getMaxZoom()),
));*/
map.setMaxBounds([
[-300, -600],
[900, 900]
]);
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css">
<script src="https://unpkg.com/[email protected]/dist/leaflet-src.js"></script>
<div id="map" style="height: 200px"></div>
Upvotes: 1