Setting the circleMarker color based on feature property

4,372 views
Skip to first unread message

Matt Travis

unread,
Jun 12, 2013, 2:01:13 PM6/12/13
to leafl...@googlegroups.com
Hi all

I have a point layer that is using geojsonMarkerOptions to set the style of the circleMarkers.

What I would like to do is set the color of the markers based on a property in my geojson.

Is this possible as it is for polygon layer such as the democrat/republican example here: http://leafletjs.com/examples/geojson.html

var geojsonMarkerOptions = {
radius: 4,
fillColor: "#ff7800",
color: "#000",
weight: 0.5,
opacity: 1,
fillOpacity: 1
};

L.geoJson(em_homes,
{
pointToLayer: function (feature, latlng) {
        return L.circleMarker(latlng, geojsonMarkerOptions);
}
}).addTo(map);


Thanks

Matt




Matt Travis

unread,
Jun 13, 2013, 4:53:11 PM6/13/13
to leafl...@googlegroups.com
I gave this a go myself by assigning a function to the fillColor. This still did not work though. 

Any have any ideas? 

Matt


L.geoJson(em_homes,
{
pointToLayer: function (feature, latlng) {
        return L.circleMarker(latlng, 
geojsonMarkerOptions = {
radius: 4,
fillColor: function(feature){
if (feature.properties.Years === '2 to 5')
{
return { color:"Red"};
}
else
return { color:"Green"};
},
color: "red",
weight: 0.5,
opacity: 1,
fillOpacity: 1
}
);
}
}).addTo(map);

Stefan Jelkovich

unread,
Dec 6, 2013, 8:07:29 AM12/6/13
to leafl...@googlegroups.com
Hi,

exactly the same problem here. Did you get through this, Matt?

My code is based on the cloropleth example:

# return color based on value
function getValue(x) {
return x > 7 ? "#800026" :
       x > 6.5 ? "#BD0026" :
       x > 6 ? "#E31A1C" :
       x > 5.5 ? "#FC4E2A" :
       x > 5 ? "#FD8D3C" :
       x > 4.5 ? "#FEB24C" :
       x > 4 ? "#FED976" :
       "#FFEDA0";
}

# style function 
function style(feature) {
return {
"color": getValue(feature.properties.mag),
"stroke": false
};
}

# adding data from geojson file using style
var dat = L.geoJson(data, {
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, style);
}
});
dat.addTo(map);

This works fine with polygons and lines:

var dat2 = L.geoJson(data2, {
style: style
});
dat.addTo(map);

But points (circles) still have the default style.
It must be possible to style circles dynamically. Anyone knows how?

Stefan Jelkovich

unread,
Dec 6, 2013, 2:54:06 PM12/6/13
to leafl...@googlegroups.com
Got it!

I don't know exactly why, but passing the feature to the style function does the trick.

var dat = L.geoJson(data, {
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, style(feature));
}
});
dat.addTo(map);

Thanks for reading. ;-)
Stefan
Reply all
Reply to author
Forward
0 new messages