Map (Leaflet)
Map.tsx
import React, { useEffect, useRef } from 'react';
import { Map as LeafletMap, TileLayer, Marker, Popup } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
interface MapProps {
center: [number, number];
zoom: number;
markers: {
position: [number, number];
popupContent?: JSX.Element | string;
}[];
}
const Map = ({ center, zoom, markers }: MapProps) => {
const mapRef = useRef<LeafletMap>(null);
useEffect(() => {
// Fix for Leaflet marker icons not appearing
delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png').default,
iconUrl: require('leaflet/dist/images/marker-icon.png').default,
shadowUrl: require('leaflet/dist/images/marker-shadow.png').default,
});
}, []);
return (
<LeafletMap center={center} zoom={zoom} ref={mapRef} style={{ height: '400px', width: '100%' }}>
<TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
{markers.map((marker, index) => (
<Marker position={marker.position} key={index}>
{marker.popupContent && <Popup>{marker.popupContent}</Popup>}
</Marker>
))}
</LeafletMap>
);
};
export default Map;
Map.module.css