我正在开发一个使用 React 作为所有其他 UI 内容的包装器的 OpenLayers 地图。因此,我也在尝试对一些特性进行组件化,在本例中是绘图。
下面是重新创建OpenLayers 文档中的示例的尝试。发生的事情是我得到了绘图表面,它进行了绘图,但是一旦绘图完成,地图上什么也没有显示。
我还有一个代码沙盒中行为的活生生的例子。
地图组件
import React, { Component, createRef } from "react";
import ReactDOM from "react-dom";
import Map from "ol/Map";
import View from "ol/View";
import OSM from "ol/source/OSM";
import TileLayer from "ol/layer/Tile";
import DrawingComponent from "./DrawingComponent";
class MapComponent extends Component {
mapDomRef;
map;
constructor(...args) {
super(...args);
this.mapDomRef = createRef();
this.map = new Map();
}
componentDidMount() {
const view = new View({
center: [-11000000, 4600000],
zoom: 4
});
const rasterLayer = new TileLayer({
source: new OSM()
});
this.map.addLayer(rasterLayer);
this.map.setTarget(this.mapDomRef.current);
this.map.setView(view);
}
render() {
return (
<div className="App">
<div ref={this.mapDomRef} />
<DrawingComponent map={this.map} />
</div>
);
}
}
绘图组件
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Draw from "ol/interaction/Draw";
import { Vector as VectorSource } from "ol/source";
import { Vector as VectorLayer } from "ol/layer";
class DrawingComponent extends Component {
state = {
geomType: "None"
};
constructor(...args) {
super(...args);
this.source = new VectorSource({ wrapX: false });
this.layer = new VectorLayer({ source: this.source });
}
handleGeomChange = event => {
const geomType = event.target.value;
this.setState(({ draw }) => {
if (draw) {
this.props.map.removeInteraction(draw);
}
return { geomType, draw: this.addInteraction(geomType) };
});
};
addInteraction(geomType) {
if (geomType !== "None") {
const draw = new Draw({
source: this.source,
type: geomType
});
this.props.map.addInteraction(draw);
return draw;
}
}
render() {
return (
<form class="form-inline">
<label>Geometry type </label>
<select
id="type"
value={this.state.geomType}
onChange={this.handleGeomChange}
>
<option value="Point">Point</option>
<option value="LineString">LineString</option>
<option value="Polygon">Polygon</option>
<option value="Circle">Circle</option>
<option value="None">None</option>
</select>
</form>
);
}
}
export default DrawingComponent;
编辑:应用了使用地图上相同来源的建议,这意味着还要添加我以前没有做过的图层。