Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve map performance #1069

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 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
5 changes: 0 additions & 5 deletions packages/website/src/helpers/bleachingAlertIntervals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,6 @@ export const findIntervalByLevel = (
}
};

export const findMaxLevel = (intervals: Interval[]): number => {
const levels = intervals.map((item) => item.level);
return Math.max(...levels);
};

export const getColorByLevel = (level: number): string => {
return findIntervalByLevel(level).color;
};
Expand Down
45 changes: 21 additions & 24 deletions packages/website/src/routes/HomeMap/Map/Markers/SiteMarker.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Marker, useLeaflet } from 'react-leaflet';
import { Marker } from 'react-leaflet';
import { useDispatch, useSelector } from 'react-redux';
import React from 'react';
import { Site } from 'store/Sites/types';
import {
siteOnMapSelector,
setSiteOnMap,
setSearchResult,
isSelectedOnMapSelector,
} from 'store/Homepage/homepageSlice';
import { useMarkerIcon } from 'helpers/map';
import { hasDeployedSpotter } from 'helpers/siteUtils';
Expand All @@ -21,46 +21,43 @@ const LNG_OFFSETS = [-360, 0, 360];

interface SiteMarkerProps {
site: Site;
setCenter: (inputMap: L.Map, latLng: [number, number], zoom: number) => void;
}

/**
* All in one site marker with icon, offset duplicates, and popup built in.
*/
export default function SiteMarker({ site, setCenter }: SiteMarkerProps) {
const siteOnMap = useSelector(siteOnMapSelector);
const { map } = useLeaflet();
export const SiteMarker = React.memo(({ site }: SiteMarkerProps) => {
const isSelected = useSelector(isSelectedOnMapSelector(site.id));
const dispatch = useDispatch();
const { tempWeeklyAlert } = site.collectionData || {};
const markerIcon = useMarkerIcon(
hasDeployedSpotter(site),
site.hasHobo,
siteOnMap?.id === site.id,
isSelected,
alertColorFinder(tempWeeklyAlert),
alertIconFinder(tempWeeklyAlert),
);

if (site.polygon.type !== 'Point') return null;

const [lng, lat] = site.polygon.coordinates;

return (
<>
{LNG_OFFSETS.map((offset) => {
return (
<Marker
onClick={() => {
if (map) setCenter(map, [lat, lng], 6);
dispatch(setSearchResult());
dispatch(setSiteOnMap(site));
}}
key={`${site.id}-${offset}`}
icon={markerIcon}
position={[lat, lng + offset]}
>
<Popup site={site} autoOpen={offset === 0} />
</Marker>
);
})}
{LNG_OFFSETS.map((offset) => (
<Marker
onClick={() => {
dispatch(setSearchResult());
dispatch(setSiteOnMap(site));
}}
key={`${site.id}-${offset}`}
icon={markerIcon}
position={[lat, lng + offset]}
data-alert={tempWeeklyAlert}
>
{isSelected && <Popup site={site} autoOpen={offset === 0} />}
</Marker>
))}
</>
);
}
});
106 changes: 42 additions & 64 deletions packages/website/src/routes/HomeMap/Map/Markers/index.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,22 @@
import { useSelector } from 'react-redux';
import { LayerGroup, useLeaflet } from 'react-leaflet';
import { useLeaflet } from 'react-leaflet';
import MarkerClusterGroup from 'react-leaflet-markercluster';
import React, { useCallback, useEffect, useState, useMemo } from 'react';
import React, { useEffect, useState, useMemo } from 'react';
import L from 'leaflet';
import { sitesToDisplayListSelector } from 'store/Sites/sitesListSlice';
import { Site } from 'store/Sites/types';
import { siteOnMapSelector } from 'store/Homepage/homepageSlice';
import 'leaflet/dist/leaflet.css';
import 'react-leaflet-markercluster/dist/styles.min.css';
import { CollectionDetails } from 'store/Collection/types';
import {
findIntervalByLevel,
findMaxLevel,
getColorByLevel,
Interval,
} from 'helpers/bleachingAlertIntervals';
import SiteMarker from './SiteMarker';
import { getColorByLevel } from 'helpers/bleachingAlertIntervals';
import { SiteMarker } from './SiteMarker';

