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);
},
在上面的代码中,img 属性的 src 没有加载图像。我尝试使用 :src
绑定(bind)为 vue 组件,但它被渲染为字符串。我到图像的相对路径也存在。
最佳答案
一般来说,使用 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/
关于vue.js - 如何将自定义图像添加到 map 框标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69209161/