8
votes

The standard method of using a custom icon as shown in the Leaflet docs isn't working for me when I have a geojson data source. the layer is added fine, but is using the default marker icon. There's no reference to my custom icon PNG when i examine the DOM. Here's my code:

    var crossIcon = L.icon({
            iconUrl: 'plus.png',
            shadowUrl: 'marker-shadow.png',
            iconSize: [11, 11],
            shadowSize: [11, 11],
            iconAnchor: [6, 6],
            shadowAnchor: [5, 5],
            popupAnchor: [5, 5]
    });


    var points = L.geoJson(labels, {
            icon: crossIcon
    });
    map.addLayer(points);
    layerControl.addOverlay(points, 'Site Locations');

I've tried several suggestions found on SO and elsewhere with no success. plus.png is located in /lib/images/ where the default icon is also found.

2

2 Answers

17
votes

Looking at the API for GeoJson here, there is no such option when creating a L.GeoJson layer for icon. I believe you may be looking for the style option, for polylines and polygons, or the pointToLayer option for specifying icons.

The sample GeoJson page on Leaflet's website shows this scenario. Look at the icon with the baseball player.

The icon is defined in this way:

var baseballIcon = L.icon({
        iconUrl: 'baseball-marker.png',
        iconSize: [32, 37],
        iconAnchor: [16, 37],
        popupAnchor: [0, -28]
    });

The icon is applied to the L.geoJson layer through the pointToLayer option, which specifies a function; like this:

var coorsLayer = L.geoJson(coorsField, {
        pointToLayer: function (feature, latlng) {
            return L.marker(latlng, {icon: baseballIcon});
        }
    })

This function will be called for each GeoJSON point. The function will return an L.Marker that uses your specified icon.

So, to answer your question: Your code block that creates your Layer should look like this:

var points = L.geoJson(labels, {
        pointToLayer: function (feature, latlng) {
            return L.marker(latlng, {icon: crossIcon });
        }
});
0
votes

Rather than adding it as geojson layer you can add it as a marker

var crossIcon = L.icon({
        iconUrl: 'plus.png',
        shadowUrl: 'marker-shadow.png',
        iconSize: [11, 11],
        shadowSize: [11, 11],
        iconAnchor: [6, 6],
        shadowAnchor: [5, 5],
        popupAnchor: [5, 5]
});

       L.marker(icon:crossIcon);