Reputation: 329
I use Leaflet to present some points on map. However, I want to place different marker depending on some parameters. The question is: is it possible to import in React whole directory of my custom markers (.png files)? Currently it looks like this:
import icon from 'leaflet/dist/images/marker-icon.png';
And then
render() {
const position = [54.40, 18.60];
let DefaultIcon = L.icon({
iconUrl: icon,
shadowUrl: iconShadow,
iconSize: [24, 36],
iconAnchor: [12, 36],
popupAnchor: [0, -25]
});
So for one marker there's one import at the top.
Say I want to import few icons, so do I have to import every single .png
file separately at the top of my react component? Or is there a way to just import a directory and then place only path to appropriate icon file?
Upvotes: 0
Views: 2494
Reputation: 11
You can do this kinda thing:
if ( feature.properties.name === "NONE") {
var shadow = "Project/data/images/NONE.png";
} else {
var shadow = "Project/data/images/shadow.png";
}
var flag = L.icon({
shadowUrl: shadow,
iconUrl: `Project/data/images/${feature.properties.name }.png`,
Upvotes: 0
Reputation: 59338
For that matter a webpack feature called dynamic require could be utilized, for example with expression:
const icon = L.icon({
iconUrl: require(`../public/custom-icons/${item.iconName}`),
});
icons images dynamically get loaded from /public/custom-icons/
folder and included in bundle
Example
const MapExample = () => {
const data = [
{ position: { lat: -33.8478796, lng: 150.7918932 }, title: "Sydney", "iconName" : "leaf-red.png" },
{ position: { lat: -31.954654, lng: 115.8399823 }, title: "Perth ", "iconName" : "leaf-green.png" }
];
return (
<Map center={{ lat: -24.9929159, lng: 115.2297986 }} zoom={4}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
{data.map((item, idx) => {
const icon = L.icon({
iconUrl: require(`../public/custom-icons/${item.iconName}`),
iconSize: [24, 36],
iconAnchor: [12, 36],
popupAnchor: [0, -25]
});
return (
<Marker key={idx} icon={icon} position={item.position}>
<Popup>{item.title}</Popup>
</Marker>
);
})}
</Map>
);
};
Here is a demo
Upvotes: 1