在本教程中,您将学习如何轻松地使用自定义的图标在地图上做标记。
查看本实例 |
为了制作自定义图标,我们通常需要两个图像——实际图标图像和它的阴影图像。对于本教程,我们采用Leaflet的logo,并由此创建出4个图像-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图标(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
创建叶状图标实例。那么为什么所有的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.");
现在来看完整的例子.