@uiw/react-baidu-map-custom-overlay
Version:
Baidu Map custom-overlay Components for React.
108 lines • 3.27 kB
JavaScript
import { useState, useMemo, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useMapContext } from '@uiw/react-baidu-map-map';
import { useProperties, usePrevious } from '@uiw/react-baidu-map-utils';
function getCustomOverlay() {
return class extends BMap.Overlay {
constructor(elm, _position, paneName) {
super();
this.container = void 0;
this.map = void 0;
this.paneName = void 0;
this.position = void 0;
this.offset = void 0;
this.initialize = map => {
var panes = map.getPanes();
this.container.style.position = 'absolute';
this.map = map;
panes[this.paneName].appendChild(this.container);
return this.container;
};
this.draw = () => {
if (this.position == null || this.map == null) {
return;
}
var position = this.map.pointToOverlayPixel(this.position);
var {
width = 0,
height = 0
} = this.offset || {};
this.container.style.left = position.x + width + "px";
this.container.style.top = position.y + height + "px";
};
this.setOffset = offset => {
this.offset = offset;
this.draw();
};
this.setPosition = position => {
this.position = position;
this.draw();
};
this.setVisiable = visiable => {
this.container.style.display = visiable ? 'block' : 'none';
};
this.getPosition = () => {
return this.position;
};
this.setZIndex = index => {
this.container.style.zIndex = index.toString();
};
this.container = elm;
this.paneName = paneName || 'markerPane';
this.position = _position;
}
};
}
export function useCustomOverlay(props) {
if (props === void 0) {
props = {};
}
var {
children,
paneName,
position
} = props;
var {
map
} = useMapContext();
var [customOverlay, setCustomOverlay] = useState();
var [div, setDiv] = useState();
var [portal, setPortal] = useState();
var [count, setCount] = useState(0);
useEffect(() => {
return () => {
if (map && customOverlay) {
map.removeOverlay(customOverlay);
}
};
}, [customOverlay, map]);
useMemo(() => {
if (map && !portal && document) {
var elm = document.createElement('div');
var CustomOverlay = getCustomOverlay();
var portalInstance = /*#__PURE__*/createPortal(children, elm);
var CompOverlay = new CustomOverlay(elm, position, paneName);
setCount(count + 1);
setDiv(elm);
map.addOverlay(CompOverlay);
setPortal(portalInstance);
setCustomOverlay(CompOverlay);
}
}, [children, count, map, paneName, portal, position]);
var prevCount = usePrevious(count);
useMemo(() => {
if (map && div && children && count === prevCount) {
var portalInstance = /*#__PURE__*/createPortal(children, div);
setPortal(portalInstance);
setCount(count + 1);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [children, customOverlay]);
useProperties(customOverlay, props, ['ZIndex', 'Offset', 'Position', 'Visiable']);
return {
portal,
setPortal,
customOverlay,
setCustomOverlay
};
}