0

I am trying to give a class to the markers on a Leaflet map based on geoJSON properties using Leaflet 0.7.3. I want to be able to change the color of the marker based on the crop it represents using CSS. This seems quite straight forward but everything I tried failed.

I've tried to use :

L.DomUtil.addClass(marker._icon, 'className');

and

addClass(marker, 'I use a variable here');

but it's not working. So far here is the code I'm using:

L.geoJson(geoDataF,{
pointToLayer: function(feature,latlng){
var className = feature.properties.crop;
console.log(className);
var marker = L.marker(latlng);
marker.bindPopup(feature.properties.name 
+ '<br/>' + feature.properties.location
+ '<br/>' + "Crops: " + feature.properties.crop);
console.log(marker);
return marker;
}
}).addTo(map);

I am not sure where to add some the extra code to add the class and what syntax to use. every time I use addclass, I get a message I cannot use it because it is not a function. I though about using D3 to try adding a class, but I don't fully understand leaflet and have a hard time manipulating the DOM.

1

1 Answer 1

0

Refer to this: Leaflet changing Marker color

addClass is used to add class to an html element so you have specify which elements for example: $(selector).addClass(header, 'closed'); Refer to this : https://www.w3schools.com/jquery/html_addclass.asp for use of addClass

getColor() write function in the js script to adjust your color accordingly     
function style(feature) {
        return {
            fillColor: getColor(feature.properties.density),
            weight: 2,
            opacity: 1,
            color: 'white',
            dashArray: '3',
            fillOpacity: 0.7
        };
    }
L.geoJson(statesData, {style: style}).addTo(map);

This is the example from leaflet tutorial refer to it (helps a lot) https://leafletjs.com/examples/choropleth/

Also marker is an image(png) is right so you won't be able to change its color, define different images(of markers with different colors).

1
  • Thank you for clarifying. I haven't gone through the chloropleth tutorial yet as I did not think it would be relevant for my case. I'll check it out.For some reason, I was convinced the marker was in svg format.
    – Papa
    Commented Jun 20, 2019 at 14:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.