React 组件中的 OpenLayers 绘制模块不会更新地图



我正在开发一个OpenLayers映射,该映射使用React作为所有其他UI内容的包装器。因此,我也在尝试对一些特征进行组件化,在本例中是图形。

以下是试图重新创建OpenLayers文档中的示例。发生的情况是,我得到了绘制表面,它进行绘制,但一旦绘制完成,地图上就什么都没有显示。

我还有一个代码沙盒中行为的活生生的例子。

MapComponent

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 &nbsp;</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;

编辑:应用了使用地图上相同来源的建议,这意味着也要添加图层,这是我以前没有做过的。

检查是否在光栅层之前添加了矢量层。如果首先添加矢量层,光栅层将在矢量的顶部进行渲染。

最新更新