I have geographic coordinates that I display to a Leaflet Map. Each feature is ether in the Category (2018, Never Covered or Other periods).

I would like to create a simple function to have different colors for my categories.

Whats the most simple way to do that?

Ive joined my blockbuilder: http://blockbuilder.org/renauld94/5678103bddc3c05c5410e1579b62944a

Can i call a function directly after adding my markers ?

var mymap = L.map('mapid').setView([10.762622, 106.660172], 13);
var pharmaciesMarkers = new L.FeatureGroup();

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'

Any examples will be usefull.


You can define a function to select the appropriate icon beforehand and call it when you instantiate the marker. Since the shipped marker is blue, you might find this resource useful: leaflet-color-markers. You would then write up a function that selects the appropriate marker color:

function colorMarker(category) {
  switch (category) {
    /*Icons need to be defined beforehand 
      according to leaflet-color-marker documentation*/
    case '2018':            return greenIcon; break; 
    case 'Never Covered':   return yellowIcon; break;
    case 'Other periods':   return redIcon; break;

var marker = L.marker([+d.lat, +d.lng], { icon: colorMarker(d.category) })
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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