Search code examples
javascriptleafletgeojson

Adding custom icons in leaflet to geojson file


I got the following code

var Iconcm = L.icon({
iconUrl: 'customicon.png',
iconSize: [25, 25],
iconAnchor: [22, 94],
popupAnchor: [-10, -95]
});



$.ajax({
        dataType: "json",
        url: "pc.geojson",
        success: function(data) {
                L.geoJson(data, {
                    onEachFeature: onEachFeature
                }).addTo(map);
        }
     }).error(function() {});


        function onEachFeature(feature, layer) {
      var lines = ('Field1: ' + feature.properties.f1 + '<br>' + 'Field2: ' + feature.properties.f2)

            layer.bindPopup(lines);
        };

I want to be able to use the Iconcm instead of the default blue marker. I've tried just about every way to do it that I found on the internet to no avail. I'm new at javascript and even more at AJAX. The above code is the only way my geojson file actually worked so I would prefer to keep it that way. In addition, in the future I would like to be able to have different icons depending on the feature properties in one field. So for example if feature.properties.f3 is Type1 be customicon1, Type2 is customicon2, and so on. Is there a way to do that too? Thank you!


Solution

  • There is a method setIcon you can use.

    You want to test you only call it if the layer is actually a L.Marker

    function onEachFeature(feature, layer) {
      if (layer instanceof L.Marker) {
        layer.setIcon(Iconcm)
      }
    // ...