Reputation: 387
I have to save the Zoom level of the Map. In zoom end function of Map I saved it in a local storage and while again the component is rendered, I tried to check whether any zoom value is preserved or not. Based on it I tried to render the Map.Everythings works fine but I need to save the location also so I tried to get the bounds and do the same as in Zoom level.It's not working I tried to apply fitBounds if there is any value in local storage. Please help me to solve this issue.
initializeMap = () => {
const { user } = this.props;
const zoomLevel = localStorage.getItem('itemsZoom');
let boundCoordinates = {};
boundCoordinates = JSON.parse(localStorage.getItem('itemsBounds'));
if (zoomLevel !== null && Object.keys(boundCoordinates).length > 0) {
this.map.fitbounds(boundCoordinates);
}
this.map.fitbounds(boundCoordinates);
this.map = L.map('map', {
center: [38.778, -73.554]
zoom: zoomLevel !== null ? zoomLevel : 18
});
L.gridLayer.googleMutant({ type: 'satellite', maxZoom: 20 }).addTo(this.map);
this.map.on(L.Draw.Event.CREATED, (e) => {
this.onMarkerCreated(e);
});
this.map.on('draw:editmove', (e) => {
this.onMarkerEdited(e);
});
this.map.on('zoomend', (e) => {
const zoom = this.map.getZoom();
localStorage.setItem('itemsZoom', zoom);
const bounds = this.map.getBounds();
localStorage.setItem('itemsBounds', JSON.stringify(bounds));
});
}
Upvotes: 1
Views: 477
Reputation: 11338
use this to save the bounds localStorage.setItem('itemsBounds',this.map.getBounds().toBBoxString()))
and then when you read out call:
[west, south, east, north] = localStorage.getItem('itemsBounds').split(',').map(parseFloat)
var bounds = new L.LatLngBounds(new L.LatLng(south, west), new L.LatLng(north, east))
this.map.fitBounds(bounds);
PS: fitBounds
with "B"
Upvotes: 2