I've written the following javascript code using leaflet to make multiple red polylines with each having property called "active" which starts as true.
for (let i = 0; i < railLinks.length; i++) {
var polyline = new L.geoJSON(railLinks[i].polyline, {
linkNumber: railLinks[i].linkNumber,
active: true, //THIS LINE DOESNT DO WHAT I THOUGHT IT WOULD
style: function(active) {
return {
weight: 2,
color: 'red'
};
}
}).addTo(map);
polyline.on('click', function() {
set = !this.active
this.active = set;
this.setStyle({
color: getColor(set)
});
});
}
function getColor(x) {
return x ? 'black':
'#888888';
};
I'm tring to implement a toggle so that when you click a true polyline it turns to false and vice versa.
With this I would expect the first click to make grey ("false"), then black, then grey etc. Instead the first click makes black (representing true), suggesting the initial state was not true.
I would imagine the problem is with my syntax and that
active: true
is not the same property being changed as the later
this.active
as I can set the first active to any value without affecting the on click behaviour. Any ideas what this should be?
For anyone's information who comes across a similar problem, I've now solved my issue with the code below:
for (let i = 0; i < railLinks.length; i++) {
var polyline = new L.geoJSON(railLinks[i].polyline, {
linkNumber: railLinks[i].linkNumber,
}).addTo(map);
polyline.active = true;
polyline.setStyle({
weight: 2,
color: 'red'
});
polyline.on('contextmenu', function() {
set = !this.active
this.active = set;
this.setStyle({
color: getColor(set)
});
});
}
function getColor(x) {
return x ? 'black':'#888888';
};