Reputation: 504
I'm using markers with custom images in Leaflet, like this:
// A template for icons when they get instantiated on the map
var UnitIcon = L.Icon.extend({
options: {
iconSize: [40, 40],
iconAnchor: [20, 35]
}
});
function PlaceIconOnMapAtLatLng(iconURL, lat, lng)
{
var newIcon = new UnitIcon({iconUrl: iconURL});
var myMarker = L.marker([lat, lng], {icon: newIcon, draggable: true}).addTo(map);
}
The custom images sit in a folder and get read at run-time. The idea is that the user can change these and have as many as they want.
My problem is that when it comes to highlighting these, e.g. on click, there doesn't seem to be any straightforward way to do this in Leaflet. Initially I thought about just drawing a shape around the icon, but then this would be treated as its own separate thing that would be dragged around separately, whereas I want it to stay with its associated icon at all times.
A horrible first attempt would be something like having an update running constantly that sets the position of the highlight to whatever the selected marker's position is.
Or is there some way to associate objects e.g. as "children" so that when their parent object moves, the child moves with it?
I would preferably like an explicit highlight instead of doing something like changing the size or opacity of the selected marker, or giving it a pop-up, although these could be fall-back options. The reason I want a highlight is because ultimately I want to be able to highlight multiple icons at once, and having loads of pop-ups etc. doesn't seem like a very nice way of doing that.
Upvotes: 1
Views: 992
Reputation: 11338
You can add a CSS-Class to the Icon.
marker.on('click', function (e){
var layer = e.target;
if(!L.DomUtil.hasClass(layer._icon, 'dash-border')){
L.DomUtil.addClass(layer._icon,'dash-border');
}else{
L.DomUtil.removeClass(layer._icon,'dash-border');
}
});
.dash-border {
border: 2px dashed #3388ff;
background-color: #3388ff4d;
}
https://jsfiddle.net/falkedesign/r9onevq2/
Upvotes: 2