Skip to content

Commit 076d147

Browse files
Aries-0331zhouwenxuan
andauthored
Optimize/map marker cluster (#7421)
* click overlay to preview * updatea cluster plugin --------- Co-authored-by: zhouwenxuan <[email protected]>
1 parent 0b0e471 commit 076d147

File tree

7 files changed

+144
-1867
lines changed

7 files changed

+144
-1867
lines changed
Lines changed: 29 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,69 +1,69 @@
1-
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
1+
import React, { useEffect, useMemo } from 'react';
22
import { getFileNameFromRecord, getFileTypeFromRecord, getImageLocationFromRecord, getParentDirFromRecord, getRecordIdFromRecord } from '../../utils/cell';
3-
import ClusterPhotos from './cluster-photos';
43
import MapView from './map-view';
54
import { PREDEFINED_FILE_TYPE_OPTION_KEY } from '../../constants';
65
import { useMetadataView } from '../../hooks/metadata-view';
76
import { Utils } from '../../../utils/utils';
8-
import { gettext, siteRoot, thumbnailSizeForGrid } from '../../../utils/constants';
7+
import { fileServerRoot, siteRoot, thumbnailSizeForGrid, thumbnailSizeForOriginal } from '../../../utils/constants';
98
import { isValidPosition } from '../../utils/validate';
109
import { gcj02_to_bd09, wgs84_to_gcj02 } from '../../../utils/coord-transform';
1110
import { PRIVATE_FILE_TYPE } from '../../../constants';
1211

1312
import './index.css';
1413

1514
const Map = () => {
16-
const [showCluster, setShowCluster] = useState(false);
1715
const { metadata, viewID, updateCurrentPath } = useMetadataView();
1816

19-
const clusterRef = useRef([]);
20-
2117
const repoID = window.sfMetadataContext.getSetting('repoID');
18+
const repoInfo = window.sfMetadataContext.getSetting('repoInfo');
2219

2320
const images = useMemo(() => {
2421
return metadata.rows
2522
.map(record => {
2623
const recordType = getFileTypeFromRecord(record);
2724
if (recordType !== PREDEFINED_FILE_TYPE_OPTION_KEY.PICTURE) return null;
2825
const id = getRecordIdFromRecord(record);
29-
const fileName = getFileNameFromRecord(record);
26+
const name = getFileNameFromRecord(record);
3027
const parentDir = getParentDirFromRecord(record);
31-
const path = Utils.encodePath(Utils.joinPath(parentDir, fileName));
32-
const src = `${siteRoot}thumbnail/${repoID}/${thumbnailSizeForGrid}${path}`;
28+
const path = Utils.encodePath(Utils.joinPath(parentDir, name));
3329
const location = getImageLocationFromRecord(record);
3430
if (!location) return null;
3531
const { lng, lat } = location;
3632
if (!isValidPosition(lng, lat)) return null;
3733
const gcPosition = wgs84_to_gcj02(lng, lat);
3834
const bdPosition = gcj02_to_bd09(gcPosition.lng, gcPosition.lat);
39-
return { id, src, lng: bdPosition.lng, lat: bdPosition.lat };
40-
})
41-
.filter(Boolean);
42-
}, [repoID, metadata.rows]);
4335

44-
const openCluster = useCallback((clusterIds) => {
45-
clusterRef.current = clusterIds;
46-
updateCurrentPath(`/${PRIVATE_FILE_TYPE.FILE_EXTENDED_PROPERTIES}/${viewID}/${gettext('Location')}`);
47-
setShowCluster(true);
48-
// eslint-disable-next-line react-hooks/exhaustive-deps
49-
}, [viewID, updateCurrentPath]);
36+
const repoEncrypted = repoInfo.encrypted;
37+
const cacheBuster = new Date().getTime();
38+
const fileExt = name.substr(name.lastIndexOf('.') + 1).toLowerCase();
39+
let thumbnail = '';
40+
const isGIF = fileExt === 'gif';
41+
if (repoEncrypted || isGIF) {
42+
thumbnail = `${siteRoot}repo/${repoID}/raw${path}?t=${cacheBuster}`;
43+
} else {
44+
thumbnail = `${siteRoot}thumbnail/${repoID}/${thumbnailSizeForOriginal}${path}`;
45+
}
5046

51-
const closeCluster = useCallback(() => {
52-
clusterRef.current = [];
53-
updateCurrentPath(`/${PRIVATE_FILE_TYPE.FILE_EXTENDED_PROPERTIES}/${viewID}`);
54-
setShowCluster(false);
55-
}, [viewID, updateCurrentPath]);
47+
return {
48+
id,
49+
name,
50+
src: `${siteRoot}thumbnail/${repoID}/${thumbnailSizeForGrid}${path}`,
51+
url: `${siteRoot}lib/${repoID}/file${path}`,
52+
downloadURL: `${fileServerRoot}repos/${repoID}/files${path}?op=download`,
53+
thumbnail,
54+
parentDir,
55+
location: { lng: bdPosition.lng, lat: bdPosition.lat }
56+
};
57+
})
58+
.filter(Boolean);
59+
}, [repoID, repoInfo.encrypted, metadata]);
5660

5761
useEffect(() => {
5862
updateCurrentPath(`/${PRIVATE_FILE_TYPE.FILE_EXTENDED_PROPERTIES}/${viewID}`);
5963
// eslint-disable-next-line react-hooks/exhaustive-deps
6064
}, []);
6165

62-
if (showCluster) {
63-
return (<ClusterPhotos photoIds={clusterRef.current} onClose={closeCluster} />);
64-
}
65-
66-
return (<MapView images={images} onOpenCluster={openCluster} />);
66+
return (<MapView images={images} />);
6767
};
6868

6969
export default Map;

frontend/src/metadata/views/map/map-view/index.js

Lines changed: 83 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
1+
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
22
import PropTypes from 'prop-types';
33
import loadBMap, { initMapInfo } from '../../../../utils/map-utils';
44
import { appAvatarURL, baiduMapKey, googleMapKey, mediaUrl } from '../../../../utils/constants';
@@ -8,21 +8,27 @@ import { MAP_TYPE as MAP_PROVIDER } from '../../../../constants';
88
import { EVENT_BUS_TYPE, MAP_TYPE, STORAGE_MAP_CENTER_KEY, STORAGE_MAP_TYPE_KEY, STORAGE_MAP_ZOOM_KEY } from '../../../constants';
99
import { createBMapGeolocationControl, createBMapZoomControl } from './control';
1010
import { customAvatarOverlay, customImageOverlay } from './overlay';
11+
import ModalPortal from '../../../../components/modal-portal';
12+
import ImageDialog from '../../../../components/dialog/image-dialog';
1113

1214
import './index.css';
1315

1416
const DEFAULT_POSITION = { lng: 104.195, lat: 35.861 };
1517
const DEFAULT_ZOOM = 4;
16-
const BATCH_SIZE = 500;
1718
const MAX_ZOOM = 21;
1819
const MIN_ZOOM = 3;
1920

20-
const MapView = ({ images, onOpenCluster }) => {
21+
const MapView = ({ images }) => {
22+
const [imageIndex, setImageIndex] = useState(0);
23+
const [clusterLeaveIds, setClusterLeaveIds] = useState([]);
24+
2125
const mapInfo = useMemo(() => initMapInfo({ baiduMapKey, googleMapKey }), []);
26+
const clusterLeaves = useMemo(() => images.filter(image => clusterLeaveIds.includes(image.id)), [images, clusterLeaveIds]);
2227

2328
const mapRef = useRef(null);
2429
const clusterRef = useRef(null);
2530
const batchIndexRef = useRef(0);
31+
const clickTimeoutRef = useRef(null);
2632

2733
const saveMapState = useCallback(() => {
2834
if (!mapRef.current) return;
@@ -68,44 +74,57 @@ const MapView = ({ images, onOpenCluster }) => {
6874
return { center: savedCenter, zoom: savedZoom };
6975
}, []);
7076

71-
const onClickMarker = useCallback((e, markers) => {
72-
saveMapState();
73-
const imageIds = markers.map(marker => marker._id);
74-
onOpenCluster(imageIds);
75-
}, [onOpenCluster, saveMapState]);
76-
77-
const renderMarkersBatch = useCallback(() => {
78-
if (!images.length || !clusterRef.current) return;
79-
80-
const startIndex = batchIndexRef.current * BATCH_SIZE;
81-
const endIndex = Math.min(startIndex + BATCH_SIZE, images.length);
82-
const batchMarkers = [];
83-
84-
for (let i = startIndex; i < endIndex; i++) {
85-
const image = images[i];
86-
const { lng, lat } = image;
87-
const point = new window.BMapGL.Point(lng, lat);
88-
const marker = customImageOverlay(point, image, {
89-
callback: (e, markers) => onClickMarker(e, markers)
90-
});
91-
batchMarkers.push(marker);
92-
}
93-
clusterRef.current.addMarkers(batchMarkers);
94-
95-
if (endIndex < images.length) {
96-
batchIndexRef.current += 1;
97-
setTimeout(renderMarkersBatch, 20); // Schedule the next batch
98-
}
99-
}, [images, onClickMarker]);
77+
const getPoints = useCallback((images) => {
78+
if (!window.Cluster || !images) return [];
79+
return window.Cluster.pointTransformer(images, (data) => ({
80+
point: [data.location.lng, data.location.lat],
81+
properties: {
82+
id: data.id,
83+
src: data.src,
84+
}
85+
}));
86+
}, []);
10087

10188
const initializeCluster = useCallback(() => {
102-
if (mapRef.current && !clusterRef.current) {
103-
clusterRef.current = new window.BMapLib.MarkerCluster(mapRef.current, {
104-
callback: (e, markers) => onClickMarker(e, markers),
105-
maxZoom: 21,
106-
});
107-
}
108-
}, [onClickMarker]);
89+
clusterRef.current = new window.Cluster.View(mapRef.current, {
90+
clusterRadius: 80,
91+
updateRealTime: true,
92+
fitViewOnClick: false,
93+
isAnimation: true,
94+
clusterMap: (properties) => ({ src: properties.src, id: properties.id }),
95+
clusterReduce: (acc, properties) => {
96+
if (!acc.properties) {
97+
acc.properties = [];
98+
}
99+
acc.properties.push(properties);
100+
},
101+
renderClusterStyle: {
102+
type: window.Cluster.ClusterRender.DOM,
103+
inject: (props) => customImageOverlay(props),
104+
},
105+
});
106+
107+
clusterRef.current.setData(getPoints(images));
108+
109+
clusterRef.current.on(window.Cluster.ClusterEvent.CLICK, (element) => {
110+
if (clickTimeoutRef.current) {
111+
clearTimeout(clickTimeoutRef.current);
112+
clickTimeoutRef.current = null;
113+
return;
114+
} else {
115+
clickTimeoutRef.current = setTimeout(() => {
116+
let imageIds = [];
117+
if (element.isCluster) {
118+
imageIds = clusterRef.current.getLeaves(element.id).map(item => item.properties.id).filter(Boolean);
119+
} else {
120+
imageIds = [element.properties.id];
121+
}
122+
clickTimeoutRef.current = null;
123+
setClusterLeaveIds(imageIds);
124+
}, 300);
125+
}
126+
});
127+
}, [images, getPoints]);
109128

110129
const renderBaiduMap = useCallback(() => {
111130
if (!mapRef.current || !window.BMapGL.Map) return;
@@ -141,8 +160,20 @@ const MapView = ({ images, onOpenCluster }) => {
141160
initializeCluster();
142161

143162
batchIndexRef.current = 0;
144-
renderMarkersBatch();
145-
}, [addMapController, initializeCluster, initializeUserMarker, renderMarkersBatch, getBMapType, loadMapState]);
163+
}, [addMapController, initializeCluster, initializeUserMarker, getBMapType, loadMapState]);
164+
165+
const handleClose = useCallback(() => {
166+
setImageIndex(0);
167+
setClusterLeaveIds([]);
168+
}, []);
169+
170+
const moveToPrevImage = useCallback(() => {
171+
setImageIndex((imageIndex + clusterLeaves.length - 1) % clusterLeaves.length);
172+
}, [imageIndex, clusterLeaves.length]);
173+
174+
const moveToNextImage = useCallback(() => {
175+
setImageIndex((imageIndex + 1) % clusterLeaves.length);
176+
}, [imageIndex, clusterLeaves.length]);
146177

147178
useEffect(() => {
148179
const modifyMapTypeSubscribe = window.sfMetadataContext.eventBus.subscribe(EVENT_BUS_TYPE.MODIFY_MAP_TYPE, (newType) => {
@@ -172,6 +203,17 @@ const MapView = ({ images, onOpenCluster }) => {
172203
return (
173204
<div className="sf-metadata-view-map">
174205
<div className="sf-metadata-map-container" ref={mapRef} id="sf-metadata-map-container"></div>
206+
{clusterLeaveIds.length > 0 && (
207+
<ModalPortal>
208+
<ImageDialog
209+
imageItems={clusterLeaves}
210+
imageIndex={imageIndex}
211+
closeImagePopup={handleClose}
212+
moveToPrevImage={moveToPrevImage}
213+
moveToNextImage={moveToNextImage}
214+
/>
215+
</ModalPortal>
216+
)}
175217
</div>
176218
);
177219
};
Lines changed: 26 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -1,86 +1,36 @@
1-
import { Utils } from '../../../../../utils/utils';
1+
const OVERLAY_SIZE = 80;
22

3-
const customImageOverlay = (center, image, callback) => {
4-
class ImageOverlay extends window.BMapLib.TextIconOverlay {
5-
constructor(center, image, { callback } = {}) {
6-
super(center, '', { styles: [] });
7-
this._center = center;
8-
this._URL = image.src;
9-
this._id = image.id;
10-
this._callback = callback;
11-
}
3+
const customImageOverlay = (props) => {
4+
const { isCluster, pointCount, reduces } = props;
5+
const src = isCluster ? reduces.src : props.src;
126

13-
initialize(map) {
14-
this._map = map;
15-
const div = document.createElement('div');
16-
div.style.position = 'absolute';
17-
div.style.zIndex = 2000;
18-
map.getPanes().markerPane.appendChild(div);
19-
this._div = div;
7+
const div = document.createElement('div');
8+
div.style.position = 'absolute';
209

21-
const imageElement = `<img src=${this._URL} />`;
22-
const htmlString =
23-
`
24-
<div class="custom-image-container">
25-
${this._URL ? imageElement : '<div class="empty-custom-image-wrapper"></div>'}
26-
</div>
27-
`;
28-
const labelDocument = new DOMParser().parseFromString(htmlString, 'text/html');
29-
const label = labelDocument.body.firstElementChild;
30-
this._div.append(label);
10+
const container = document.createElement('div');
11+
container.className = 'custom-image-container';
3112

32-
const eventHandler = (event) => {
33-
event.preventDefault();
34-
this._callback && this._callback(event, [{ _id: this._id }]);
35-
};
36-
37-
if (Utils.isDesktop()) {
38-
let clickTimeout;
39-
this._div.addEventListener('click', (event) => {
40-
if (clickTimeout) {
41-
clearTimeout(clickTimeout);
42-
clickTimeout = null;
43-
return;
44-
}
45-
clickTimeout = setTimeout(() => {
46-
eventHandler(event);
47-
clickTimeout = null;
48-
}, 300);
49-
});
50-
this._div.addEventListener('dblclick', (e) => {
51-
e.preventDefault();
52-
if (clickTimeout) {
53-
clearTimeout(clickTimeout);
54-
clickTimeout = null;
55-
}
56-
});
57-
} else {
58-
this._div.addEventListener('touchend', eventHandler);
59-
}
60-
61-
return div;
62-
}
63-
64-
draw() {
65-
const position = this._map.pointToOverlayPixel(this._center);
66-
this._div.style.left = position.x - 40 + 'px'; // 40 is 1/2 container height
67-
this._div.style.top = position.y - 88 + 'px'; // 80 is container height and 8 is icon height
68-
}
69-
70-
getImageUrl() {
71-
return image.src || '';
72-
}
73-
74-
getPosition() {
75-
return center;
76-
}
13+
if (isCluster && pointCount > 1) {
14+
const customImageNumber = document.createElement('span');
15+
customImageNumber.className = 'custom-image-number';
16+
customImageNumber.innerText = pointCount < 1000 ? pointCount : '1k+';
17+
container.appendChild(customImageNumber);
18+
}
7719

78-
getMap() {
79-
return this._map || null;
80-
}
20+
if (src) {
21+
const imageElement = document.createElement('img');
22+
imageElement.src = src;
23+
imageElement.width = OVERLAY_SIZE;
24+
imageElement.height = OVERLAY_SIZE;
25+
container.appendChild(imageElement);
26+
} else {
27+
const emptyImageWrapper = document.createElement('div');
28+
emptyImageWrapper.className = 'empty-custom-image-wrapper';
29+
container.appendChild(emptyImageWrapper);
8130
}
8231

83-
return new ImageOverlay(center, image, callback);
32+
div.appendChild(container);
33+
return div;
8434
};
8535

8636
export default customImageOverlay;

frontend/src/utils/map-utils.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,12 @@ export const loadMapSource = (type, key, callback) => {
3131

3232
export default function loadBMap(ak) {
3333
return new Promise((resolve, reject) => {
34+
if (typeof window.BMapGL !== 'undefined' && document.querySelector(`script[src*="${mediaUrl}js/map/cluster.js"]`)) {
35+
resolve(true);
36+
return;
37+
}
3438
asyncLoadBaiduJs(ak)
35-
.then(() => asyncLoadJs(`${mediaUrl}/js/map/text-icon-overlay.js?v=${STATIC_RESOURCE_VERSION}`))
36-
.then(() => asyncLoadJs(`${mediaUrl}/js/map/marker-cluster.js?v=${STATIC_RESOURCE_VERSION}`))
39+
.then(() => asyncLoadJs(`${mediaUrl}js/map/cluster.js`))
3740
.then(() => resolve(true))
3841
.catch((err) => reject(err));
3942
});

media/js/map/cluster.js

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)