2

I'm just beginning to learn coding in d3 and leaflet, i have some code that i'm experimenting with and facing some problems with setting the icon.

I wanted to change the leaflet icon depends on the data value, but i'm stuck how to show it.

This is my code,

var ActiveIcon = L.Icon.extend({
    options: {
        iconUrl: 'images/marker-icon_green.png',
        iconSize: [17, 30]
    } }); 
var NotActiveIcon = L.Icon.extend({   
     options: {
      iconUrl: 'images/marker-icon_blue.png',
      iconSize: [17, 30]   } });

d3.json("data_db.php", function(error, data) {       
  // add map markers to map layer   
   data.forEach( function(d,i) {
    // create a map marker if the lat lng is present
    if (d.latitude!=null && d.latitude!=undefined) {
      var title = d.site,
          mark = L.marker(([d.latitude, d.longitude]), {title: title});
          mark.bindPopup("<strong>" + d.site + "</strong>Status : " + d.status);
      markersLayer.addLayer(mark);
      clusterLayer.addLayer(mark);
    } 
});

How can i change the icon from the data value i have, if my d.status is equal to "Active" change as green icon, and Inactive as blue icon?

1

The documentation on custom icons is here: http://leafletjs.com/examples/custom-icons/

What you want to so is something like this (untested):

var ActiveIcon = L.Icon.extend({
        iconUrl: 'images/marker-icon_green.png',
        iconSize: [17, 30]
    }); 
var NotActiveIcon = L.Icon.extend({   
      iconUrl: 'images/marker-icon_blue.png',
      iconSize: [17, 30]   
    });

d3.json("data_db.php", function(error, data) {       
  // add map markers to map layer   
   data.forEach( function(d,i) {
    // create a map marker if the lat lng is present
    var icon = NotActiveIcon;
    if (d.status === 'active') {
      icon = ActiveIcon;
    }
    if (d.latitude!=null && d.latitude!=undefined) {
      var config = {
        title: d.title
        icon: d.icon
      };
      var title = d.site,
          mark = L.marker(([d.latitude, d.longitude]), config);
          mark.bindPopup("<strong>" + d.site + "</strong>Status : " + d.status);
      markersLayer.addLayer(mark);
      clusterLayer.addLayer(mark);
    } 
});
  • Thanks Alex, I got an error options undefined. i don't have data for d.icon, so i deleted it and replaced with icon: icon only, but still options undefined. So i got directly to change the config to icon, no error but the icon didn't change. – Jovanni Mar 4 '17 at 8:30
  • You don't need to define your options, like options = {}. See the example here: leafletjs.com/examples/custom-icons So, for each marker, just pass in the object {} with options in it. I'll edit my answer. – Alex Leith Mar 4 '17 at 23:03

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.