如何将自定义图像添加到地图框标记?


const marker = document.createElement('div');
marker.innerHTML = `<img src="../../assets/FuelPin.png" style="height: 56px; width: 44px" alt=""/>`;
new mapboxgl.Marker(marker)
.setLngLat(lngLatPopup)
.addTo(this.map);
},

在上面的代码中,src from img属性没有加载图像。我尝试使用:src绑定为值组件,但它被渲染为字符串。我的图像的相对路径也存在。

一般来说,用JavaScript改变innerHTML不是像Vue或React这样的框架允许的(参见https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#security_considerations)

下面是来自Mapbox GL网站的纯JS示例:

const el = document.createElement('div');
const width = marker.properties.iconSize[0];
const height = marker.properties.iconSize[1];
el.className = 'marker';
el.style.backgroundImage = `url(https://placekitten.com/g/${width}/${height}/)`;
el.style.width = `${width}px`;
el.style.height = `${height}px`;
el.style.backgroundSize = '100%';

el.addEventListener('click', () => {
window.alert(marker.properties.message);
});

// Add markers to the map.
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.addTo(map);

从https://docs.mapbox.com/mapbox-gl-js/example/custom-marker-icons/

一个专业提示,如果你有很多图像要加载(像成千上万的标记),你会得到更好的性能,如果你让MapboxGL在WebGL中渲染它,而不是使用DOM,见:https://docs.mapbox.com/mapbox-gl-js/example/add-image/

最新更新