Jinuss's blog Jinuss's blog
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript高级程序设计》
    • 《Vue》
    • 《React》
    • 《Git》
    • JS设计模式总结
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • 学习
  • 实用技巧
关于
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

东流

前端可视化
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript高级程序设计》
    • 《Vue》
    • 《React》
    • 《Git》
    • JS设计模式总结
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • 学习
  • 实用技巧
关于
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 框架

  • core模块

  • dom模块

  • control

  • geometry

  • geo

  • layer

    • marker

    • tile

      • GridLayer
        • 概述
          • GridLayer作用
          • GridLayer功能特点
        • 源码分析
          • 源码实现
          • 源码详解
          • 生命周期
          • onAdd(map)
          • onRemove(map)
          • 容器与层级管理
          • _initContainer()
          • _updateLevels()
          • 核心渲染方法
          • _update(center)
          • 瓦片生命周期控制
          • _pruneTiles()
          • 坐标转换与投影
          • _getTilePos(coords)
          • _wrapCoords(coords)
          • 事件绑定与响应
          • getEvents()
          • 性能优化
          • _tileReady
        • 总结
      • TileLayer
      • TileLayer.WMS
    • vector

    • Layer
    • LayerGroup
    • FeatureGroup
    • DivOverlay
    • Popup
    • Tooltip
    • ImageOverlay
    • SVGOverlay
    • VideoOverlay
    • GeoJSON
  • Map

  • 《Leaflet源码》笔记
  • layer
  • tile
东流
2025-04-11
目录

GridLayer

# 概述

GridLayer是一个用于在地图上显示网格瓦片的图层。它继承自Layer类,提供了加载和管理瓦片的功能,用于显示栅格数据。

# GridLayer作用

GridLayer作用就是定义网格图层基类,管理瓦片加载、渲染和生命周期。

# GridLayer功能特点

  • 瓦片加载:支持异步加载瓦片,根据当前地图视口和缩放级别加载相应的瓦片。
  • 缓存管理:支持缓存已加载的瓦片,避免重复加载。
  • 层级控制:支持设置最小和最大缩放级别,控制瓦片的加载范围。
  • 自定义样式:支持自定义瓦片的样式,如透明度、颜色等。
  • 事件处理:支持监听瓦片加载完成、错误等事件。
  • 性能优化:支持预加载和懒加载,减少不必要的瓦片加载。
  • 兼容性:支持多种浏览器和设备,包括移动设备和桌面浏览器。

# 源码分析

# 源码实现

GridLayer的源码实现如下:

