无法读取 React JS 中未定义的 属性 'Vector'/'Draw'

Cannot read property 'Vector'/'Draw' of undefined in React JS

我正在尝试使用带开放层的 React js 在地图中绘制一些矩形形状。但是,我收到一个错误 "Cannot read property 'Vector' of undefined" /"Cannot read property 'Draw' of undefined".

我在导入所有必需的 class 后收到错误消息。请参阅两条评论之间的可用代码。

代码:

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 map = new Map({
      target: 'map',
      layers: [
        new Tile({
          source: new OSM()
        })
      ],
      view: new View({
        center: proj.fromLonLat([37.41, 8.82]),
        zoom: 4
      })
    })

  //To draw Rectangle in Map - Begins
    var source = new ol.source.Vector({wrapX: false});
    var geometryFunction = ol.interaction.Draw.createRegularPolygon(4);

    var draw = new ol.interaction.Draw({
      source: source,
      type: 'Square',
      geometryFunction: geometryFunction
    });
    map.addInteraction(draw);
 //To draw Rectangle in Map - Ends
  }
  render() {

    return (
      <div id="map"></div>

    )
  }
}

export default MapComponent;

截图:

您正在导入 Vector 和 Draw,但使用 ol.source.Vector 来使用它们。

替换为:

var source = new ol.source.Vector({wrapX: false});

与:

var source = new Vector({wrapX: false});

平局同样如此。