0
点赞
收藏
分享

微信扫一扫

Leaflet中自定义marker的icon图标

圣杰 2023-02-15 阅读 108


场景

Leaflet中添加标记、折线、圆圈、多边形、弹窗显示点击处坐标:

​​Leaflet中添加标记、折线客​​

在上面加载标记使用的是默认图标,如果要自定义图标怎么用。

官网有详细的教程

​​Markers With Custom Icons - Leaflet - a JavaScript library for interactive maps​​

Leaflet中自定义marker的icon图标_ico

注:

博客:
​​BADAO_LIUMAN众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

1、与官方教程一样,准备一张阴影照片,三张不同颜色的icon

Leaflet中自定义marker的icon图标_宽高_02

Leaflet中自定义marker的icon图标_宽高_03

2、创建ICON构造函数,相当于继承ICON,可以重新设置属性

//创建ICON构造函数,相当于继承于ICON,可以重新设置属性
var LeafIcon = L.Icon.extend({
options: {
shadowUrl: './icon/leaf-shadow.png', //阴影地址
iconSize: [38, 95], //图标宽高
shadowSize: [50, 64], //阴影宽高
iconAnchor: [22, 94], //图标锚点
shadowAnchor: [4, 62], //阴影锚点
popupAnchor: [-3, -76] //弹出框弹出位置,相对于图标锚点
}
});

3、创建多个icon

//创建多个icon
var greenIcon = new LeafIcon({
iconUrl: './icon/leaf-green.png'
}),
redIcon = new LeafIcon({
iconUrl: './icon/leaf-red.png'
}),
orangeIcon = new LeafIcon({
iconUrl: './icon/leaf-orange.png'
});

4、创建marker添加到地图上

//创建marker添加到地图上
L.marker([36.09, 120.35], {
icon: greenIcon
}).bindPopup("I am a green leaf.").addTo(map);
L.marker([36.13, 120.25], {
icon: redIcon
}).bindPopup("I am a red leaf.").addTo(map);
L.marker([36.16, 120.15], {
icon: orangeIcon
}).bindPopup("I am an orange leaf.").addTo(map);

5、完整代码

<!doctype html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>leaflet自定义标记图标</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
<style>
html,
body,
#map {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
</style>
</head>

<body>
<div id="map"></div>
<script type="text/javascript" src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<script type="text/javascript">
var map = L.map('map').setView([36.09, 120.35], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="OpenStreetMaphttps://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

//创建原始图标ICON
//创建ICON构造函数,相当于继承于ICON,可以重新设置属性
var LeafIcon = L.Icon.extend({
options: {
shadowUrl: './icon/leaf-shadow.png', //阴影地址
iconSize: [38, 95], //图标宽高
shadowSize: [50, 64], //阴影宽高
iconAnchor: [22, 94], //图标锚点
shadowAnchor: [4, 62], //阴影锚点
popupAnchor: [-3, -76] //弹出框弹出位置,相对于图标锚点
}
});

//创建多个icon
var greenIcon = new LeafIcon({
iconUrl: './icon/leaf-green.png'
}),
redIcon = new LeafIcon({
iconUrl: './icon/leaf-red.png'
}),
orangeIcon = new LeafIcon({
iconUrl: './icon/leaf-orange.png'
});

//创建marker添加到地图上
L.marker([36.09, 120.35], {
icon: greenIcon
}).bindPopup("I am a green leaf.").addTo(map);
L.marker([36.13, 120.25], {
icon: redIcon
}).bindPopup("I am a red leaf.").addTo(map);
L.marker([36.16, 120.15], {
icon: orangeIcon
}).bindPopup("I am an orange leaf.").addTo(map);
</script>
</body>

</html>

6、效果

Leaflet中自定义marker的icon图标_leaflet_04

 

举报

相关推荐

0 条评论