Vue2 Leaflet应用中默认marker-icon.png找不到如何修复?
问题现象
在Vue项目中集成Leaflet绘制地图标记时,默认标记显示为破损状态。查看DOM结构发现,执行L.marker(center).addTo(mapDiv)生成的标记img标签src为相对路径marker-icon.png,无法正确加载静态资源,标签结构如下:
<img src="marker-icon.png" class="leaflet-marker-icon leaflet-zoom-animated leaflet-interactive" alt="Marker" tabindex="0" role="button" style="margin-left: -12px; margin-top: -41px; width: 25px; height: 41px; transform: translate3d(250px, 250px, 0px); z-index: 250;">
测试用的核心组件代码如下:
<template> <div id="container"> <div id="mapContainer"></div> </div> </template> <script> import 'leaflet/dist/leaflet.css'; import L from 'leaflet'; import Vue from 'vue'; export default { name: 'Map', methods: { async setupLeafletMap() { const center = [37, -122]; const mapDiv = L.map('mapContainer').setView(center, 13); var tiles = new L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', minZoom: 3, maxZoom: 8 }).addTo(mapDiv); L.marker(center).addTo(mapDiv); } }, async mounted() { await Vue.nextTick(); await this.setupLeafletMap(); } }; </script> <style scoped> #mapContainer { width: 500px; height: 500px; } </style>
问题原因
Leaflet内部默认通过相对路径引用标记图标资源,在基于Vue CLI、Vite等构建工具的项目中,静态资源路径会被构建工具做hash重写、路径替换处理,Leaflet内置的相对路径无法匹配构建后输出的真实资源路径,最终导致资源404、图标破损。
解决方案
不需要额外修改构建配置,直接在初始化地图前手动修正Leaflet默认图标的资源路径即可,操作步骤:
- 从leaflet依赖包中导入内置的标记图标静态资源
- 删除Leaflet默认的图标路径获取方法,覆盖默认图标配置
修改组件中引入Leaflet后的代码片段:
import 'leaflet/dist/leaflet.css'; import L from 'leaflet'; import Vue from 'vue'; // 导入leaflet内置的标记图标资源 import markerIcon from 'leaflet/dist/images/marker-icon.png'; import markerIconRetina from 'leaflet/dist/images/marker-icon-2x.png'; import markerShadow from 'leaflet/dist/images/marker-shadow.png'; // 重置默认图标配置 delete L.Icon.Default.prototype._getIconUrl; L.Icon.Default.mergeOptions({ iconUrl: markerIcon, iconRetinaUrl: markerIconRetina, shadowUrl: markerShadow });
修改完成后重新启动项目,标记图标即可正常加载显示。该方案无额外依赖,兼容Vue2/Vue3、Webpack/Vite等所有项目场景。
内容的提问来源于stack exchange,提问作者ericg
相关产品推荐
相关产品推荐

