我正在处理一个OpenLayers地图,该地图使用React作为所有其他UI东西的包装。因此,我也在尝试对某些功能(在本例中为图形)进行组件化。
下面是尝试重新创建在OpenLayers documentation中找到的示例的尝试。发生的事情是我得到了绘图表面,它进行了绘图,但是一旦完成绘图,地图上就什么也没有显示。
我也有一个生动的例子,说明了codesandbox中的行为。
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>
);
}
}
DrawingComponent
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;
编辑:应用了建议,以使用地图上的相同源,这意味着还添加了我以前没有做过的图层。
答案 0 :(得分:0)
检查是否在栅格图层之前添加了矢量图层。如果首先添加矢量层,则光栅层将在矢量上方渲染。