使用自定义图标的标记
在本教程中,您将学习如何轻松地定义您自己的图标,以供您在地图上放置的标记使用。
查看这个独立示例。 |
准备图像
要创建自定义图标,我们通常需要两张图像 - 实际的图标图像和其阴影的图像。在本教程中,我们使用了 Leaflet 徽标并从中创建了四张图像 - 3 张不同颜色的叶子图像和一张用于这三张图像的阴影图像。
请注意,图像中的白色区域实际上是透明的。
创建图标
Leaflet 中的标记图标由 L.Icon 对象定义,该对象在创建标记时作为选项传递。让我们创建一个绿色的叶子图标
var greenIcon = L.icon({
iconUrl: 'leaf-green.png',
shadowUrl: 'leaf-shadow.png',
iconSize: [38, 95], // size of the icon
shadowSize: [50, 64], // size of the shadow
iconAnchor: [22, 94], // point of the icon which will correspond to marker's location
shadowAnchor: [4, 62], // the same for the shadow
popupAnchor: [-3, -76] // point from which the popup should open relative to the iconAnchor
});
现在将一个带有此图标的标记放在地图上很容易
L.marker([51.5, -0.09], {icon: greenIcon}).addTo(map);
查看这个独立示例。 |
定义图标类
如果我们需要创建几个具有许多共同点的图标怎么办?让我们定义我们自己的图标类,其中包含共享的选项,并从 L.Icon
继承!在 Leaflet 中这非常容易
var LeafIcon = L.Icon.extend({
options: {
shadowUrl: 'leaf-shadow.png',
iconSize: [38, 95],
shadowSize: [50, 64],
iconAnchor: [22, 94],
shadowAnchor: [4, 62],
popupAnchor: [-3, -76]
}
});
现在我们可以从这个类中创建我们所有的三个叶子图标,并使用它们
var greenIcon = new LeafIcon({iconUrl: 'leaf-green.png'}),
redIcon = new LeafIcon({iconUrl: 'leaf-red.png'}),
orangeIcon = new LeafIcon({iconUrl: 'leaf-orange.png'});
您可能已经注意到,我们使用了 new
关键字来创建 LeafIcon 实例。那么为什么所有 Leaflet 类都是在没有它的情况下创建的呢?答案很简单:真正的 Leaflet 类以大写字母命名(例如 L.Icon
),并且也需要使用 new
创建,但也有使用小写字母命名的快捷方式 (L.icon
),为了方便而创建,如下所示
L.icon = function (options) {
return new L.Icon(options);
};
您也可以对您的类执行相同的操作。好的,让我们最后在地图上放置一些带有这些图标的标记
L.marker([51.5, -0.09], {icon: greenIcon}).addTo(map).bindPopup("I am a green leaf.");
L.marker([51.495, -0.083], {icon: redIcon}).addTo(map).bindPopup("I am a red leaf.");
L.marker([51.49, -0.1], {icon: orangeIcon}).addTo(map).bindPopup("I am an orange leaf.");