I am trying to draw some rectangular shape in map using react js with open layer. But,I am getting an error as "Cannot read property 'Vector' of undefined" /"Cannot read property 'Draw' of undefined".
I am getting an error after importing all the necessary class. See the code which is available in between two comments.
Code:
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;
Screenshot:
You are importing Vector and Draw but using ol.source.Vector to use them.
Instead replace:
var source = new ol.source.Vector({wrapX: false});
With:
var source = new Vector({wrapX: false});
Similarly for Draw.