export var GridLayer = Layer.extend({
  options: {
    tileSize: 256, // 瓦片尺寸,单位:像素
    opacity: 1, // 透明度 0-1
    updateWhenIdle: Browser.mobile, // 移动端默认在停止拖动后再加载瓦片
    updateWhenZooming: true, // 是否在地图缩放动画过程中更新瓦片,false表示仅在动画结束后更新
    updateInterval: 200, // 拖拽时更新瓦片的最小间隔时间毫秒,避免频繁请求
    zIndex: 1, // 图层堆叠顺序
    bounds: null, // 限制瓦片加载的地理范围
    minZoom: 0, // 图层可见的最小缩放级别,包含该级别
    maxZoom: undefined, // 图层可见的最大缩放级别,包含该级别
    maxNativeZoom: undefined, // 最大原生缩放级别,超出该级别将使用最大缩放级别加载瓦片
    minNativeZoom: undefined, // 最小原生缩放级别,低于该级别将使用最小缩放级别加载瓦片
    noWrap: false, // 是否禁止横向循环
    pane: "tilePane", // 指定图层添加到地图的哪个窗格
    className: "", //自定义CSS类名
    keepBuffer: 2, // 预加载瓦片的行列数
  },
  initialize: function (options) {
    Util.setOptions(this, options); // 合并选项与默认值
  },
  onAdd: function () {
    this._initContainer(); // 初始化容器
    this._levels = {}; // 存储不同缩放级别下的瓦片信息
    this._tiles = {}; // 存储当前加载的瓦片
    this._resetView(); // 初始化视图, 触发首次加载
  },
  beforeAdd: function (map) {
    map._addZoomLimit(this);
  },
  onRemove: function (map) {
    this._removeAllTiles(); // 清理所有瓦片
    DomUtil.remove(this._container); // 移除DOM
    map._removeZoomLimit(this);
    this._container = null; // 清除容器引用
    this._tileZoom = undefined; // 清除缩放级别
  },
  bringToFront: function () {
    if (this._map) {
      DomUtil.toFront(this._container);
      this._setAutoZIndex(Math.max);
    }
    return this;
  },
  bringToBack: function () {
    if (this._map) {
      DomUtil.toBack(this._container);
      this._setAutoZIndex(Math.min);
    }
    return this;
  },
  getContainer: function () {
    return this._container;
  },
  setOpacity: function (opacity) {
    this.options.opacity = opacity;
    this._updateOpacity();
    return this;
  },
  setZIndex: function (zIndex) {
    this.options.zIndex = zIndex;
    this._updateZIndex();

    return this;
  },
  isLoading: function () {
    return this._loading;
  },
  redraw: function () {
    if (this._map) {
      this.removeAllTiles();
      var tileZoom = this._clampZoom(this._map.getZoom());
      if (tileZoom !== this._tileZoom) {
        this._titleZoom = tileZoom;
        this._updateLevels();
      }
      this._update();
    }
    return this;
  },
  getEvents: function () {
    var events = {
      viewprereset: this._invalidateAll,
      viewreset: this._resetView,
      zoom: this._resetView,
      moveend: this._onMoveEnd,
    };
    
    // 非空闲更新模式时,节流处理move事件
    if (!this.options.updateWhenIdle) {
      if (!this._onMove) {
        this._onMove = Util.throttle(
          this._onMoveEnd,
          this.options.updateInterval,
          this
        );
      }

      events.move = this._onMove;
    }

    if (this._zoomAnimated) {
      events.zoomanim = this._animateZoom;
    }

    return events;
  },
  createTile: function () {
    // 用户可自行扩展
    return document.createElement("div");
  },
  getTileSize: function () {
    var s = this.options.tileSize;
    return s instanceof Point ? s : new Point(s, s);
  },
  _updateZIndex: function () {
    if (
      this._container &&
      this.options.zIndex !== undefined &&
      this.options.zIndex !== null
    ) {
      this._container.style.zIndex = this.options.zIndex;
    }
  },
  _setAutoZIndex: function (compare) {
    var layers = this.getPane().children,
      edgeZIndex = -compare(-Infinity, Infinity);

    for (var i = 0, len = layers.length, zIndex; i < len; i++) {
      zIndex = layers[i].style.zIndex;

      if (layers[i] !== this._container && zIndex) {
        edgeZIndex = compare(edgeZIndex, +zIndex);
      }
    }

    if (isFinite(edgeZIndex)) {
      this.options.zIndex = edgeZIndex + compare(-1, 1);
      this._updateZIndex();
    }
  },
  _updateOpacity: function () {
    if (!this._map) {
      return;
    }

    if (Browser.ielt9) {
      return;
    }

    DomUtil.setOpacity(this._container, this.options.opacity);

    var now = +new Date(),
      nextFrame = false,
      willPrune = false;

    for (var key in this._tiles) {
      var tile = this._tiles[key];
      if (!tile.current || !tile.loaded) {
        continue;
      }

      var fade = Math.min(1, (now - tile.loaded) / 200);

      DomUtil.setOpacity(tile.el, fade);
      if (fade < 1) {
        nextFrame = true;
      } else {
        if (tile.active) {
          willPrune = true;
        } else {
          this._onOpaqueTile(tile);
        }
        tile.active = true;
      }
    }
    if (willPrune && !this._noPrune) {
      this._pruneTiles();
    }

    if (nextFrame) {
      Util.cancelAnimFrame(this._fadeFrame);
      this._fadeFrame = Util.requestAnimFrame(this._updateOpacity, this);
    }
  },
  _onOpaqueTile: Util.falseFn,
  _initContainer: function () {
    if (this._container) {
      return;
    }

    this._container = DomUtil.create(
      "div",
      "leaflet-layer " + (this.options.className || "")
    );
    this._updateZIndex();
    if (this.options.opacity < 1) {
      this._updateOpacity();
    }
    this.getPane().appendChild(this._container); // 添加到指定窗格pane
  },
  _updateLevels: function () {
    var zoom = this._tileZoom,
      maxZoom = this.options.maxZoom;

    if (zoom === undefined) {
      return undefined;
    }
    // 清理无效层级,保留当前缩放和邻近层级
    for (var z in this._levels) {
      z = Number(z);
      if (this._levels[z].el.children.length || z === zoom) {
        // 调整 zIndex 确保正确覆盖 
        this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
        this._onUpdateLevel(z);
      } else {
        // 移除空层级
        DomUtil.remove(this._levels[z].el);
        this._removeTilesAtZoom(z);
        this._onRemoveLevel(z);
        delete this._levels[z];
      }
    }

    var level = this._levels[zoom],
      map = this._map;
    
    // 创建当前缩放层级的容器
    if (!level) {
      level = this._levels[zoom] = {};

      level.el = DomUtil.create(
        "div",
        "leaflet-tile-container leaflet-zoom-animated",
        this._container
      );
      level.el.style.zIndex = maxZoom;

      level.origin = map
        .project(map.unproject(map.getPixelOrigin()), zoom)
        .round();
      level.zoom = zoom;

      this._setZoomTransform(level, map.getCenter(), map.getZoom());

      // force the browser to consider the newly added element for transition
      Util.falseFn(level.el.offsetWidth);

      this._onCreateLevel(level);
    }

    this._level = level;

    return level;
  },
  _onUpdateLevel: Util.falseFn,
  onRemoveLevel: Util.falseFn,
  _onCreateLevel: Util.falseFn,
  _pruneTiles: function () {
    if (!this._map) {
      return;
    }

    var key, tile;

    var zoom = this._map.getZoom();
    if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
      this._removeAllTiles();
      return;
    }
    
    // 标记需保留的瓦片(current当前及缓冲区瓦片)
    for (key in this._tiles) {
      tile = this._tiles[key];
      tile.retain = tile.current;
    }
    
    // 递归保留父级或子级瓦片
    for (key in this._tiles) {
      tile = this._tiles[key];
      if (tile.current && !tile.active) {
        var coords = tile.coords;
        if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
          this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
        }
      }
    }
    
    // 移除非保留瓦片
    for (key in this._tiles) {
      if (!this._tiles[key].retain) {
        this._removeTile(key);
      }
    }
  },
  _removeTilesAtZoom: function () {
    for (var key in this._tiles) {
      if (this._tiles[key].coord.z !== zoom) {
        continue;
      }
      this._removeTile(key);
    }
  },
  _removeAllTiles: function () {
    for (var key in this._tiles) {
      this._removeTile(key);
    }
  },
  _invalidateAll: function () {
    for (var z in this._levels) {
      DomUtil.remove(this._levels[z].el);
      this._onRemoveLevel(Number(z));
      delete this._levels[z];
    }
    this._removeAllTiles();

    this._tileZoom = undefined;
  },
  _retainParent: function (x, y, z, minZoom) {
    var x2 = Math.floor(x / 2),
      y2 = Math.floor(y / 2),
      z2 = z - 1,
      coords2 = new Point(+x2, +y2);
    coords2.z = +z2;

    var key = this._tileCoordsToKey(coords2),
      tile = this._tiles[key];

    if (tile && tile.active) {
      tile.retain = true;
      return true;
    } else if (tile && tile.loaded) {
      tile.retain = true;
    }

    if (z2 > minZoom) {
      return this._retainParent(x2, y2, z2, minZoom);
    }

    return false;
  },
  _retainChildren: function (x, y, z, maxZoom) {
    for (var i = 2 * x; i < 2 * x + 2; i++) {
      for (var j = 2 * y; j < 2 * y + 2; j++) {
        var coords = new Point(i, j);
        coords.z = z + 1;

        var key = this._tileCoordsToKey(coords),
          tile = this._tiles[key];

        if (tile && tile.active) {
          tile.retain = true;
          continue;
        } else if (tile && tile.loaded) {
          tile.retain = true;
        }

        if (z + 1 < maxZoom) {
          this._retainChildren(i, j, z + 1, maxZoom);
        }
      }
    }
  },
  _resetView: function (e) {
    var animating = e && (e.pinch || e.flyTo);
    // 更新视图(瓦片)
    this._setView(
      this._map.getCenter(),
      this._map.getZoom(),
      animating,
      animating
    );
  },
  _animateZoom: function (e) {
    // 应用缩放动画
    this._setView(e.center, e.zoom, true, e.noUpdate); 
  },
  _clampZoom: function (zoom) {
    var options = this.options;

    if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {
      return options.minNativeZoom;
    }

    if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {
      return options.maxNativeZoom;
    }

    return zoom;
  },
  _setView: function (center, zoom, noPrune, noUpdate) {
    var tileZoom = Math.round(zoom);
    if (
      (this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
      (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)
    ) {
      tileZoom = undefined;
    } else {
      tileZoom = this._clampZoom(tileZoom);
    }

    var tileZoomChanged =
      this.options.updateWhenZooming && tileZoom !== this._tileZoom;

    if (!noUpdate || tileZoomChanged) {
      this._tileZoom = tileZoom;

      if (this._abortLoading) {
        this._abortLoading();
      }

      this._updateLevels();
      this._resetGrid();

      if (tileZoom !== undefined) {
        this._update(center);
      }

      if (!noPrune) {
        this._pruneTiles();
      }

      this._noPrune = !!noPrune;
    }

    this._setZoomTransforms(center, zoom);
  },
  _setZoomTransforms: function (center, zoom) {
    for (var i in this._levels) {
      this._setZoomTransform(this._levels[i], center, zoom);
    }
  },
  _setZoomTransform: function (level, center, zoom) {
    var scale = this._map.getZoomScale(zoom, level.zoom),
      translate = level.origin
        .multiplyBy(scale)
        .subtract(this._map._getNewPixelOrigin(center, zoom))
        .round();

    if (Browser.any3d) {
      DomUtil.setTransform(level.el, translate, scale);
    } else {
      DomUtil.setPosition(level.el, translate);
    }
  },
  _resetGrid: function () {
    var map = this._map,
      crs = map.options.crs,
      tileSize = (this._tileSize = this.getTileSize()),
      tileZoom = this._tileZoom;

    var bounds = this._map.getPixelWorldBounds(this._tileZoom);
    if (bounds) {
      this._globalTileRange = this._pxBoundsToTileRange(bounds);
    }

    this._wrapX = crs.wrapLng &&
      !this.options.noWrap && [
        Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
        Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y),
      ];
    this._wrapY = crs.wrapLat &&
      !this.options.noWrap && [
        Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
        Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y),
      ];
  },
  _onMoveEnd: function () {
    if (!this._map || this._map._animatingZoom) {
      return;
    }

    this._update();
  },
  _getTiledPixelBounds: function (center) {
    var map = this._map,
      mapZoom = map._animatingZoom
        ? Math.max(map._animateToZoom, map.getZoom())
        : map.getZoom(),
      scale = map.getZoomScale(mapZoom, this._tileZoom),
      pixelCenter = map.project(center, this._tileZoom).floor(),
      halfSize = map.getSize().divideBy(scale * 2);

    return new Bounds(
      pixelCenter.subtract(halfSize),
      pixelCenter.add(halfSize)
    );
  },
  _update: function (center) {
    var map = this._map;
    if (!map) {
      return;
    }
    var zoom = this._clampZoom(map.getZoom());

    if (center === undefined) {
      center = map.getCenter();
    }

    if (this._tileZoom === undefined) {
      return;
    }
    // 计算当前视图的像素范围 → 瓦片坐标范围
    var pixelBounds = this._getTiledPixelBounds(center),
      tileRange = this._pxBoundsToTileRange(pixelBounds),
      tileCenter = tileRange.getCenter(),
      queue = [],
      margin = this.options.keepBuffer,
      // 生成缓冲区范围noPruneRange
      noPruneRange = new Bounds(
        tileRange.getBottomLeft().subtract([margin, -margin]),
        tileRange.getTopRight().add([margin, -margin])
      );

    if (
      !(
        isFinite(tileRange.min.x) &&
        isFinite(tileRange.min.y) &&
        isFinite(tileRange.max.x) &&
        isFinite(tileRange.max.y)
      )
    ) {
      throw new Error("Attempted to load an infinite number tiles");
    }
    
    // 标记当前可视瓦片,清理非活跃瓦片
    for(var key in this._tiles){
      var c=this._tiles[key].coords;
      if(c.z !== this._tileZoom || !noPruneRange.container(new Point(c.x,c.y))){
          this.+tiles[key].current=false;
      }
    }
    if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
    
    // 生成待加载瓦片队列
    for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
			for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
				var coords = new Point(i, j);
				coords.z = this._tileZoom;

				if (!this._isValidTile(coords)) { continue; }

				var tile = this._tiles[this._tileCoordsToKey(coords)];
				if (tile) {
					tile.current = true;
				} else {
					queue.push(coords);
				}
			}
		}
    //  按距离中心排序
    queue.sort(function (a, b) {
			return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
		});

        if (queue.length !== 0) {
			if (!this._loading) {
				this._loading = true;
				this.fire('loading');
			}

     // 批量创建并加载瓦片
			var fragment = document.createDocumentFragment();

			for (i = 0; i < queue.length; i++) {
				this._addTile(queue[i], fragment);
			}

			this._level.el.appendChild(fragment);
		}
  },
  _isValidTile: function (coords) {
    var crs=this._map.options.crs;
    if(!crs.infinite){
      var bounds =this._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;
      }
    }

    if (!this.options.bounds) { return true; }

    var tileBounds = this._tileCoordsToBounds(coords);
	return latLngBounds(this.options.bounds).overlaps(tileBounds);
  },
  _keyToBounds:function(key){
    return this._tileCoordsToBounds(this._keyToTileCoords(key))
  },
  _tileCoordsToNwSe: function (coords) {
    var map = this._map,
		    tileSize = this.getTileSize(),
		    nwPoint = coords.scaleBy(tileSize),
		    sePoint = nwPoint.add(tileSize),
		    nw = map.unproject(nwPoint, coords.z),
		    se = map.unproject(sePoint, coords.z);
		return [nw, se];
  },
  _tileCoordsBounds: function (coords) {
    var bp = this._tileCoordsToNwSe(coords),
		    bounds = new LatLngBounds(bp[0], bp[1]);

		if (!this.options.noWrap) {
			bounds = this._map.wrapLatLngBounds(bounds);
		}
		return bounds;
  },
  _tileCoordsToKey: function (coords) {
    return coords.x + ':' + coords.y + ':' + coords.z;
  },
  _keyToTileCoords: function (key) {
    var k = key.split(':'),
		    coords = new Point(+k[0], +k[1]);
		coords.z = +k[2];
		return coords;
  },
  _removeTile: function (key) {
    var tile = this._tiles[key];
		if (!tile) { return; }

		DomUtil.remove(tile.el); // 移除DOM元素

		delete this._tiles[key]; // 清理引用
    
    // 触发tileunload事件
		this.fire('tileunload', {
			tile: tile.el,
			coords: this._keyToTileCoords(key)
		});
  },
  _initTile: function (tile) {
    DomUtil.addClass(tile, 'leaflet-tile');

		var tileSize = this.getTileSize();
		tile.style.width = tileSize.x + 'px';
		tile.style.height = tileSize.y + 'px';

		tile.onselectstart = Util.falseFn;
		tile.onmousemove = Util.falseFn;

		if (Browser.ielt9 && this.options.opacity < 1) {
			DomUtil.setOpacity(tile, this.options.opacity);
		}
  },
  _addTile: function (coords,container) {
    var tilePos =this._getTilePos(coords),
    key=this._tileCoordsToKey(coords);
    var tile =this.createTile(this._wrapCoords(coords),Util.bind(this._tileReady,this,coords));

    this._initTile(tile);
    if(this.createTile.length<2){
     Util.requestAnimFrame(Util.bind(this._tileReady,this,coords,null,tile));
    }
    DomUtil.setPosition(tile,tilePos);
    this._tiles[key]={
        el:tile,
        coords:coords,
        current:true
    }

    container.appendChild(tile);
    this.fire('tileloadstart',{tile:tile,coords:coords})
  },
  _tileReady: function (coords,err,tile) {
    if(err){
      // 触发错误事件
      this.fire('fileerror',{
        error:err,
        tile:tile,
        coords:coords
      })
    }

    var key =this._tileCoordsToKey(coords);
    tile=this._tiles[key];
    if(!tile){
      return;
    }
    // 更新透明度并触发清理
    tile.loaded = + new Date();
    if(this._map._fadeAnimated){
      DomUtil.setOpacity(tile.el,0);
      Util.cancelAnimFrame(this._fadeFrame);
      this._fadeFrame=Util.requestAnimFrame(this._updateOpacity,this);
    }else{
        tile.active=true;
        this._pruneTiles()
    }

    if(!err){
        DomUtil.addClass(tile.el,'leaflet-tile-loaded'); // 标记加载完成
        // 触发加载成功事件
       this.fire('tileload',{
            tile:tile.el,
            coords:coords
        })
    }

    if(this._noTilesToLoad()){
      this._loading=false;
      this.fire('load');
      if(Browser.ielt9||!this._map._fadeAnimated){
        Util.requestAnimFrame(this._pruneTiles,this)
      } else{
      	setTimeout(Util.bind(this._pruneTiles, this), 250);
      }
    }
  },
  _getTilePos: function (coords) {
    // 计算瓦片在容器中的像素位置
    return coords.scaleBy(this.getTileSize()).subtract(this._level.origin)
  },
  _wrapCoords: function (coords) {
    // 处理横向循环
    var newCoords=new Point(this._wrapX?Util.wrapNum(coords.x,this._wrapX):coords.x,this._wrapY?Util.wrapNum(coords.y,this._wrapY):coords.y);

    newCoords.z = coords.z;
    return newCoords;
  },
  _pxBoundsToTileRange: function (bounds) {
    var tileSize =this.getTileSize();
    return new Bounds(bounds.min.unscaleBy(tileSize).floor(),bounds.max.unscaleBy(tileSize).ceil().subtract([1,1]))
  },
  _noTilesToLoad: function () {
    for(var key in this._tiles){
      if(!this._tiles[key].loaded){
        return false;
      }
    }

    return true;
  },
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734

