user3825080
user3825080

Reputation: 55

Set different L.divIcon style depending on geoJSON properties

I'm using L.divIcon to style markers on a Leaflet/Mapbox.js map. I have managed to set a single className to all features on the map, but I want to set different classes depending on properties associated with each feature. It seems that every configuration I've tried either comes back with a "feature is not defined" error or will only return the default l.divIcon square.

Work in progress at http://pennybeames.net/maps/MekongHydroTimeline2.html

An excerpt from the GeoJSON:

"features": [
{ "type": "Feature", "properties": { "Dam_name": "A Luoi", "Main": "false"}, "geometry": { "type": "Point", "coordinates": [ 107.18, 16.21 ] } },
{ "type": "Feature", "properties": { "Dam_name": "Banda", "Main": "true"}, "geometry": { "type": "Point", "coordinates": [ 97.93, 30.2 ] } },

I create a switch function to look for "true" and "false" and return a css class that I've defined in my stylesheet:

function getClassName(x) {
            switch(x) {
               case "true":
                    return 'circle' ;
                    //'circle set in stylesheet'
                    break;
                case "false":
                    //'leaflet-div-icon' set by leaflet stylesheet
                    return 'leaflet-div-icon';
                    break;
                default:
                    //set default to 'triangle' from my own stylesheet to test if the code 
                    //was recognizing this function and would set everything to 'triangle', 
                    //but it doesn't
                    return 'triangle';
                    break;
        }};

and then create a function to return className depending on the results found in feature.properties.Main in the geoJSON:

var setDivIcon = function(feature) {
          return {
              className: getClassName(feature.properties.Main)
          };
         }

and then create my L.divIcon:

var damIcon = L.divIcon(setDivIcon);

Later on I use pointToLayer later to add the geoJSON to the map:

 pointToLayer: function (feature, latlng) {
        return L.marker(latlng, {icon: damIcon});
    }   

But no matter what, all I get is the default leaflet-div-icon and I get zero errors in the console. What have I missed?

Upvotes: 0

Views: 3433

Answers (1)

tmcw
tmcw

Reputation: 11882

L.divIcon takes an object as input

var damIcon = L.divIcon(setDivIcon);

setDivIcon is a function that returns an object, not an object.

A correct call would be

var damIcon = L.divIcon(setDivIcon(feature));

And all together:

pointToLayer: function (feature, latlng) {
    return L.marker(latlng, { icon: L.divIcon(setDivIcon(feature)) });
}   

Upvotes: 1

Related Questions