我正在使用 LeafletJS 和 Vue3 开发一个个人项目。我想更改默认标记图标,因此我将 png 文件直接复制到与我的脚本相同的文件中,并创建了一个新图标,如下所示。
import leaflet from "leaflet";
let DefaultIcon = new leaflet.Icon({
iconUrl: './Banner.png',
iconSize: [50, 50]
})
export default class Info {
constructor(
name = "", notes = "", icon = DefaultIcon
){
this.name = name;
this.notes = notes;
this.icon = icon;
}
...
当我创建标记时,我会访问此图标...
...
constructor(data) {
this.id = data.id;
this.info = new Info(data.info.name, data.info.notes);
console.log("Icon", this.info.icon)
if (mapStore.map != null) {
this.object = new leaflet.marker(
[data.lat, data.lng],
{
icon: this.info.icon,
draggable: true,
riseOnHover: true
}
).addTo(mapStore.map)
}
...
在我在选项中指定
icon: this.info.icon
之前,使用默认的蓝色标记图标一切正常。现在标记仍然出现(我可以看到它们的工具提示),但没有图标。我完全不知道是什么原因造成的。日志语句显示 data.info.name
是一个具有正确路径和一切的 leaflet.Icon
。
我尝试将路径设置为从项目根目录开始的绝对路径、从脚本位置开始的相对路径,并在初始化图标时提供选项值。我还尝试在不使用
DefaultIcon
关键字的情况下初始化 new
,只是因为这就是我在 here 看到的内容(虽然我真的不知道为什么该示例中没有 new
关键字),但我收到了一个错误初始化挂钩。我希望将默认的蓝色标记图标替换为我的 Banner.png
标记图标,但实际上根本没有标记图标。为什么地图上没有显示图标?
由于您使用的是具有构建步骤的前端框架(此处为 Vue 3),因此您构建的资产很可能不具有与项目源代码相同的文件结构:您的文件被捆绑并复制到目标中文件夹和媒体资产的名称可能会被修改(通常是用于缓存清除的指纹识别)。
因此,当 Leaflet 使用
iconUrl: './Banner.png'
填充标记图标 <img src>
属性时,路径已损坏:您的图像不在服务器上的该位置。
要让构建引擎将您的图像作为其余媒体资源进行处理,并检索其最终路径和名称,请确保
import
或 require
:
let DefaultIcon = new leaflet.Icon({
iconUrl: require('./Banner.png'), // require the image, the build engine will prohide the final path and name
iconSize: [50, 50]
})
或者:
import myImgPath from './Banner.png'
let DefaultIcon = new leaflet.Icon({
iconUrl: myImgPath,
iconSize: [50, 50]
})