# 源码详解

# 生命周期

# onAdd(map)
  • 流程:
      1. 初始化容器和数据结构
      1. 调用_resetView()触发首次瓦片加载
# onRemove(map)
  • 资源释放:确保内存和DOM所有资源被正确释放,如事件监听器、定时器等

# 容器与层级管理

# _initContainer()
  • DOM结构:创建容器div,自定义类名,层级由pane控制
# _updateLevels()
  • 动态层级:仅维护当前及相邻层级的DOM容器,优化性能

# 核心渲染方法

# _update(center)
  • 核心步骤:
    1. 范围计算:将视图像素范围转换为瓦片坐标
    2. 缓冲区扩展:通过subtract和add生成noPruneRange,保留预加载瓦片
    3. 标记逻辑:在noPruneRange内的瓦片标记为current
    4. 队列生成:按距离中心点的顺序加载,优先渲染可见区域
    5. 批量插入:使用Document.Fragment提升性能

# 瓦片生命周期控制

# _pruneTiles()
  • 递归保留策略
    • _retainParent:向上超找父级瓦片(低缩放层级),确保缩放时能快速回退
    • _retainChildren:向下查找子级瓦片(高缩放层级),确保平滑放大

# 坐标转换与投影

# _getTilePos(coords)
  • 作用:将瓦片坐标(如{x:3,y:5,z:2})转换为容器内的像素位置
