rlayers
Version:
React Components for OpenLayers
70 lines • 3.29 kB
JavaScript
import React from 'react';
import { Control } from 'ol/control';
import RControlBase from './RControlBase';
/** A custom control allowing to switch between different layers
*
* Layers that are to be controlled have to be nested inside the control
*
* Every layer should have a `label` property
*
* Requires an `RMap` context
*/
export default class RLayers extends RControlBase {
constructor(props, context) {
super(props, context);
this.onchange = () => this.forceUpdate();
this.clickCollapse = () => {
this.setState({ collapsed: !this.state.collapsed });
};
this.targetRef = React.createRef();
this.state = { collapsed: true, visible: [true] };
}
componentDidMount() {
this.ol = new Control(this.toOLProps(this.props));
super.componentDidMount();
this.context.map.on('change', this.onchange);
this.forceUpdate();
}
componentWillUnmount() {
super.componentWillUnmount();
this.context.map.un('change', this.onchange);
}
toOLProps(props) {
var _a;
return Object.assign(Object.assign({}, super.toOLProps(props)), { element: (_a = this.targetRef) === null || _a === void 0 ? void 0 : _a.current });
}
render() {
var _a, _b;
const visible = React.Children.map(this.props.children, (child, i) => {
var _a;
if (React.isValidElement(child)) {
return (_a = this.state.visible[i]) !== null && _a !== void 0 ? _a : false;
}
});
const labels = React.Children.map(this.props.children, (child) => {
var _a, _b;
if (React.isValidElement(child)) {
return (_b = (_a = child.props.properties) === null || _a === void 0 ? void 0 : _a.label) !== null && _b !== void 0 ? _b : 'no label';
}
});
return (React.createElement(React.Fragment, null,
React.createElement("div", { className: ['ol-control', (_a = this.props.className) !== null && _a !== void 0 ? _a : 'ol-layers-control'].join(' '), ref: this.targetRef },
React.createElement("span", { onClick: this.clickCollapse }, (_b = this.props.element) !== null && _b !== void 0 ? _b : React.createElement("button", null, "=")),
this.state.collapsed ? null : (React.createElement("div", null, labels.map((l, i) => (React.createElement("div", { key: i },
React.createElement("input", { type: 'radio', id: i.toString(), name: l, value: i.toString(), checked: visible[i], onChange: () => {
for (const v in visible) {
visible[v] = false;
}
visible[i] = true;
this.setState({ visible: [...visible], collapsed: true });
} }),
React.createElement("label", { htmlFor: i.toString() }, l))))))),
React.Children.map(this.props.children, (child, i) => {
if (React.isValidElement(child)) {
return React.cloneElement(child, { visible: visible[i] });
}
return child;
})));
}
}
//# sourceMappingURL=RLayers.js.map