React组件中OpenLayers Draw模块绘制后地图无更新问题求助
解决React封装OpenLayers绘制组件完成后无图形显示的问题
嘿,我看了你的代码后马上就找到问题根源了——你在DrawingComponent里创建了矢量数据源VectorSource和矢量图层VectorLayer,但从来没把这个图层添加到地图实例中!OpenLayers不会自动把你创建的图层关联到地图,必须显式调用addLayer方法,不然数据源里的要素根本没有载体来渲染~
具体修改步骤
- 在
DrawingComponent中添加componentDidMount生命周期,把矢量图层挂载到地图:
componentDidMount() { // 将绘制用的矢量图层添加到地图 this.props.map.addLayer(this.layer); }
- 为了避免组件卸载后残留图层和交互,补充
componentWillUnmount做清理工作:
componentWillUnmount() { // 移除图层 this.props.map.removeLayer(this.layer); // 移除绘制交互 if (this.state.draw) { this.props.map.removeInteraction(this.state.draw); } }
修改后的完整DrawingComponent代码
import React, { Component } from "react"; 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 }); } componentDidMount() { this.props.map.addLayer(this.layer); } componentWillUnmount() { this.props.map.removeLayer(this.layer); if (this.state.draw) { this.props.map.removeInteraction(this.state.draw); } } 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 className="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;
补充说明
另外我还帮你修正了一个小细节:React中元素的类名要用className而非原生的class,避免控制台出现警告。
修改完成后,你绘制的要素会被Draw交互添加到VectorSource,而关联这个数据源的VectorLayer已经挂载到地图上,就能正常显示绘制的图形了。你之前的操作其实已经把要素存入数据源了,只是缺少了对应的图层来渲染它~
内容的提问来源于stack exchange,提问作者jktravis
相关产品推荐
相关产品推荐

