|
| 1 | +import { MapContainer, TileLayer } from "react-leaflet"; |
| 2 | +import { useContext, useEffect, useState } from "react"; |
| 3 | +import LatLongContext from "../../context/latitude-longitude-context"; |
| 4 | +import YouAreHere from "../../icons/you-are-here-icon.svg?raw"; |
| 5 | +import { getIndexedPinSvg, getPinSvg, mapArrayForOuterBounds } from "../../util/helper"; |
| 6 | +import MapMarker from "./MapMarker"; |
| 7 | +import "leaflet/dist/leaflet.css"; |
| 8 | +import "./map-wrapper.css"; |
| 9 | + |
| 10 | +function MapComponent({ mapData, additionalClass = "", withIndex }) { |
| 11 | + const { lat, long } = useContext(LatLongContext); |
| 12 | + const [outerBounds, setOuterBounds] = useState(null); |
| 13 | + function getLabelForPin(index) { |
| 14 | + return index + 1; |
| 15 | + } |
| 16 | + |
| 17 | + useEffect(() => { |
| 18 | + if (mapData.length > -1) { |
| 19 | + setOuterBounds(mapArrayForOuterBounds(mapData, lat, long)); |
| 20 | + } |
| 21 | + }, [mapData, lat, long]); |
| 22 | + |
| 23 | + if (outerBounds === null) return null; |
| 24 | + |
| 25 | + return ( |
| 26 | + <MapContainer bounds={outerBounds} className={`${additionalClass} rounded`} scrollWheelZoom={true}> |
| 27 | + <TileLayer |
| 28 | + attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' |
| 29 | + url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" |
| 30 | + /> |
| 31 | + {mapData.map(({ latitude, longitude }, index) => ( |
| 32 | + <MapMarker |
| 33 | + key={latitude} |
| 34 | + latitude={latitude} |
| 35 | + longitude={longitude} |
| 36 | + iconHtml={withIndex ? getIndexedPinSvg(getLabelForPin(index)) : getPinSvg()} |
| 37 | + /> |
| 38 | + ))} |
| 39 | + {lat && long && <MapMarker latitude={lat} longitude={long} iconHtml={YouAreHere} />} |
| 40 | + </MapContainer> |
| 41 | + ); |
| 42 | +} |
| 43 | +export default MapComponent; |
0 commit comments