# _wrapCoords(coords)
  • 循环处理:当noWrap:false时,修正经度超出[-180,180]的坐标,实现无缝循环

# 事件绑定与响应

# getEvents()
  • 事件策略:
    • updateWhenIdle:true:仅在拖拽结束时更新(移动端默认)
    • updateWhenIdle:false:拖拽时按updateInterval节流更新

# 性能优化

# _tileReady
  • 异步加载:_tileReady中使用requestAnimFrame异步加载,避免阻塞主线程

# 总结

核心设计思想​​

1. ​按需加载​​:仅加载视口及缓冲区内的瓦片,优先中心区域。 2. 动态层级管理​​:维护当前缩放层级的 DOM 容器,优化性能。 3. ​递归保留策略​​:确保缩放时的平滑过渡(父级降级/子级升级)。 4. 异步支持​​:通过 done 回调分离加载逻辑,扩展性强。 5. 内存控制​​:通过 _pruneTiles 及时清理不可见瓦片

编辑 (opens new window)
上次更新: 2025/05/16, 06:30:31
DivIcon
TileLayer

← DivIcon TileLayer→

最近更新
01
GeoJSON
05-08
02
Circle
04-15
03
CircleMarker
04-15
更多文章>
Theme by Vdoing | Copyright © 2024-2025 东流 | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式