Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 54 additions & 16 deletions src/components/ProjectMap/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import React, { useRef, useCallback } from 'react';
import React, {
useRef,
useState,
useEffect,
useCallback,
} from 'react';
import {
MapContainer,
TileLayer,
Expand All @@ -11,17 +16,45 @@ import GestureHandler from 'components/LeafletGestureHandler';
interface Props {
className?: string;
children?: React.ReactNode;
geoJSON: GeoJSON.FeatureCollection<GeoJSON.Polygon>;
// NOTE: URL to a GeoJSON file which the map fetches and renders. fetch
// supports data: URLs too, so a client-built fallback can be passed the
// same way as a real file URL.
geoJsonUrl: string;
}

function ProjectMap(props: Props) {
const {
className,
children,
geoJSON,
geoJsonUrl,
} = props;

const mapRef = useRef<Map>(null);
const [geoJson, setGeoJson] = useState<GeoJSON.GeoJsonObject>();

useEffect(() => {
// NOTE: Handle component dismount gracefully
let active = true;

async function loadGeoJson(url: string) {
try {
const res = await fetch(url);
const data = await res.json();
if (active) {
setGeoJson(data);
}
} catch (err) {
// eslint-disable-next-line no-console
console.error('Failed fetching map GeoJSON', url, err);
}
}

loadGeoJson(geoJsonUrl);

return () => {
active = false;
};
}, [geoJsonUrl]);

const handleGeoJSONAdd = useCallback(
(layer: LayerEvent) => {
Expand All @@ -43,19 +76,24 @@ function ProjectMap(props: Props) {
minZoom={1}
worldCopyJump
>
<GeoJSON
data={geoJSON}
eventHandlers={{
add: handleGeoJSONAdd,
}}
pathOptions={{
fillColor: '#AABE5D',
color: '#AABE5D',
weight: 2,
opacity: 1,
fillOpacity: 0.1,
}}
/>
{geoJson && (
<GeoJSON
// NOTE: react-leaflet's GeoJSON only reads `data` on mount,
// so key it to the source to remount when the data changes.
key={geoJsonUrl}
data={geoJson}
eventHandlers={{
add: handleGeoJSONAdd,
}}
pathOptions={{
fillColor: '#AABE5D',
color: '#AABE5D',
weight: 2,
opacity: 1,
fillOpacity: 0.1,
}}
/>
)}
<GestureHandler />
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>'
Expand Down
4 changes: 2 additions & 2 deletions src/pages/[locale]/projects/[id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -503,11 +503,11 @@ function Project(props: Props) {
})
)}
>
{aoiGeometryFeature && (
{aoiDownload && (
<div className={styles.mapContainer}>
<DynamicProjectMap
className={styles.projectsMap}
geoJSON={aoiGeometryFeature}
geoJsonUrl={aoiDownload.url}
/>
</div>
)}
Expand Down
Loading