mapboxgl V3 Slot插槽使用介紹

槑孒發表於2024-07-31

一、介紹

插槽允許在樣式中建立定義明確的插入點,如:通常“面”圖層需要插入到“線”圖層下方,在標準樣式之前,需要透過指定圖層 id 來實現,一旦 id 發生變化,則會丟擲錯誤,而在新的標準樣式中,只需要指定相應的插槽即可。

{
  "layers": [
    ...,
    {
      "id": "bottom",
      "type": "slot",
      "metadata": {
        "mapbox:description": "Above polygons (land, landuse, water, etc.)"
      }
    },
    ...
  ]
}

當前提供的標準樣式(mapbox://styles/mapbox/standard)中定義了三個插槽:bottom, middle 和 top。

bottom:突出顯示路徑和道路、建築物、模型和註記下方的區域(面)。
middle:覆蓋區域,或在路徑和道路上方,但在建築物、模型和註記下方新增的線條。
top:將資料放置在 POI 圖層上方,但在地點和交通註記下方。

可透過map.getSlots()獲取。

二、使用

在Style定義所需插槽

const map = new mapboxgl.Map({
  container: 'mapView',
  accessToken:'***',
  style: {
    sources: {},
    layers: [
      {
        id: 'bottom',
        type: 'slot',
        metadata: {
          'mapbox:description': '面',
        },
      },
      {
        id: 'middle',
        type: 'slot',
        metadata: {
          'mapbox:description': '線',
        },
      },
      {
        id: 'top',
        type: 'slot',
        metadata: {
          'mapbox:description': '點',
        },
      },
    ],
    version: 8,
  },
  center: [113,23],
  zoom: 3,
  attributionControl: false,
  minZoom: 1,
  maxZoom: 18,
});

然後在新增圖層的時候,指定插槽名稱就可以了

this.map?.addLayer({
  id: layerId,
  type: 'symbol',
  slot: 'top',
  source: layerId,
  layout: {
    'icon-image': '{icon}',
    'icon-anchor': 'bottom',
  },
  paint: {
    'text-color': ['get', 'color'],
    'text-halo-color': 'white',
    'text-halo-width': 2,
  },
});

https://docs.mapbox.com/style-spec/reference/slots

相關文章