mirror of
https://github.com/haiwen/seahub.git
synced 2025-04-27 19:05:16 +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:
parent
0b0e471c90
commit
076d147d4e
@ -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));
|
||||
});
|
||||
|
1
media/js/map/cluster.js
Normal file
1
media/js/map/cluster.js
Normal file
File diff suppressed because one or more lines are too long
@ -1,642 +0,0 @@
|
||||
/**
|
||||
* @fileoverview MarkerCluster标记聚合器用来解决加载大量点要素到地图上产生覆盖现象的问题,并提高性能。
|
||||
* 主入口类是<a href="symbols/BMapLib.MarkerCluster.html">MarkerCluster</a>,
|
||||
* 基于Baidu Map API 1.2。
|
||||
*
|
||||
* @author Baidu Map Api Group
|
||||
* @version 1.2
|
||||
*/
|
||||
|
||||
/**
|
||||
* @namespace BMap的所有library类均放在BMapLib命名空间下
|
||||
*/
|
||||
var BMapLib = window.BMapLib = BMapLib || {};
|
||||
(function(){
|
||||
|
||||
/**
|
||||
* 获取一个扩展的视图范围,把上下左右都扩大一样的像素值。
|
||||
* @param {Map} map BMapGL.Map的实例化对象
|
||||
* @param {BMapGL.Bounds} bounds BMapGL.Bounds的实例化对象
|
||||
* @param {Number} gridSize 要扩大的像素值
|
||||
*
|
||||
* @return {BMapGL.Bounds} 返回扩大后的视图范围。
|
||||
*/
|
||||
var getExtendedBounds = function(map, bounds, gridSize){
|
||||
bounds = cutBoundsInRange(bounds);
|
||||
var pixelNE = map.pointToPixel(bounds.getNorthEast());
|
||||
var pixelSW = map.pointToPixel(bounds.getSouthWest());
|
||||
pixelNE.x += gridSize;
|
||||
pixelNE.y -= gridSize;
|
||||
pixelSW.x -= gridSize;
|
||||
pixelSW.y += gridSize;
|
||||
var newNE = map.pixelToPoint(pixelNE);
|
||||
var newSW = map.pixelToPoint(pixelSW);
|
||||
if (!newSW || !newNE) return null;
|
||||
return new BMapGL.Bounds(newSW, newNE);
|
||||
};
|
||||
|
||||
/**
|
||||
* 按照百度地图支持的世界范围对bounds进行边界处理
|
||||
* @param {BMapGL.Bounds} bounds BMapGL.Bounds的实例化对象
|
||||
*
|
||||
* @return {BMapGL.Bounds} 返回不越界的视图范围
|
||||
*/
|
||||
var cutBoundsInRange = function (bounds) {
|
||||
var maxX = getRange(bounds.getNorthEast().lng, -180, 180);
|
||||
var minX = getRange(bounds.getSouthWest().lng, -180, 180);
|
||||
var maxY = getRange(bounds.getNorthEast().lat, -90, 90);
|
||||
var minY = getRange(bounds.getSouthWest().lat, -90, 90);
|
||||
return new BMapGL.Bounds(new BMapGL.Point(minX, minY), new BMapGL.Point(maxX, maxY));
|
||||
};
|
||||
|
||||
/**
|
||||
* 对单个值进行边界处理。
|
||||
* @param {Number} i 要处理的数值
|
||||
* @param {Number} min 下边界值
|
||||
* @param {Number} max 上边界值
|
||||
*
|
||||
* @return {Number} 返回不越界的数值
|
||||
*/
|
||||
var getRange = function (i, mix, max) {
|
||||
mix && (i = Math.max(i, mix));
|
||||
max && (i = Math.min(i, max));
|
||||
return i;
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断给定的对象是否为数组
|
||||
* @param {Object} source 要测试的对象
|
||||
*
|
||||
* @return {Boolean} 如果是数组返回true,否则返回false
|
||||
*/
|
||||
var isArray = function (source) {
|
||||
return '[object Array]' === Object.prototype.toString.call(source);
|
||||
};
|
||||
|
||||
/**
|
||||
* 返回item在source中的索引位置
|
||||
* @param {Object} item 要测试的对象
|
||||
* @param {Array} source 数组
|
||||
*
|
||||
* @return {Number} 如果在数组内,返回索引,否则返回-1
|
||||
*/
|
||||
var indexOf = function(item, source){
|
||||
var index = -1;
|
||||
if(isArray(source)){
|
||||
if (source.indexOf) {
|
||||
index = source.indexOf(item);
|
||||
} else {
|
||||
for (var i = 0, m; m = source[i]; i++) {
|
||||
if (m === item) {
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return index;
|
||||
};
|
||||
|
||||
/**
|
||||
*@exports MarkerCluster as BMapLib.MarkerCluster
|
||||
*/
|
||||
var MarkerCluster =
|
||||
/**
|
||||
* MarkerCluster
|
||||
* @class 用来解决加载大量点要素到地图上产生覆盖现象的问题,并提高性能
|
||||
* @constructor
|
||||
* @param {Map} map 地图的一个实例。
|
||||
* @param {Json Object} options 可选参数,可选项包括:<br />
|
||||
* markers {Array<Marker>} 要聚合的标记数组<br />
|
||||
* girdSize {Number} 聚合计算时网格的像素大小,默认60<br />
|
||||
* maxZoom {Number} 最大的聚合级别,大于该级别就不进行相应的聚合<br />
|
||||
* minClusterSize {Number} 最小的聚合数量,小于该数量的不能成为一个聚合,默认为2<br />
|
||||
* isAvgCenter {Boolean} 聚合点的落脚位置是否是所有聚合在内点的平均值,默认为否,落脚在聚合内的第一个点<br />
|
||||
* styles {Array<IconStyle>} 自定义聚合后的图标风格,请参考TextIconOverlay类<br />
|
||||
*/
|
||||
BMapLib.MarkerCluster = function(map, options){
|
||||
if (!map){
|
||||
return;
|
||||
}
|
||||
this._map = map;
|
||||
this._markers = [];
|
||||
this._clusters = [];
|
||||
|
||||
var opts = options || {};
|
||||
this._gridSize = opts["gridSize"] || 60;
|
||||
this._maxZoom = opts["maxZoom"] || 21;
|
||||
this._minClusterSize = opts["minClusterSize"] || 2;
|
||||
this._isAverageCenter = false;
|
||||
if (opts['isAverageCenter'] != undefined) {
|
||||
this._isAverageCenter = opts['isAverageCenter'];
|
||||
}
|
||||
this._styles = opts["styles"] || [];
|
||||
this._callback = opts["callback"] || function(){};
|
||||
|
||||
var that = this;
|
||||
this._map.addEventListener("zoomend",function(){
|
||||
that._redraw();
|
||||
});
|
||||
|
||||
// this._map.addEventListener("moveend",function(){
|
||||
// that._redraw();
|
||||
// });
|
||||
|
||||
var markers = opts["markers"];
|
||||
isArray(markers) && this.addMarkers(markers);
|
||||
};
|
||||
|
||||
/**
|
||||
* 添加要聚合的标记数组。
|
||||
* @param {Array<Marker>} markers 要聚合的标记数组
|
||||
*
|
||||
* @return 无返回值。
|
||||
*/
|
||||
MarkerCluster.prototype.addMarkers = function(markers){
|
||||
for(var i = 0, len = markers.length; i <len ; i++){
|
||||
this._pushMarkerTo(markers[i]);
|
||||
}
|
||||
this._createClusters();
|
||||
};
|
||||
|
||||
/**
|
||||
* 把一个标记添加到要聚合的标记数组中
|
||||
* @param {BMapGL.Marker} marker 要添加的标记
|
||||
*
|
||||
* @return 无返回值。
|
||||
*/
|
||||
MarkerCluster.prototype._pushMarkerTo = function(marker){
|
||||
var index = indexOf(marker, this._markers);
|
||||
if(index === -1){
|
||||
marker.isInCluster = false;
|
||||
this._markers.push(marker);//Marker拖放后enableDragging不做变化,忽略
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 添加一个聚合的标记。
|
||||
* @param {BMapGL.Marker} marker 要聚合的单个标记。
|
||||
* @return 无返回值。
|
||||
*/
|
||||
MarkerCluster.prototype.addMarker = function(marker) {
|
||||
this._pushMarkerTo(marker);
|
||||
this._createClusters();
|
||||
};
|
||||
|
||||
/**
|
||||
* 根据所给定的标记,创建聚合点,并且遍历所有聚合点
|
||||
* @return 无返回值
|
||||
*/
|
||||
MarkerCluster.prototype._createClusters = function(){
|
||||
var mapBounds = this._map.getBounds();
|
||||
var extendedBounds = getExtendedBounds(this._map, mapBounds, this._gridSize);
|
||||
for(var i = 0, marker; marker = this._markers[i]; i++){
|
||||
if(!marker.isInCluster && extendedBounds && extendedBounds.containsPoint(marker._position) ){
|
||||
this._addToClosestCluster(marker);
|
||||
}
|
||||
}
|
||||
|
||||
var len = this._markers.length;
|
||||
for (var i = 0; i < len; i++) {
|
||||
if(this._clusters[i]){
|
||||
this._clusters[i].render();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 根据标记的位置,把它添加到最近的聚合中
|
||||
* @param {BMapGL.Marker} marker 要进行聚合的单个标记
|
||||
*
|
||||
* @return 无返回值。
|
||||
*/
|
||||
MarkerCluster.prototype._addToClosestCluster = function (marker){
|
||||
var distance = 4000000;
|
||||
var clusterToAddTo = null;
|
||||
var position = marker.getPosition();
|
||||
for(var i = 0, cluster; cluster = this._clusters[i]; i++){
|
||||
var center = cluster.getCenter();
|
||||
if(center){
|
||||
var d = this._map.getDistance(center, marker.getPosition());
|
||||
if(d < distance){
|
||||
distance = d;
|
||||
clusterToAddTo = cluster;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)){
|
||||
clusterToAddTo.addMarker(marker);
|
||||
} else {
|
||||
var cluster = new Cluster(this);
|
||||
cluster.addMarker(marker);
|
||||
this._clusters.push(cluster);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 清除上一次的聚合的结果
|
||||
* @return 无返回值。
|
||||
*/
|
||||
MarkerCluster.prototype._clearLastClusters = function(){
|
||||
for(var i = 0, cluster; cluster = this._clusters[i]; i++){
|
||||
cluster.remove();
|
||||
}
|
||||
this._clusters = [];//置空Cluster数组
|
||||
this._removeMarkersFromCluster();//把Marker的cluster标记设为false
|
||||
};
|
||||
|
||||
/**
|
||||
* 清除某个聚合中的所有标记
|
||||
* @return 无返回值
|
||||
*/
|
||||
MarkerCluster.prototype._removeMarkersFromCluster = function(){
|
||||
for(var i = 0, marker; marker = this._markers[i]; i++){
|
||||
marker.isInCluster = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 把所有的标记从地图上清除
|
||||
* @return 无返回值
|
||||
*/
|
||||
MarkerCluster.prototype._removeMarkersFromMap = function(){
|
||||
for(var i = 0, marker; marker = this._markers[i]; i++){
|
||||
marker.isInCluster = false;
|
||||
this._map.removeOverlay(marker);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 删除单个标记
|
||||
* @param {BMapGL.Marker} marker 需要被删除的marker
|
||||
*
|
||||
* @return {Boolean} 删除成功返回true,否则返回false
|
||||
*/
|
||||
MarkerCluster.prototype._removeMarker = function(marker) {
|
||||
var index = indexOf(marker, this._markers);
|
||||
if (index === -1) {
|
||||
return false;
|
||||
}
|
||||
this._map.removeOverlay(marker);
|
||||
this._markers.splice(index, 1);
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 删除单个标记
|
||||
* @param {BMapGL.Marker} marker 需要被删除的marker
|
||||
*
|
||||
* @return {Boolean} 删除成功返回true,否则返回false
|
||||
*/
|
||||
MarkerCluster.prototype.removeMarker = function(marker) {
|
||||
var success = this._removeMarker(marker);
|
||||
if (success) {
|
||||
this._clearLastClusters();
|
||||
this._createClusters();
|
||||
}
|
||||
return success;
|
||||
};
|
||||
|
||||
/**
|
||||
* 删除一组标记
|
||||
* @param {Array<BMapGL.Marker>} markers 需要被删除的marker数组
|
||||
*
|
||||
* @return {Boolean} 删除成功返回true,否则返回false
|
||||
*/
|
||||
MarkerCluster.prototype.removeMarkers = function(markers) {
|
||||
var success = false;
|
||||
for (var i = 0; i < markers.length; i++) {
|
||||
var r = this._removeMarker(markers[i]);
|
||||
success = success || r;
|
||||
}
|
||||
|
||||
if (success) {
|
||||
this._clearLastClusters();
|
||||
this._createClusters();
|
||||
}
|
||||
return success;
|
||||
};
|
||||
|
||||
/**
|
||||
* 从地图上彻底清除所有的标记
|
||||
* @return 无返回值
|
||||
*/
|
||||
MarkerCluster.prototype.clearMarkers = function() {
|
||||
this._clearLastClusters();
|
||||
this._removeMarkersFromMap();
|
||||
this._markers = [];
|
||||
};
|
||||
|
||||
/**
|
||||
* 重新生成,比如改变了属性等
|
||||
* @return 无返回值
|
||||
*/
|
||||
MarkerCluster.prototype._redraw = function () {
|
||||
this._clearLastClusters();
|
||||
this._createClusters();
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取网格大小
|
||||
* @return {Number} 网格大小
|
||||
*/
|
||||
MarkerCluster.prototype.getGridSize = function() {
|
||||
return this._gridSize;
|
||||
};
|
||||
|
||||
/**
|
||||
* 设置网格大小
|
||||
* @param {Number} size 网格大小
|
||||
* @return 无返回值
|
||||
*/
|
||||
MarkerCluster.prototype.setGridSize = function(size) {
|
||||
this._gridSize = size;
|
||||
this._redraw();
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取聚合的最大缩放级别。
|
||||
* @return {Number} 聚合的最大缩放级别。
|
||||
*/
|
||||
MarkerCluster.prototype.getMaxZoom = function() {
|
||||
return this._maxZoom;
|
||||
};
|
||||
|
||||
/**
|
||||
* 设置聚合的最大缩放级别
|
||||
* @param {Number} maxZoom 聚合的最大缩放级别
|
||||
* @return 无返回值
|
||||
*/
|
||||
MarkerCluster.prototype.setMaxZoom = function(maxZoom) {
|
||||
this._maxZoom = maxZoom;
|
||||
this._redraw();
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取聚合的样式风格集合
|
||||
* @return {Array<IconStyle>} 聚合的样式风格集合
|
||||
*/
|
||||
MarkerCluster.prototype.getStyles = function() {
|
||||
return this._styles;
|
||||
};
|
||||
|
||||
/**
|
||||
* 设置聚合的样式风格集合
|
||||
* @param {Array<IconStyle>} styles 样式风格数组
|
||||
* @return 无返回值
|
||||
*/
|
||||
MarkerCluster.prototype.setStyles = function(styles) {
|
||||
this._styles = styles;
|
||||
this._redraw();
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取单个聚合的最小数量。
|
||||
* @return {Number} 单个聚合的最小数量。
|
||||
*/
|
||||
MarkerCluster.prototype.getMinClusterSize = function() {
|
||||
return this._minClusterSize;
|
||||
};
|
||||
|
||||
/**
|
||||
* 设置单个聚合的最小数量。
|
||||
* @param {Number} size 单个聚合的最小数量。
|
||||
* @return 无返回值。
|
||||
*/
|
||||
MarkerCluster.prototype.setMinClusterSize = function(size) {
|
||||
this._minClusterSize = size;
|
||||
this._redraw();
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取单个聚合的落脚点是否是聚合内所有标记的平均中心。
|
||||
* @return {Boolean} true或false。
|
||||
*/
|
||||
MarkerCluster.prototype.isAverageCenter = function() {
|
||||
return this._isAverageCenter;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取聚合的Map实例。
|
||||
* @return {Map} Map的示例。
|
||||
*/
|
||||
MarkerCluster.prototype.getMap = function() {
|
||||
return this._map;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取所有的标记数组。
|
||||
* @return {Array<Marker>} 标记数组。
|
||||
*/
|
||||
MarkerCluster.prototype.getMarkers = function() {
|
||||
return this._markers;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取聚合的总数量。
|
||||
* @return {Number} 聚合的总数量。
|
||||
*/
|
||||
MarkerCluster.prototype.getClustersCount = function() {
|
||||
var count = 0;
|
||||
for(var i = 0, cluster; cluster = this._clusters[i]; i++){
|
||||
cluster.isReal() && count++;
|
||||
}
|
||||
return count;
|
||||
};
|
||||
|
||||
MarkerCluster.prototype.getCallback = function() {
|
||||
return this._callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* Cluster
|
||||
* @class 表示一个聚合对象,该聚合,包含有N个标记,这N个标记组成的范围,并有予以显示在Map上的TextIconOverlay等。
|
||||
* @constructor
|
||||
* @param {MarkerCluster} markerCluster 一个标记聚合器示例。
|
||||
*/
|
||||
function Cluster(markerCluster){
|
||||
this._markerCluster = markerCluster;
|
||||
this._map = markerCluster.getMap();
|
||||
this._minClusterSize = markerCluster.getMinClusterSize();
|
||||
this._isAverageCenter = markerCluster.isAverageCenter();
|
||||
this._center = null;//落脚位置
|
||||
this._markers = [];//这个Cluster中所包含的markers
|
||||
this._gridBounds = null;//以中心点为准,向四边扩大gridSize个像素的范围,也即网格范围
|
||||
this._isReal = false; //真的是个聚合
|
||||
|
||||
this._clusterMarker = new BMapLib.TextIconOverlay(this._center, this._markers.length, {"styles":this._markerCluster.getStyles()});
|
||||
//this._map.addOverlay(this._clusterMarker);
|
||||
}
|
||||
|
||||
/**
|
||||
* 向该聚合添加一个标记。
|
||||
* @param {Marker} marker 要添加的标记。
|
||||
* @return 无返回值。
|
||||
*/
|
||||
Cluster.prototype.addMarker = function(marker){
|
||||
if(this.isMarkerInCluster(marker)){
|
||||
return false;
|
||||
}//也可用marker.isInCluster判断,外面判断OK,这里基本不会命中
|
||||
|
||||
if (!this._center){
|
||||
this._center = marker.getPosition();
|
||||
this.updateGridBounds();//
|
||||
} else {
|
||||
if(this._isAverageCenter){
|
||||
var l = this._markers.length + 1;
|
||||
var lat = (this._center.lat * (l - 1) + marker.getPosition().lat) / l;
|
||||
var lng = (this._center.lng * (l - 1) + marker.getPosition().lng) / l;
|
||||
this._center = new BMapGL.Point(lng, lat);
|
||||
this.updateGridBounds();
|
||||
}//计算新的Center
|
||||
}
|
||||
|
||||
marker.isInCluster = true;
|
||||
this._markers.push(marker);
|
||||
};
|
||||
|
||||
/**
|
||||
* 进行dom操作
|
||||
* @return 无返回值
|
||||
*/
|
||||
Cluster.prototype.render = function(){
|
||||
var len = this._markers.length;
|
||||
|
||||
if (len < this._minClusterSize) {
|
||||
for (var i = 0; i < len; i++) {
|
||||
this._map.addOverlay(this._markers[i]);
|
||||
}
|
||||
} else {
|
||||
this._map.addOverlay(this._clusterMarker);
|
||||
this._isReal = true;
|
||||
this.updateClusterMarker();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断一个标记是否在该聚合中。
|
||||
* @param {Marker} marker 要判断的标记。
|
||||
* @return {Boolean} true或false。
|
||||
*/
|
||||
Cluster.prototype.isMarkerInCluster= function(marker){
|
||||
if (this._markers.indexOf) {
|
||||
return this._markers.indexOf(marker) != -1;
|
||||
} else {
|
||||
for (var i = 0, m; m = this._markers[i]; i++) {
|
||||
if (m === marker) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断一个标记是否在该聚合网格范围中。
|
||||
* @param {Marker} marker 要判断的标记。
|
||||
* @return {Boolean} true或false。
|
||||
*/
|
||||
Cluster.prototype.isMarkerInClusterBounds = function(marker) {
|
||||
return this._gridBounds.containsPoint(marker.getPosition());
|
||||
};
|
||||
|
||||
Cluster.prototype.isReal = function(marker) {
|
||||
return this._isReal;
|
||||
};
|
||||
|
||||
/**
|
||||
* 更新该聚合的网格范围。
|
||||
* @return 无返回值。
|
||||
*/
|
||||
Cluster.prototype.updateGridBounds = function() {
|
||||
var bounds = new BMapGL.Bounds(this._center, this._center);
|
||||
this._gridBounds = getExtendedBounds(this._map, bounds, this._markerCluster.getGridSize());
|
||||
};
|
||||
|
||||
/**
|
||||
* 更新该聚合的显示样式,也即TextIconOverlay。
|
||||
* @return 无返回值。
|
||||
*/
|
||||
Cluster.prototype.updateClusterMarker = function () {
|
||||
if (this._map.getZoom() > this._markerCluster.getMaxZoom()) {
|
||||
this._clusterMarker && this._map.removeOverlay(this._clusterMarker);
|
||||
for (var i = 0, marker; marker = this._markers[i]; i++) {
|
||||
this._map.addOverlay(marker);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._markers.length < this._minClusterSize) {
|
||||
this._clusterMarker.hide();
|
||||
return;
|
||||
}
|
||||
|
||||
this._clusterMarker.setPosition(this._center);
|
||||
|
||||
// this._clusterMarker.setText(this._markers.length);
|
||||
var imageUrl = this._markers[0].getImageUrl();
|
||||
this._clusterMarker.setText(this._markers.length, imageUrl);
|
||||
|
||||
var thatMap = this._map;
|
||||
var thatBounds = this.getBounds();
|
||||
let clickTimeout;
|
||||
this._clusterMarker.addEventListener("click", (event) => {
|
||||
if (clickTimeout) {
|
||||
clearTimeout(clickTimeout);
|
||||
clickTimeout = null;
|
||||
return;
|
||||
}
|
||||
clickTimeout = setTimeout(() => {
|
||||
if (this._markerCluster && typeof this._markerCluster.getCallback() === 'function') {
|
||||
const markers = this._markers;
|
||||
this._markerCluster.getCallback()(event, markers);
|
||||
}
|
||||
clickTimeout = null;
|
||||
}, 300); // Delay to differentiate between single and double click
|
||||
});
|
||||
|
||||
this._clusterMarker.addEventListener("dblclick", (event) => {
|
||||
if (clickTimeout) {
|
||||
clearTimeout(clickTimeout);
|
||||
clickTimeout = null;
|
||||
}
|
||||
// Do nothing on double click
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 删除该聚合。
|
||||
* @return 无返回值。
|
||||
*/
|
||||
Cluster.prototype.remove = function(){
|
||||
for (var i = 0, m; m = this._markers[i]; i++) {
|
||||
this._markers[i].getMap() && this._map.removeOverlay(this._markers[i])
|
||||
}//清除散的标记点
|
||||
this._map.removeOverlay(this._clusterMarker);
|
||||
this._markers.length = 0;
|
||||
delete this._markers;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取该聚合所包含的所有标记的最小外接矩形的范围。
|
||||
* @return {BMapGL.Bounds} 计算出的范围。
|
||||
*/
|
||||
Cluster.prototype.getBounds = function() {
|
||||
var bounds = new BMapGL.Bounds(this._center, this._center);
|
||||
for (var i = 0, marker; marker = this._markers[i]; i++) {
|
||||
bounds.extend(marker.getPosition());
|
||||
}
|
||||
return bounds;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取该聚合的落脚点。
|
||||
* @return {BMapGL.Point} 该聚合的落脚点。
|
||||
*/
|
||||
Cluster.prototype.getCenter = function() {
|
||||
return this._center;
|
||||
};
|
||||
|
||||
})();
|
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue
Block a user