I ran into a similar issue using Parcel
as the bundler in combination with TypeScript
and Leaflet v1.4
(installed via npm
, as well as its typings) and solved it using Gil's answer in a slightly different way.
import 'leaflet/dist/leaflet.css';
import 'leaflet-draw/dist/leaflet.draw.css';
import L, {
LatLngExpression,
FeatureGroup,
TileLayerOptions,
LayerEvent,
LeafletMouseEvent,
Marker,
Layer,
icon,
LayerGroup,
GeoJSON
} from 'leaflet';
import 'leaflet-draw';
import iconRetinaUrl from './assets/marker-icon-2x.png';
import iconUrl from './assets/marker-icon.png';
import shadowUrl from './assets/marker-shadow.png';
// Assign the imported image assets before you do anything with Leaflet.
Marker.prototype.options.icon = icon({
iconRetinaUrl,
iconUrl,
shadowUrl,
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
tooltipAnchor: [16, -28],
shadowSize: [41, 41],
});
And in another file, I added the required declarations so TypeScript
allows me to import png
images, e.g.
declare module "*.png" {
const content: string;
export default content;
}
Also notice that, in case you use a Leaflet plugin that requires access to these images, you may need to explicitly assign it too, e.g. the Leaflet draw plugin required it as well. Example:
map.addLayer(drawLayer);
const drawControl = new L.Control.Draw({
draw: {
circle: false,
circlemarker: false,
marker: {
icon: Marker.prototype.options.icon, // Assign icon explicitly
},
},
edit: {
featureGroup: drawLayer,
},
});
map.addControl(drawControl);
map.on(L.Draw.Event.CREATED, event => {
const layer = (event as LayerEvent).layer;
drawLayer.addLayer(layer);
});