mapboxGL中多图标加载的实现
生活随笔
收集整理的這篇文章主要介紹了
mapboxGL中多图标加载的实现
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
概述
mapboxGl中多圖標的實現(xiàn)可以在style中指定sprite來實現(xiàn),但是在實際使用的時候會出現(xiàn)sprite之外的圖標需要引用,此時通過map.addImage()來實現(xiàn),但是如果存在多個圖標的時候,因為map.addImage()需要先通過map.loadImage()先加載圖標,而map.loadImage()是一個異步的,使用起來就有點麻煩。本文希望通過再再加sprite來實現(xiàn)一次性添加圖標。
實現(xiàn)效果
實現(xiàn)
測試的sprite如下圖:
json文件如下:
實現(xiàn)代碼如下:
map.on('load',() => {const canvas = document.createElement('canvas')const ctx = canvas.getContext('2d')const img = new Image()img.src = './lib/merge.png'img.onload = async () => {canvas.width = img.widthcanvas.height = img.heightctx.drawImage(img, 0, 0)fetch('./lib/merge.json').then(res => res.json()).then(res => {for (const k in res) {const { width, height, x, y } = res[k]const data = ctx.getImageData(x, y, width, height).datamap.addImage(k, { width, height, data })}map.addSource('points', {type: 'geojson',data: {type: 'FeatureCollection',features: [{"type": "Feature","properties": { icon: 'zgyh' },"geometry": { "type": "Point", "coordinates": [107.0132554, 22.1441921] }},{"type": "Feature","properties": { icon: 'jsyh' },"geometry": { "type": "Point", "coordinates": [107.0223554, 22.1443921] }},{"type": "Feature","properties": { icon: 'nyyh' },"geometry": { "type": "Point", "coordinates": [107.0344554, 22.1444921] }}]}});map.addLayer({'id': 'points-h','type': 'symbol','source': 'points','layout': {'icon-allow-overlap': true,'icon-image': ['get', 'icon'],'icon-size': ["interpolate",["exponential",1.5],["zoom"],5, 0.5,10, 0.8]},});})}})總結(jié)
以上是生活随笔為你收集整理的mapboxGL中多图标加载的实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【计算机网络】物理层 : 编码与调制 (
- 下一篇: 英雄杀9月中秋活动