leaflet地图瓦片裁剪

516 阅读1分钟

1. 问题背景

项目过程中遇到一个需求,需要leaflet加载两层TileLayer,一层是卫星瓦片,一层是文字标注瓦片。文字标注瓦片又只需要在特定的区域内显示,对于这个问题的解决做下简单的记录。

2. 需求实现

这里需要使用第三方leaflet插件:leaflet-boundary-canvas

import 'leaflet-boundary-canvas'

// 为了方便,url这里不做更改
const streeResource = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
const labelResource = 'xxx'

// 正常加载一个街道瓦片图层
const stree = L.tileLayer(streeResource)
stree.addTo(map)

// 加载一个标注瓦片图层 
const label =  L.TileLayer.BoundaryCanvas(labelResource, {
    boundary: geojson.features[0],
    opacity: 0.8
})
label.addTo(map)

// 同时你也可以这么做
const layer2 = L.tileLayer(labelResource, { opacity: 0.8 })
const boundaryLayer = L.TileLayer.BoundaryCanvas.createFromLayer(layer2, {
    boundary: geojson.features[0],
})
boundaryLayer.addTo(map)