Icon.Default
# 概述
Leaflet中默认的图标实现,继承自Icon
类。
# 源码分析
# 源码实现
Icon.Default
类的实现如下:
export var IconDefault = Icon.extend({
options: {
iconUrl: "marker-icon.png", // 默认图标
iconRetinaUrl: "marker-icon-2x.png", // 默认Retina屏图标
shadowUrl: "marker-shadow.png", // 阴影图片
iconSize: [25, 41], // 图标尺寸 px
iconAnchor: [12, 41], // 锚点位置居中偏上
popupAnchor: [1, -34], // 弹出框偏移量
tooltipAnchor: [16, -28], // 弹框偏移量
shadowSize: [41, 41], // 阴影尺寸
},
_getIconUrl: function (name) { // 重写获取图片URL方法
if (typeof IconDefault.imagePath !== "string") {
IconDefault.imagePath = this._detectIconPath(); // DOM检测图片路径
}
return (
(this.options.imagePath || IconDefault.imagePath) +
Icon.prototype._getIconUrl.call(this, name)
);
},
// 使用正则表达式处理路径,从CSS的`background-image`属性中提取
_stripIconUrl: function (url) {
var strip = function (str, re, idx) {
var match = re.exec(str);
return match && match[idx];
};
path = strip(path, /^url\((['"])?(.+)\1\)$/, 2);
return path && strip(path, /^(.*)marker-icon\.png$/, 1);
},
_detectIconPath: function () {
var el = DomUtil.create("div", "leaflet-default-icon-path", document.body);
var path =
DomUtil.getStyle(el, "background-image") ||
DomUtil.getStyle(el, "backgroundImage");
document.body.removeChild(el);
path = this._stripUrl(path);
if (path) {
return path;
}
var link = document.querySelector('link[href$="leaflet.css"]');
if (!link) {
return "";
}
return link.href.substring(0, link.href.length - "leaflet.css".length - 1);
},
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# 设计亮点
- 智能路径检测:自动适配不同部署环境
- Retina支持:自动切换@2x高清图片
- CSS耦合设计:通过CSS类名
leaflet-default-icon-path
保持样式统一 - 渐进式降级:当检测失败时回退到Leaflet CSS路径
# 总结
Icon.Default
类提供了一个默认的图标实现,继承自Icon
类,通过CSS类名leaflet-default-icon-path
保持样式统一,支持Retina屏自适应,并且在检测失败时回退到Leaflet CSS路径。
编辑 (opens new window)
上次更新: 2025/04/23, 09:39:50