如何在传单 - 杂食性图层上使用自定义图标?

时间:2018-05-31 12:13:22

标签: javascript leaflet

我试图更改其中一个KML图层的默认标记。我正在使用传单 - 杂食动物。

这是我已有的代码。标记不会更改为图像,图层控件仅显示文本,即使img位在代码中也是如此。

标记代码:

var redIcon = L.icon({
    iconUrl: 'icon.png',
    iconSize:     [20, 24],
    iconAnchor:   [12, 55], 
    popupAnchor:  [-3, -76] 
});

var nissanLayer = omnivore.kml('icons.kml')
    .on('ready', function() {
        map.fitBounds(customLayer.getBounds());
         //change the icons for each point on the map
         // After the 'ready' event fires, the GeoJSON contents are accessible
        // and you can iterate through layers to bind custom popups.
        customLayer.eachLayer(function(layer) {
            // See the `.bindPopup` documentation for full details. This
            // dataset has a property called `name`: your dataset might not,
            // so inspect it and customize to taste.
            layer.icon
            layer.bindPopup('<img src="icon.png" height="24"><br><h3>'+layer.feature.properties.name+'</h3>');
        });
    })
.addTo(map);


  var marker = new L.Marker(customLayer, {icon:redIcon});
      map.addLayer(marker);

2 个答案:

答案 0 :(得分:3)

你好像忽略了setIcon() method of L.Marker。在调用任何L.Layer功能之前,我还检查L.Marker实际上是L.Marker,只是为了代码健全。 e.g:

var redIcon = L.icon({ /* ... */ });

var omnivoreLayer = omnivore.kml('icons.kml')
    .on('ready', function() {
        omnivoreLayer.eachLayer(function(layer) {

            if (layer instanceof L.Marker) {
                layer.setIcon(redIcon);
            }
        });
    })
    .addTo(map);

但是,Leaflet-Omnivore documentation表示将自定义样式应用于Omnivore图层的更好方法是使用所需的过滤器和样式创建L.GeoJSON实例,然后将其传递给Omnivore工厂方法。我建议你阅读Leaflet tutorial on GeoJSON以熟悉这一点。

因此,不依赖于on('ready')事件处理程序(在创建标记后更改标记),这样可以通过直接创建标记来节省一小部分时间。期望的风格:

var omnivoreStyleHelper = L.geoJSON(null, {
    pointToLayer: function (feature, latlng) {
        return L.marker(latlng, {icon: redIcon});
    }
});

var omnivoreLayer = omnivore.kml('icons.kml', null, omnivoreStyleHelper);

答案 1 :(得分:0)

我没有使用传单,但我做了一个小项目,我将图标设置为图像。

var redIcon = L.icon({
    iconUrl: 'red-x.png',

   iconSize:     [25, 25], // size of the icon
   iconAnchor:   [12, 55], // point of the icon which will correspond to 
   marker's location
   popupAnchor:  [-3, -76] // point from which the popup should open 
   relative to the iconAnchor
});


  var marker = new L.Marker(markerLocation, {icon:redIcon});
      mymap.addLayer(marker);

不确定这是多么有用。

链接有一个关注指南,可能更有用https://leafletjs.com/examples/custom-icons/