Mapbox提供了自定義圖層(CustomLayer)的接口,可以方便地利用創建自定義圖層利用three.js在圖中添加模型,可以參考官方案例:https://docs.mapbox.com/mapbox-gl-js/example/add-3d-model/
但是自定義圖層沒有minZoom、maxZoom屬性,那么就不能像普通圖層那樣設置自定義圖層的可視范圍了。
不過根據定義,自定義圖層必須實現render方法,該方法將要顯示的內容繪制在GL context,那么可以在該render函數中判斷地圖的zoom,如果在minZoom - maxZoom的范圍,正常繪制,否則該函數將直接返回。示例如下:
1 map.addLayer({ 2 id: 'custom-layer-id', 3 type: 'custom', 4 renderingMode: '3d', 5 onAdd: function (map, mbxContext) { 6 let Threebox = window.Threebox 7 that.threebox = new Threebox(map, mbxContext, { defaultLights: true }) 8 that.__loadLamp() 9 }, 10 render: function (gl, matrix) { 11 if (that.map.getZoom() < minZoom) { 12 return 13 } 14 that.threebox && that.threebox.update() 15 that.map.triggerRepaint() 16 } 17 })
這是一種方案,如果大家有更好的方法歡迎一起交流~