Wolfe
Wolfe

Reputation: 97

JavaScript Leaflet - Adding custom icon images to Layer Control

I've created several map overlays and the legend/layer control is automatically created for the buttons. Ideally, I'd like to have my custom icon in place of the text "purple", etc. Is there a way to do this? I added comments with the image source file and the variable name for the icon.

//<img src="Images/purple.jpeg">  
//var purpleIcon = 'Images/purple.jpeg'

// Create an overlays object to add to the layer control
let overlayMaps = {
    "Up to $250K - purple": layers.one,
    "$250K - $500K- blue": layers.two,
    "$500K - $750K - green": layers.three,
    "$750K - $1M - yellow": layers.four,
    "Over $1M - red": layers.five,
    "School Quality": layers.six
};

Layer control with current behaivor

Upvotes: 3

Views: 1709

Answers (2)

Wolfe
Wolfe

Reputation: 97

Thank you! I ended up with this, and it works:):

let overlayMaps = {
                "<img src='Images/purple.jpeg' width = 15 /> <span>Up to $250K</span>": layers.one,
                "<img src='Images/blue.jpeg' width = 15 /> <span>$250K - $500K</span>": layers.two,
                "<img src='Images/green.jpeg' width = 15 /> <span>$500K - $750K</span>": layers.three,
                "<img src='Images/yellow.jpeg' width = 15 /> <span>$750K - $1M</span>": layers.four,
                "<img src='Images/pink.jpeg' width = 15 /> <span>$1M+</span>": layers.five,
                "School Quality": layers.six
            };

Upvotes: 3

jharris711
jharris711

Reputation: 612

According to the Control.Layers section of the Leaflet Docs:

The baseLayers and overlays parameters are object literals with layer names as keys and Layer objects as values:

{
    "<someName1>": layer1,
    "<someName2>": layer2
}

The layer names can contain HTML, which allows you to add additional styling to the items:

{"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}

So, say you are using an Icon from Font-Awesome. You could set it up your control like so:

L.control.layers(null, {
  '<i class="fas fa-bus"></i>': layer
}).addTo(map);

(Examples taken from this answer on gis.stackexchange)

Upvotes: 2

Related Questions