我正在尝试使用带有Open Layers Map的React JS在Map中绘制一个矩形形状。我能够画出形状。但是在执行单击操作后,“绘制的形状”不会显示在Map中。如果我将图层值添加为vector
,则地图本身不会显示。我使用下面的链接作为参考(https://openlayers.org/en/latest/examples/draw-shapes.html?mode=advanced),当图层被称为栅格和图层时,它工作正常。
代码:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import 'ol/ol.css';
import ol from 'ol';
import Map from 'ol/map';
import View from 'ol/view';
import Tile from 'ol/layer/tile';
import OSM from 'ol/source/osm';
import proj from 'ol/proj';
import Vector from 'ol/source/vector';
import Draw from 'ol/interaction/draw';
class MapComponent extends Component {
componentDidMount() {
var raster=new Tile({
source: new OSM()
});
var source = new Vector({wrapX: false});
var vector = new Vector({
source: source
});
var map = new Map({
target: 'map',
layers: [raster,vector],
view: new View({
center: proj.fromLonLat([37.41, 8.82]),
zoom: 4
})
})
var value = 'Circle';
var geometryFunction = Draw.createRegularPolygon(4);
var draw = new Draw({
source: source,
type: value,
geometryFunction: geometryFunction
});
map.addInteraction(draw);
}
render() {
return (
<div id="map"></div>
)
}
}
export default MapComponent;
当我在图层中添加矢量时,会出现以下错误。
错误:
group.js:195 Uncaught TypeError: layer.getLayerStatesArray is not a function
at group.js:195
at _ol_Collection_../node_modules/ol/collection.js._ol_Collection_.forEach (collection.js:99)
at _ol_layer_Group_../node_modules/ol/layer/group.js._ol_layer_Group_.getLayerStatesArray (group.js:194)
at _ol_Map_../node_modules/ol/pluggablemap.js._ol_PluggableMap_.renderFrame_ (pluggablemap.js:1141)
at _ol_Map_.<anonymous> (pluggablemap.js:87)
答案 0 :(得分:1)
我没有将OpenLayers与React一起使用,但我认为问题的原因在于:
import Vector from 'ol/source/vector';
[...]
var source = new Vector({wrapX: false});
var vector = new Vector({
source: source
});
您需要两次创建相同类型的对象( ol.source.Vector )。
您应该只有一个 ol.layer.Vector :
// Different types = different imports
import SourceVector from 'ol/source/vector';
import LayerVector from 'ol/layer/vector';
var source = new SourceVector({wrapX: false});
// vector is a layer of type Vector, not a source !
var vector = new LayerVector({
source: source
});