const clusterIcon = (cluster: any) => {
const alerts: Interval[] = cluster.getAllChildMarkers().map((marker: any) => {
const { site } = marker?.options?.children?.[0]?.props || {};
const { tempWeeklyAlert } = site?.collectionData || {};
return findIntervalByLevel(tempWeeklyAlert);
});
const color = getColorByLevel(findMaxLevel(alerts));
const alertLevels = cluster
.getAllChildMarkers()
.map((marker: any) => marker?.options?.['data-alert'] ?? 0);
const maxLevel = Math.max(...alertLevels);
const color = getColorByLevel(maxLevel);
const count = cluster.getChildCount();
return L.divIcon({
html: `<div style="background-color: ${color}"><span>${count}</span></div>`,
Expand All @@ -38,65 +31,50 @@ export const SiteMarkers = ({ collection }: SiteMarkersProps) => {
() => collection?.sites || storedSites || [],
[collection?.sites, storedSites],
);
const siteOnMap = useSelector(siteOnMapSelector);
const { map } = useLeaflet();
const [visibleSites, setVisibleSites] = useState(sitesList);

const setCenter = useCallback(
(inputMap: L.Map, latLng: [number, number], zoom: number) => {
const maxZoom = Math.max(inputMap.getZoom() || 6, zoom);
const pointBounds = L.latLngBounds(latLng, latLng);
inputMap.flyToBounds(pointBounds, {
duration: 2,
maxZoom,
paddingTopLeft: L.point(0, 200),
});
},
[],
);

const filterSitesByViewport = useCallback(() => {
if (!map) return;

const bounds = map.getBounds();
const filtered = sitesList.filter((site: Site) => {
if (!site.polygon || site.polygon.type !== 'Point') return false;
const [lng, lat] = site.polygon.coordinates;
return bounds.contains([lat, lng]);
});
setVisibleSites(filtered);
}, [map, sitesList]);
const [visibleSitesMap, setVisibleSitesMap] = useState<
Record<string, boolean>
>({});

useEffect(() => {
// Incrementally mount visible site markers on map
// Avoid mounting all sites at once, mount only the visible ones and don't umount them

if (!map) return undefined;
const mountSitesInViewport = () => {
if (!map) return;
const bounds = map.getBounds();
const filtered: Record<string, boolean> = {};
sitesList.forEach((site: Site) => {
if (!site.polygon || site.polygon.type !== 'Point') return;
const [lng, lat] = site.polygon.coordinates;
if (bounds.contains([lat, lng])) {
// eslint-disable-next-line fp/no-mutation
filtered[site.id] = true;
}
});
// Keep the previous markers and add the new visible sites
setVisibleSitesMap((prev) => ({ ...prev, ...filtered }));
};

filterSitesByViewport();
map.on('moveend', filterSitesByViewport);
mountSitesInViewport();
map.on('moveend', mountSitesInViewport);

return () => {
map.off('moveend', filterSitesByViewport);
map.off('moveend', mountSitesInViewport);
return undefined;
};
}, [map, filterSitesByViewport]);

useEffect(() => {
if (map && siteOnMap?.polygon.type === 'Point') {
const [lng, lat] = siteOnMap.polygon.coordinates;
setCenter(map, [lat, lng], 6);
}
}, [map, siteOnMap, setCenter]);
}, [map, sitesList]);

return (
<LayerGroup>
<MarkerClusterGroup
iconCreateFunction={clusterIcon}
disableClusteringAtZoom={1}
>
{visibleSites.map((site: Site) => (
<SiteMarker key={site.id} site={site} setCenter={setCenter} />
))}
</MarkerClusterGroup>
</LayerGroup>
<MarkerClusterGroup iconCreateFunction={clusterIcon}>
{sitesList.map(
(site: Site) =>
visibleSitesMap[site.id] && (
<SiteMarker key={`${site.id}`} site={site} />
),
)}
</MarkerClusterGroup>
);
};

Expand Down
21 changes: 20 additions & 1 deletion packages/website/src/routes/HomeMap/Map/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ import {
import { Alert } from '@material-ui/lab';
import MyLocationIcon from '@material-ui/icons/MyLocation';
import { sitesListLoadingSelector } from 'store/Sites/sitesListSlice';
import { searchResultSelector } from 'store/Homepage/homepageSlice';
import {
searchResultSelector,
siteOnMapSelector,
} from 'store/Homepage/homepageSlice';
import { CollectionDetails } from 'store/Collection/types';
import { MapLayerName } from 'store/Homepage/types';
import { mapConstants } from 'constants/maps';
Expand Down Expand Up @@ -68,6 +71,7 @@ const HomepageMap = ({
useState<string>();
const loading = useSelector(sitesListLoadingSelector);
const searchResult = useSelector(searchResultSelector);
const siteOnMap = useSelector(siteOnMapSelector);
const ref = useRef<Map>(null);

const onLocationSearch = () => {
Expand Down Expand Up @@ -116,6 +120,21 @@ const HomepageMap = ({
}
}, [searchResult]);

useEffect(() => {
const map = ref.current?.leafletElement;
if (map && siteOnMap?.polygon.type === 'Point') {
const [lng, lat] = siteOnMap.polygon.coordinates;
const latLng = [lat, lng] as [number, number];
const pointBounds = L.latLngBounds(latLng, latLng);
const maxZoom = Math.max(map.getZoom() || 6);
map.flyToBounds(pointBounds, {
duration: 2,
maxZoom,
paddingTopLeft: L.point(0, 200),
});
}
}, [siteOnMap]);

const onBaseLayerChange = ({ name }: LayersControlEvent) => {
setLegendName(name);
};
Expand Down
3 changes: 3 additions & 0 deletions packages/website/src/store/Homepage/homepageSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ const homepageSlice = createSlice({
},
});

export const isSelectedOnMapSelector = (id: number) => (state: RootState) =>
state.homepage.siteOnMap?.id === id;

export const siteOnMapSelector = (
state: RootState,
): HomePageState['siteOnMap'] => state.homepage.siteOnMap;
Expand Down
Loading