reactjs - React 组件中的 OpenLayers Draw 模块不会更新地图
问题描述
我正在开发一个使用 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;
编辑:应用了使用地图上相同来源的建议,这意味着还要添加我以前没有做过的图层。
解决方案
检查您是否在栅格图层之前添加了矢量图层。如果您先添加矢量图层,则光栅层将渲染在矢量图之上。
推荐阅读
- android - Flutter中url启动器的默认调用应用程序
- python-3.x - 如何动态设置 WTForms FormField 的默认值?
- android - Release APK behaves differently than debug with type Future
is not a subtype of FutureOr error - javascript - 使用 Core API 创建模型时出错
- sql-server - Excel 公式转 SQL
- sql - 是否可以在 postgres 11.x 中创建一个 ENUM 小整数?
- python - 对这个 Discord.py Rewrite + Reaction Light 代码感到困惑 - 需要解释
- html - 我想将此 CSS 更改为响应式
- java - LWJGL 无限鼠标移动
- python - python中参数化厄米特矩阵的特征系统