Published on

Leaflet的使用

Authors
  • avatar
    Name
    阿涵王小胖
    Twitter
    @hnqxc

默认图钉的图片资源404

使用vue等前端框架集成leaflet时,或许会遇到L.marker实例化出的图钉图片缺失,那么可以使用以下解决方法

如果是vue2 webpack

delete L.Icon.Default.prototype._getIconUrl
L.Icon.Default.imagePath = ''
L.Icon.Default.mergeOptions({
    iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
    iconUrl: require('leaflet/dist/images/marker-icon.png'),
    shadowUrl: require('leaflet/dist/images/marker-shadow.png')
})

如果是vue3 vite等,由于require无法使用,那么就需要这样做

delete L.Icon.Default.prototype._getIconUrl
L.Icon.Default.mergeOptions({
    iconRetinaUrl: new URL("leaflet/dist/images/marker-icon-2x.png", import.meta.url).href,
    iconUrl: new URL("leaflet/dist/images/marker-icon.png", import.meta.url).href,
    shadowUrl: new URL("leaflet/dist/images/marker-shadow.png", import.meta.url).href,
})

如果是vue3 typescript,可以先定义Icon.Default._getIconUrl

import { Icon } from 'leaflet'
type D = Icon.Default & {
    _getIconUrl?: string
}

delete (Icon.Default.prototype as D)._getIconUrl
L.Icon.Default.mergeOptions({
    iconRetinaUrl: new URL("leaflet/dist/images/marker-icon-2x.png", import.meta.url).href,
    iconUrl: new URL("leaflet/dist/images/marker-icon.png", import.meta.url).href,
    shadowUrl: new URL("leaflet/dist/images/marker-shadow.png", import.meta.url).href,
})

待定