leaflet動態更改wms瓦片請求引數

槑孒發表於2024-06-22

需求

https://leafletjs.cn/reference.html#tilelayer-wms

官方文件這裡說了可以新增自定義引數,但是這裡的寫法,值是固定的

如果我們需要新增的引數的值是動態變化的,那麼,直接寫在options的方式固然是行不通的

解決辦法

重寫getTileUrl方法,可以選擇繼承TilelayerWMS重寫一個類,也可以針對指定圖層做修改

針對指定圖層做修改做演示

a.根據地圖狀態動態修改zoom引數值示例

const tiles = L.tileLayer.wms("http://localhost:9090/geoserver/ne/wms", {
  layers: "ne:countries",
  tileSize: map.getSize(),
});
tiles.getTileUrl = function (croods) {
  let { x, y, z } = croods;
  url = L.TileLayerWMS.prototype.getTileUrl.call(this, coords);
  return url + "&zoom=" + z;
};
tiles.addTo(map);

這樣就可以根據地圖狀態動態修改zoom值了

b.非標準wms圖層服務,動態傳top/bottom/left/right/width/height值示例
有些wms服務,要求傳top/bottom/left/right而不是傳bbox,這時就需要動態傳這些值了

const tiles = L.tileLayer.wms("http://localhost:9090/geoserver/ne/wms", {
        test: "123",
});
tiles.getTileUrl = function (coords) {
  let { x: width, y: height } = this.getTileSize();
  let bound = this._tileCoordsToBounds(coords),
    top = bound.getNorth(),
    bottom = bound.getSouth(),
    left = bound.getEast(),
    right = bound.getWest(),
    options = {
      ...this.options,
      top,
      bottom,
      left,
      right,
      width,
      height,
    };
  return this._url + hnsdk.Util.getParamString(options, this._url);
};
tiles.addTo(map);

可以發現,每張瓦片請求的top/bottom/left/right引數都是不同的

這種方式也可以為後續有些圖層服務對單張瓦片請求做加密的話,使用leaflet實現的原理方案大抵相同。

相關文章