Avoid loading of invisible tiles when using multiple tile layers in Leaflet - Javascript Leaflet

Javascript examples for Leaflet:Layer

Description

Avoid loading of invisible tiles when using multiple tile layers in Leaflet

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <link rel="stylesheet" type="text/css" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"> 
      <script type="text/javascript" src="http://aparshin.ru/tmp/leaflet_dev/leaflet-src.js"></script> 
      <style id="compiled-css" type="text/css">

#map { height: 300px; }


      </style> 
      <script type="text/javascript">
    window.onload=function(){//from w w w .  ja  v a2 s .c o  m
L.ExtendedTileLayer = L.TileLayer.extend({
    _isValidTile: function (coords) {
      var crs = this._map.options.crs;
      if (!crs.infinite) {
            var globalTileRange = this._map.getPixelWorldBounds( coords.z );
         var bounds = globalTileRange;
         if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
             (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
      }
        var tileBounds = this._tileCoordsToBounds(coords);
        if (this.options.bounds &&
            ! L.latLngBounds(this.options.bounds).intersects(tileBounds)) {
            return false;
        }
        if (this.options.hole &&
            L.latLngBounds(this.options.hole).intersects(tileBounds)) {
            return false;
        }
      return true;
   },
});
var map = L.map('map', {
    center: [40.777838, -73.968654],
    zoom: 14
});
new L.ExtendedTileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{
    attribution: '? <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
    hole: L.latLngBounds(
        L.latLng(40.791853, -73.967128),
        L.latLng(40.781455, -73.955713)
    )
}).addTo(map);
L.tileLayer('http://tile.stamen.com/toner/{z}/{x}/{y}.png', {
    attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://creativecommons.org/licenses/by-sa/3.0">CC BY SA</a>.',
    bounds: L.latLngBounds(
        L.latLng(40.791853, -73.967128),
        L.latLng(40.781455, -73.955713)
    )
}).addTo(map);
    }

      </script> 
   </head> 
   <body> 
      <div id="map"></div>  
   </body>
</html>

Related Tutorials