OpenLayers VectorLayer – Fixing get() and getProperties() Not a Function in OpenLayers VectorLayer

javascriptopenlayers

I'm trying to get the value "GRID_CODE" from the attribute table of a GeoJSON file and keep getting this two errors:

  • TypeError: myFeature.get is not a function
  • TypeError: myFeature.getProperties is not a function

I can see that in the documentation and other examples that both are functions. I'm also using the Feature class for other purposes succefully, so is not a import problem.

In my console I'm able to see the number of features and the value of them, so I know that there is no problem with the file. How I tried to do:

  myVectorLayer.getSource().on('change', function(evt){
    var newsource = evt.target;
    if (newsource.getState() === 'ready') {
      // Here I can see the number of features
      var numFeatures = newsource.getFeatures().length; 
      console.log("Count after change: " + numFeatures);
      // Here I can see what is inside these features
      var myFeatures = newsource.getFeatures(); 
      console.log(myFeatures);
      // Where I getting the errors
      var myNewData = myFeatures.get("GRID_CODE");
      console.log(myNewData);
    }
  });

A part of "myFeatures":

4: Feature
  dispatching_: {}
  disposed_: false
  geometryChangeKey_: {bindTo: Feature, callOnce: false, listener: ƒ, target: Point, type: "change", …}
  geometryName_: "geometry"
  id_: undefined
  listeners_: {change:geometry: Array(1), change: Array(1), propertychange: Array(1)}
  ol_lm: {change:geometry: Array(1), change: Array(1), propertychange: Array(1)}
  ol_uid: "1428"
  pendingRemovals_: {}
  revision_: 1
  styleFunction_: undefined
  style_: null
  values_:
    GRID_CODE: 16
    OBJECTID: 6042
    geometry: Point {disposed_: false, pendingRemovals_: {…}, dispatching_: {…}, listeners_: {…}, revision_: 2, …}
    __proto__: Object
  __proto__: BaseObject

OL version: v5.3

A example that uses these functions.

Best Answer

source.getFeatures() returns an array of features. The array does not have the method get, i think you need to iterate over this array, a simple for-loop will do. If you are sure that your source only holds a single feature, you can probably just do:

var myNewData = myFeatures[0].get("GRID_CODE");
Related Question