Reputation: 3
I'm beginner in Javascript and I speak English not very well, so sorry for this. I've some code which is works but I would like to improve and simplified it.
-->what I currently have ( L.Icon is Leaflet icon ) :
let greenIcon = new L.Icon({
iconUrl: './img/marker_green.png', shadowUrl: './img/marker-shadow.png',
iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], shadowSize: [41, 41]
});
let redIcon = new L.Icon({
iconUrl: './img/marker_red.png', shadowUrl: './img/marker-shadow.png',
iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], shadowSize: [41, 41]
});
let orangeIcon = new L.Icon({
iconUrl: './img/marker_orange.png', shadowUrl: './img/marker-shadow.png',
iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], shadowSize: [41, 41]
});
-->what I would like to have if possible ( in this style ) :
let greenIcon, redIcon, orangeIcon = new L.Icon({
iconUrl: './img/marker_**xxx**.png', shadowUrl: './img/marker-shadow.png',
iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], shadowSize: [41, 41]
});
thank you in advance
Upvotes: 0
Views: 40
Reputation: 370789
The only difference is the iconUrl
, so you can make a helper function that creates an icon with the passed iconUrl
substring that differs:
const makeIcon = markerName => new L.Icon({
iconUrl: `./img/marker_${markerName}.png`, shadowUrl: './img/marker-shadow.png',
iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], shadowSize: [41, 41]
});
const greenIcon = makeIcon('green');
const redIcon = makeIcon('red');
const orangeIcon = makeIcon('orange');
But rather than having 3 separate standalone variable names for very similar values, I'd much prefer having a single object instead:
const icons = {
green: makeIcon('green'),
red: makeIcon('red'),
orange: makeIcon('orange'),
};
Then you'd reference, eg, icons.green
instead if greenIcon
.
Upvotes: 2