简体   繁体   中英

How to fit map to tile layer bounds in leaflet


I have a leaflet map. The map container is very big compared to the tile in first zoom level (256px X 256px). I want to get the bounds of tile and fit the map bounds to it. I am able to fitbound() with multiple markers. I adopted the code from here . I tried to achieve fit to tile also with same idea. unfortunately it doesn't seem working. Here is my code

     var fitToBounds = function () {
         //getting bound of tile 256X256 pixel
        var maxLat = map.unproject(new L.Point(0,0)).lat; 
        var maxLat = map.unproject(new L.Point(0,256)).lat;
        var maxLng = map.unproject(new L.Point(256,0)).lng;
        var minLng = map.unproject(new L.Point(256,256)).lng;
        var southWest = new L.LatLng(minLat, minLng);
        var northEast = new L.LatLng(maxLat, maxLng);
        map.fitBounds(new L.LatLngBounds(southWest, northEast));
    };

Group your markers in a L.mapbox.featureGroup() and then on your map use

map.fitBounds(featureGroup.getBounds());

Feature groups are like a layerGroup but also has a .getBounds() method that can be used to set your fit. See the docs.

maybe not the best solution, but at least working: Add an other layer and make it invisible. Zoom to this one. Advantage is, you might also add onEachFeature .

     var pointsWithBounds=[]
     _.each(layerWithoutBounds, function (element) {
                pointsWithBounds.push(
                    {
                        "type": "Feature",
                        "geometry": {
                            "type": "CircleMarker",
                            "coordinates": [element.lon, element.lat]
                     });
      });
      var layerWithBounds = L.geoJSON(pointsWithBounds, {
                style: {
                          fillColor: 'transparent',
                          color: 'transparent'
                       }
            });
      layerWithBounds.addTo(map)
      map.setView(layerWithBounds.getBounds().getCenter());
      map.fitBounds(layerWithBounds.getBounds());

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