Leaflet/GeoJSON – Custom Marker/Icon Based on Attribute Data

geojsongeoservericonleafletwfs

I would like to add different icons to my leaflet map based on attribute data. My layer is a geojson layer, it is coming from geoserver with jsnop. I can see my data with the default marker, but when I try to change the code to add custom style I get this error:

Cannot read property 'labelAnchor' of undefined

It would be great if I can get some help.

var WFSLayer = null;
var ajax = $.ajax({
    url : URL,
    dataType : 'jsonp',
    jsonpCallback : 'getJson',
    success : function (response) {
       WFSLayer = L.geoJson(response, {
                pointToLayer: function(feature, latlng) {
                    var smallIcon = L.Icon.extend({
                        options: {
                            iconSize: [27, 27],
                             iconAnchor: [13, 27],
                             popupAnchor:  [1, -24],
                            iconUrl: 'leaflet/icons/' + feature.properties.pcp + '.png'
                        }
                    });
                    var myIcon = new smallIcon();
                    return L.marker(latlng, {icon: smallIcon});
                },
            onEachFeature: function (feature, layer) {
                popupOptions = {maxWidth: 600};
                layer.bindLabel('<h4>'+feature.properties.musno+'</h4>');
                //sidebar.setContent('<h4>'+feature.properties.musno+'</h4><br>'+'<h4>'+feature.properties.exchange_name+'</h4><br>'+feature.properties.pcp, popupOptions);
                layer.bindPopup('<h4>'+feature.properties.musno+'</h4><br>'+'<h4>'+feature.properties.exchange_name+'</h4><br>'+feature.properties.pcp
                    ,popupOptions);
            }
        }).addTo(markers.addTo(map));
    }
});

Best Answer

Ref: http://leafletjs.com/reference.html#icon

pointToLayer: function(feature, latlng) {
   var smallIcon = L.icon({
                      iconSize: [27, 27],
                      iconAnchor: [13, 27],
                      popupAnchor:  [1, -24],
                      iconUrl: 'leaflet/icons/' + feature.properties.pcp + '.png'
   });

   return L.marker(latlng, {icon: smallIcon});
}

If some markers share the same icon, you may want to create your icon objects before L.geoJson call