简体   繁体   中英

How to render a map with bounds which are saved on zoomend function in leaflet

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));
    });
   }

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM