react-amap-v2
Version:
高德地图 v2.0 react 组件
116 lines (106 loc) • 3.71 kB
text/typescript
import { useEffect, useContext } from 'react';
import { useMap } from './use-map';
import { useEvents } from './use-events';
import debug from '@/debug';
import {
OverlayGroupContextState,
OverlayGroupContext,
} from '@/group/overlay/context';
import {
VectorLayerContextState,
VectorLayerContext,
} from '@/layers/vector-layer/context';
function firstUpperCase(str: string) {
return str.toLowerCase().replace(/( |^)[a-z]/g, L => L.toUpperCase());
}
export function useOverlay(
overlay: any,
visible?: boolean,
events?: any,
options?: any,
properties?: string[],
layer?: AMap.LabelsLayer_2,
) {
const { map } = useMap();
const { overlayGroup } = useContext<OverlayGroupContextState>(
OverlayGroupContext,
);
const { vectorLayer } = useContext<VectorLayerContextState>(
VectorLayerContext,
);
useEvents(events, overlay);
useEffect(() => {
if (map && overlay && overlay?.CLASS_NAME === 'AMap.MassMarks') {
debug(overlay)('设置覆盖物:%O', overlay);
overlay.setMap(map);
} else if (layer && overlay && typeof layer !== 'undefined' && overlay) {
debug(overlay)('往图层里添加覆盖物:%O', overlay);
layer.add(overlay);
} else if (vectorLayer && overlay) {
debug(overlay)('往矢量图层里添加覆盖物:%O', overlay);
(vectorLayer as any).add([overlay]);
} else if (overlayGroup && overlay) {
debug(overlay)('往覆盖物分组里添加覆盖物:%O', overlay);
overlayGroup.addOverlay(overlay);
} else if (map && typeof map?.add === 'function' && overlay) {
debug(overlay)('往地图里添加覆盖物:%O', overlay);
map.add(overlay);
}
return () => {
try {
if (
map &&
typeof map?.remove === 'function' &&
overlay &&
overlay?.CLASS_NAME === 'AMap.MassMarks'
) {
debug(overlay)('移除覆盖物:%O', overlay);
overlay.setMap(null);
} else if (layer && typeof layer !== 'undefined' && overlay) {
debug(overlay)('从图层移除覆盖物:%O', overlay);
layer.remove(overlay);
} else if (vectorLayer && overlay) {
debug(overlay)('从矢量图层里移除覆盖物:%O', overlay);
(vectorLayer as any).remove(overlay);
} else if (overlayGroup && overlay) {
debug(overlay)('从覆盖物分组里移除覆盖物:%O', overlay);
overlayGroup.removeOverlay(overlay);
} else if (map && typeof map?.remove === 'function' && overlay) {
debug(overlay)('从地图移除覆盖物:%O', overlay);
map.remove(overlay);
}
} catch (error) {}
};
}, []);
useEffect(() => {
if (
typeof visible === 'boolean' &&
typeof overlay.show === 'function' &&
typeof overlay.hide === 'function'
) {
debug(overlay)('设置是否可见:%s 覆盖物:%O', visible, overlay);
visible ? overlay.show() : overlay.hide();
}
}, [visible, overlay]);
useEffect(() => {
if (Array.isArray(properties)) {
properties.forEach(property => {
const methodName = ['zIndex'].includes(property)
? `set${property}`
: `set${firstUpperCase(property)}`;
if (
typeof options[property] !== 'undefined' &&
typeof overlay[methodName] === 'function'
) {
debug(overlay)(
'更新覆盖物属性,属性名:%s 属性值:%O 覆盖物:%O',
property,
options[property],
overlay,
);
overlay[methodName](options[property]);
}
});
}
}, [JSON.stringify(options)]);
}