(例子参考leaflet官方教程的)
当我们需要用到的图标,大多数样式都是类似的,例如只有颜色不同,这个时候我们可以利用L.Icon的继承功能!
定义一个继承类:
var LeafIcon = L.Icon.extend({
options: {
shadowUrl: '././assets/img/leaf-shadow.png',
iconSize: [38, 95],
shadowSize: [50, 64],
iconAnchor: [22, 94],
shadowAnchor: [4, 62],
popupAnchor: [-3, -76]
}
});
创建图标,给不同的属性定义值
var greenIcon = new LeafIcon({ iconUrl: '././assets/img/leaf-green.png' });
var redIcon = new LeafIcon({ iconUrl: '././assets/img/leaf-red.png' });
var orangeIcon = new LeafIcon({ iconUrl: '././assets/img/leaf-orange.png' });
添加到地图中
L.marker([32, -130], { icon: greenIcon }).addTo(this.mymap).bindPopup("I am a green leaf.");
L.marker([22, -120], { icon: redIcon }).addTo(this.mymap).bindPopup("I am a red leaf.");
L.marker([13, -100], { icon: orangeIcon }).addTo(this.mymap).bindPopup("I am an orange leaf.");
效果如图: