mirror of
https://github.com/haiwen/seahub.git
synced 2025-09-18 00:00:00 +00:00
Optimize/map marker cluster (#7421)
* click overlay to preview * updatea cluster plugin --------- Co-authored-by: zhouwenxuan <aries@Mac.local>
This commit is contained in:
@@ -1,11 +1,10 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import React, { useEffect, useMemo } from 'react';
|
||||
import { getFileNameFromRecord, getFileTypeFromRecord, getImageLocationFromRecord, getParentDirFromRecord, getRecordIdFromRecord } from '../../utils/cell';
|
||||
import ClusterPhotos from './cluster-photos';
|
||||
import MapView from './map-view';
|
||||
import { PREDEFINED_FILE_TYPE_OPTION_KEY } from '../../constants';
|
||||
import { useMetadataView } from '../../hooks/metadata-view';
|
||||
import { Utils } from '../../../utils/utils';
|
||||
import { gettext, siteRoot, thumbnailSizeForGrid } from '../../../utils/constants';
|
||||
import { fileServerRoot, siteRoot, thumbnailSizeForGrid, thumbnailSizeForOriginal } from '../../../utils/constants';
|
||||
import { isValidPosition } from '../../utils/validate';
|
||||
import { gcj02_to_bd09, wgs84_to_gcj02 } from '../../../utils/coord-transform';
|
||||
import { PRIVATE_FILE_TYPE } from '../../../constants';
|
||||
@@ -13,12 +12,10 @@ import { PRIVATE_FILE_TYPE } from '../../../constants';
|
||||
import './index.css';
|
||||
|
||||
const Map = () => {
|
||||
const [showCluster, setShowCluster] = useState(false);
|
||||
const { metadata, viewID, updateCurrentPath } = useMetadataView();
|
||||
|
||||
const clusterRef = useRef([]);
|
||||
|
||||
const repoID = window.sfMetadataContext.getSetting('repoID');
|
||||
const repoInfo = window.sfMetadataContext.getSetting('repoInfo');
|
||||
|
||||
const images = useMemo(() => {
|
||||
return metadata.rows
|
||||
@@ -26,44 +23,47 @@ const Map = () => {
|
||||
const recordType = getFileTypeFromRecord(record);
|
||||
if (recordType !== PREDEFINED_FILE_TYPE_OPTION_KEY.PICTURE) return null;
|
||||
const id = getRecordIdFromRecord(record);
|
||||
const fileName = getFileNameFromRecord(record);
|
||||
const name = getFileNameFromRecord(record);
|
||||
const parentDir = getParentDirFromRecord(record);
|
||||
const path = Utils.encodePath(Utils.joinPath(parentDir, fileName));
|
||||
const src = `${siteRoot}thumbnail/${repoID}/${thumbnailSizeForGrid}${path}`;
|
||||
const path = Utils.encodePath(Utils.joinPath(parentDir, name));
|
||||
const location = getImageLocationFromRecord(record);
|
||||
if (!location) return null;
|
||||
const { lng, lat } = location;
|
||||
if (!isValidPosition(lng, lat)) return null;
|
||||
const gcPosition = wgs84_to_gcj02(lng, lat);
|
||||
const bdPosition = gcj02_to_bd09(gcPosition.lng, gcPosition.lat);
|
||||
return { id, src, lng: bdPosition.lng, lat: bdPosition.lat };
|
||||
|
||||
const repoEncrypted = repoInfo.encrypted;
|
||||
const cacheBuster = new Date().getTime();
|
||||
const fileExt = name.substr(name.lastIndexOf('.') + 1).toLowerCase();
|
||||
let thumbnail = '';
|
||||
const isGIF = fileExt === 'gif';
|
||||
if (repoEncrypted || isGIF) {
|
||||
thumbnail = `${siteRoot}repo/${repoID}/raw${path}?t=${cacheBuster}`;
|
||||
} else {
|
||||
thumbnail = `${siteRoot}thumbnail/${repoID}/${thumbnailSizeForOriginal}${path}`;
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
src: `${siteRoot}thumbnail/${repoID}/${thumbnailSizeForGrid}${path}`,
|
||||
url: `${siteRoot}lib/${repoID}/file${path}`,
|
||||
downloadURL: `${fileServerRoot}repos/${repoID}/files${path}?op=download`,
|
||||
thumbnail,
|
||||
parentDir,
|
||||
location: { lng: bdPosition.lng, lat: bdPosition.lat }
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
}, [repoID, metadata.rows]);
|
||||
|
||||
const openCluster = useCallback((clusterIds) => {
|
||||
clusterRef.current = clusterIds;
|
||||
updateCurrentPath(`/${PRIVATE_FILE_TYPE.FILE_EXTENDED_PROPERTIES}/${viewID}/${gettext('Location')}`);
|
||||
setShowCluster(true);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [viewID, updateCurrentPath]);
|
||||
|
||||
const closeCluster = useCallback(() => {
|
||||
clusterRef.current = [];
|
||||
updateCurrentPath(`/${PRIVATE_FILE_TYPE.FILE_EXTENDED_PROPERTIES}/${viewID}`);
|
||||
setShowCluster(false);
|
||||
}, [viewID, updateCurrentPath]);
|
||||
}, [repoID, repoInfo.encrypted, metadata]);
|
||||
|
||||
useEffect(() => {
|
||||
updateCurrentPath(`/${PRIVATE_FILE_TYPE.FILE_EXTENDED_PROPERTIES}/${viewID}`);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
if (showCluster) {
|
||||
return (<ClusterPhotos photoIds={clusterRef.current} onClose={closeCluster} />);
|
||||
}
|
||||
|
||||
return (<MapView images={images} onOpenCluster={openCluster} />);
|
||||
return (<MapView images={images} />);
|
||||
};
|
||||
|
||||
export default Map;
|
||||
|
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import loadBMap, { initMapInfo } from '../../../../utils/map-utils';
|
||||
import { appAvatarURL, baiduMapKey, googleMapKey, mediaUrl } from '../../../../utils/constants';
|
||||
@@ -8,21 +8,27 @@ import { MAP_TYPE as MAP_PROVIDER } from '../../../../constants';
|
||||
import { EVENT_BUS_TYPE, MAP_TYPE, STORAGE_MAP_CENTER_KEY, STORAGE_MAP_TYPE_KEY, STORAGE_MAP_ZOOM_KEY } from '../../../constants';
|
||||
import { createBMapGeolocationControl, createBMapZoomControl } from './control';
|
||||
import { customAvatarOverlay, customImageOverlay } from './overlay';
|
||||
import ModalPortal from '../../../../components/modal-portal';
|
||||
import ImageDialog from '../../../../components/dialog/image-dialog';
|
||||
|
||||
import './index.css';
|
||||
|
||||
const DEFAULT_POSITION = { lng: 104.195, lat: 35.861 };
|
||||
const DEFAULT_ZOOM = 4;
|
||||
const BATCH_SIZE = 500;
|
||||
const MAX_ZOOM = 21;
|
||||
const MIN_ZOOM = 3;
|
||||
|
||||
const MapView = ({ images, onOpenCluster }) => {
|
||||
const MapView = ({ images }) => {
|
||||
const [imageIndex, setImageIndex] = useState(0);
|
||||
const [clusterLeaveIds, setClusterLeaveIds] = useState([]);
|
||||
|
||||
const mapInfo = useMemo(() => initMapInfo({ baiduMapKey, googleMapKey }), []);
|
||||
const clusterLeaves = useMemo(() => images.filter(image => clusterLeaveIds.includes(image.id)), [images, clusterLeaveIds]);
|
||||
|
||||
const mapRef = useRef(null);
|
||||
const clusterRef = useRef(null);
|
||||
const batchIndexRef = useRef(0);
|
||||
const clickTimeoutRef = useRef(null);
|
||||
|
||||
const saveMapState = useCallback(() => {
|
||||
if (!mapRef.current) return;
|
||||
@@ -68,44 +74,57 @@ const MapView = ({ images, onOpenCluster }) => {
|
||||
return { center: savedCenter, zoom: savedZoom };
|
||||
}, []);
|
||||
|
||||
const onClickMarker = useCallback((e, markers) => {
|
||||
saveMapState();
|
||||
const imageIds = markers.map(marker => marker._id);
|
||||
onOpenCluster(imageIds);
|
||||
}, [onOpenCluster, saveMapState]);
|
||||
|
||||
const renderMarkersBatch = useCallback(() => {
|
||||
if (!images.length || !clusterRef.current) return;
|
||||
|
||||
const startIndex = batchIndexRef.current * BATCH_SIZE;
|
||||
const endIndex = Math.min(startIndex + BATCH_SIZE, images.length);
|
||||
const batchMarkers = [];
|
||||
|
||||
for (let i = startIndex; i < endIndex; i++) {
|
||||
const image = images[i];
|
||||
const { lng, lat } = image;
|
||||
const point = new window.BMapGL.Point(lng, lat);
|
||||
const marker = customImageOverlay(point, image, {
|
||||
callback: (e, markers) => onClickMarker(e, markers)
|
||||
});
|
||||
batchMarkers.push(marker);
|
||||
}
|
||||
clusterRef.current.addMarkers(batchMarkers);
|
||||
|
||||
if (endIndex < images.length) {
|
||||
batchIndexRef.current += 1;
|
||||
setTimeout(renderMarkersBatch, 20); // Schedule the next batch
|
||||
}
|
||||
}, [images, onClickMarker]);
|
||||
const getPoints = useCallback((images) => {
|
||||
if (!window.Cluster || !images) return [];
|
||||
return window.Cluster.pointTransformer(images, (data) => ({
|
||||
point: [data.location.lng, data.location.lat],
|
||||
properties: {
|
||||
id: data.id,
|
||||
src: data.src,
|
||||
}
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const initializeCluster = useCallback(() => {
|
||||
if (mapRef.current && !clusterRef.current) {
|
||||
clusterRef.current = new window.BMapLib.MarkerCluster(mapRef.current, {
|
||||
callback: (e, markers) => onClickMarker(e, markers),
|
||||
maxZoom: 21,
|
||||
});
|
||||
}
|
||||
}, [onClickMarker]);
|
||||
clusterRef.current = new window.Cluster.View(mapRef.current, {
|
||||
clusterRadius: 80,
|
||||
updateRealTime: true,
|
||||
fitViewOnClick: false,
|
||||
isAnimation: true,
|
||||
clusterMap: (properties) => ({ src: properties.src, id: properties.id }),
|
||||
clusterReduce: (acc, properties) => {
|
||||
if (!acc.properties) {
|
||||
acc.properties = [];
|
||||
}
|
||||
acc.properties.push(properties);
|
||||
},
|
||||
renderClusterStyle: {
|
||||
type: window.Cluster.ClusterRender.DOM,
|
||||
inject: (props) => customImageOverlay(props),
|
||||
},
|
||||
});
|
||||
|
||||
clusterRef.current.setData(getPoints(images));
|
||||
|
||||
clusterRef.current.on(window.Cluster.ClusterEvent.CLICK, (element) => {
|
||||
if (clickTimeoutRef.current) {
|
||||
clearTimeout(clickTimeoutRef.current);
|
||||
clickTimeoutRef.current = null;
|
||||
return;
|
||||
} else {
|
||||
clickTimeoutRef.current = setTimeout(() => {
|
||||
let imageIds = [];
|
||||
if (element.isCluster) {
|
||||
imageIds = clusterRef.current.getLeaves(element.id).map(item => item.properties.id).filter(Boolean);
|
||||
} else {
|
||||
imageIds = [element.properties.id];
|
||||
}
|
||||
clickTimeoutRef.current = null;
|
||||
setClusterLeaveIds(imageIds);
|
||||
}, 300);
|
||||
}
|
||||
});
|
||||
}, [images, getPoints]);
|
||||
|
||||
const renderBaiduMap = useCallback(() => {
|
||||
if (!mapRef.current || !window.BMapGL.Map) return;
|
||||
@@ -141,8 +160,20 @@ const MapView = ({ images, onOpenCluster }) => {
|
||||
initializeCluster();
|
||||
|
||||
batchIndexRef.current = 0;
|
||||
renderMarkersBatch();
|
||||
}, [addMapController, initializeCluster, initializeUserMarker, renderMarkersBatch, getBMapType, loadMapState]);
|
||||
}, [addMapController, initializeCluster, initializeUserMarker, getBMapType, loadMapState]);
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
setImageIndex(0);
|
||||
setClusterLeaveIds([]);
|
||||
}, []);
|
||||
|
||||
const moveToPrevImage = useCallback(() => {
|
||||
setImageIndex((imageIndex + clusterLeaves.length - 1) % clusterLeaves.length);
|
||||
}, [imageIndex, clusterLeaves.length]);
|
||||
|
||||
const moveToNextImage = useCallback(() => {
|
||||
setImageIndex((imageIndex + 1) % clusterLeaves.length);
|
||||
}, [imageIndex, clusterLeaves.length]);
|
||||
|
||||
useEffect(() => {
|
||||
const modifyMapTypeSubscribe = window.sfMetadataContext.eventBus.subscribe(EVENT_BUS_TYPE.MODIFY_MAP_TYPE, (newType) => {
|
||||
@@ -172,6 +203,17 @@ const MapView = ({ images, onOpenCluster }) => {
|
||||
return (
|
||||
<div className="sf-metadata-view-map">
|
||||
<div className="sf-metadata-map-container" ref={mapRef} id="sf-metadata-map-container"></div>
|
||||
{clusterLeaveIds.length > 0 && (
|
||||
<ModalPortal>
|
||||
<ImageDialog
|
||||
imageItems={clusterLeaves}
|
||||
imageIndex={imageIndex}
|
||||
closeImagePopup={handleClose}
|
||||
moveToPrevImage={moveToPrevImage}
|
||||
moveToNextImage={moveToNextImage}
|
||||
/>
|
||||
</ModalPortal>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
@@ -1,86 +1,36 @@
|
||||
import { Utils } from '../../../../../utils/utils';
|
||||
const OVERLAY_SIZE = 80;
|
||||
|
||||
const customImageOverlay = (center, image, callback) => {
|
||||
class ImageOverlay extends window.BMapLib.TextIconOverlay {
|
||||
constructor(center, image, { callback } = {}) {
|
||||
super(center, '', { styles: [] });
|
||||
this._center = center;
|
||||
this._URL = image.src;
|
||||
this._id = image.id;
|
||||
this._callback = callback;
|
||||
}
|
||||
const customImageOverlay = (props) => {
|
||||
const { isCluster, pointCount, reduces } = props;
|
||||
const src = isCluster ? reduces.src : props.src;
|
||||
|
||||
initialize(map) {
|
||||
this._map = map;
|
||||
const div = document.createElement('div');
|
||||
div.style.position = 'absolute';
|
||||
div.style.zIndex = 2000;
|
||||
map.getPanes().markerPane.appendChild(div);
|
||||
this._div = div;
|
||||
const div = document.createElement('div');
|
||||
div.style.position = 'absolute';
|
||||
|
||||
const imageElement = `<img src=${this._URL} />`;
|
||||
const htmlString =
|
||||
`
|
||||
<div class="custom-image-container">
|
||||
${this._URL ? imageElement : '<div class="empty-custom-image-wrapper"></div>'}
|
||||
</div>
|
||||
`;
|
||||
const labelDocument = new DOMParser().parseFromString(htmlString, 'text/html');
|
||||
const label = labelDocument.body.firstElementChild;
|
||||
this._div.append(label);
|
||||
const container = document.createElement('div');
|
||||
container.className = 'custom-image-container';
|
||||
|
||||
const eventHandler = (event) => {
|
||||
event.preventDefault();
|
||||
this._callback && this._callback(event, [{ _id: this._id }]);
|
||||
};
|
||||
|
||||
if (Utils.isDesktop()) {
|
||||
let clickTimeout;
|
||||
this._div.addEventListener('click', (event) => {
|
||||
if (clickTimeout) {
|
||||
clearTimeout(clickTimeout);
|
||||
clickTimeout = null;
|
||||
return;
|
||||
}
|
||||
clickTimeout = setTimeout(() => {
|
||||
eventHandler(event);
|
||||
clickTimeout = null;
|
||||
}, 300);
|
||||
});
|
||||
this._div.addEventListener('dblclick', (e) => {
|
||||
e.preventDefault();
|
||||
if (clickTimeout) {
|
||||
clearTimeout(clickTimeout);
|
||||
clickTimeout = null;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this._div.addEventListener('touchend', eventHandler);
|
||||
}
|
||||
|
||||
return div;
|
||||
}
|
||||
|
||||
draw() {
|
||||
const position = this._map.pointToOverlayPixel(this._center);
|
||||
this._div.style.left = position.x - 40 + 'px'; // 40 is 1/2 container height
|
||||
this._div.style.top = position.y - 88 + 'px'; // 80 is container height and 8 is icon height
|
||||
}
|
||||
|
||||
getImageUrl() {
|
||||
return image.src || '';
|
||||
}
|
||||
|
||||
getPosition() {
|
||||
return center;
|
||||
}
|
||||
|
||||
getMap() {
|
||||
return this._map || null;
|
||||
}
|
||||
if (isCluster && pointCount > 1) {
|
||||
const customImageNumber = document.createElement('span');
|
||||
customImageNumber.className = 'custom-image-number';
|
||||
customImageNumber.innerText = pointCount < 1000 ? pointCount : '1k+';
|
||||
container.appendChild(customImageNumber);
|
||||
}
|
||||
|
||||
return new ImageOverlay(center, image, callback);
|
||||
if (src) {
|
||||
const imageElement = document.createElement('img');
|
||||
imageElement.src = src;
|
||||
imageElement.width = OVERLAY_SIZE;
|
||||
imageElement.height = OVERLAY_SIZE;
|
||||
container.appendChild(imageElement);
|
||||
} else {
|
||||
const emptyImageWrapper = document.createElement('div');
|
||||
emptyImageWrapper.className = 'empty-custom-image-wrapper';
|
||||
container.appendChild(emptyImageWrapper);
|
||||
}
|
||||
|
||||
div.appendChild(container);
|
||||
return div;
|
||||
};
|
||||
|
||||
export default customImageOverlay;
|
||||
|
@@ -31,9 +31,12 @@ export const loadMapSource = (type, key, callback) => {
|
||||
|
||||
export default function loadBMap(ak) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (typeof window.BMapGL !== 'undefined' && document.querySelector(`script[src*="${mediaUrl}js/map/cluster.js"]`)) {
|
||||
resolve(true);
|
||||
return;
|
||||
}
|
||||
asyncLoadBaiduJs(ak)
|
||||
.then(() => asyncLoadJs(`${mediaUrl}/js/map/text-icon-overlay.js?v=${STATIC_RESOURCE_VERSION}`))
|
||||
.then(() => asyncLoadJs(`${mediaUrl}/js/map/marker-cluster.js?v=${STATIC_RESOURCE_VERSION}`))
|
||||
.then(() => asyncLoadJs(`${mediaUrl}js/map/cluster.js`))
|
||||
.then(() => resolve(true))
|
||||
.catch((err) => reject(err));
|
||||
});
|
||||
|
Reference in New Issue
Block a user