Search code examples
reactjsopenlayersopenlayers-3

"Uncaught TypeError: layer.getLayerStatesArray is not a function" Error in React JS with Open Layer


I am trying to draw one rectangle shape in Map using React JS with Open Layers Map. I am able to draw the shape. But after doing the click action, Drawn Shape is not getting displayed in Map.If I added the layers value as vector, then map itself not displaying. I have used the below link as reference(https://openlayers.org/en/latest/examples/draw-shapes.html?mode=advanced) and it is working fine when the layer is mentioned as raster and layer.

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 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;

When I added the vector in layers, then getting the below error.

Error:

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)

Solution

  • I'm not using OpenLayers with React, but I think the cause of your problem lies here:

    import Vector from 'ol/source/vector';
    
    [...]
    
    var source = new Vector({wrapX: false});
    
    var vector = new Vector({
      source: source
    });
    

    You're creating the same kind of Objects (ol.source.Vector) twice.

    You should have one ol.layer.Vector instead:

    // 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
    });