Search code examples
javascriptjsonopenlayersgeojson

Grabbing GeoJSON data in Openlayers


What I'm trying to do:

Figure out how to reference/grab geoJSON data from a server.

In this case I'm just using an example on the openLayers doc.

Ideally I'd just be able to print out a features ID/type, but I cannot get it to work.

What's happening:

  var selectElement = document.getElementById('type');

  var source = vector.getSource();

  var feature = source.getFeatures()[0];

  var changeInteraction = function() {
    if (select !== null) {
      map.removeInteraction(select);
    }
    var value = selectElement.value;
    if (value == 'singleclick') {
      select = selectSingleClick;
    } else if (value == 'click') {
      select = selectClick;
    } else if (value == 'pointermove') {
      select = selectPointerMove;
    } else if (value == 'altclick') {
      select = selectAltClick;
    } else {
      select = null;
    }
    if (select !== null) {
      map.addInteraction(select);
      select.on('select', function(e) {
        document.getElementById('status').innerHTML = feature.getGeometry().getType();
      });
      console.log(feature);
    }
  };

I was hoping my innerHTML would display "Polygon" in this case, but no such luck. I've tried various combinations, and been looking over the documentation, can't see what I'm doing wrong.

The server I'm trying to grab the info from is,

https://openlayers.org/en/v4.6.4/examples/data/geojson/countries.geojson

Any help would be appreciated.

(I can attach full code if helpful)


Solution

  • I was able to replicate your program and find the solution for retrieving the Country's name for a selected feature, as mentioned in your comments.

    First, remove the following lines. You don't want the first feature of the source file but the first selected feature instead.

    var source = vector.getSource();
    
    var feature = source.getFeatures()[0];
    

    Second, define the feature inside the callback function(e) for the select Event. Also, since getFeatures() will return a Collection of features the getArray() method is necessary.

    The get(key) method will return a value for a determined key, "name" in this case.

    if (select !== null) {
      map.addInteraction(select);
      select.on('select', function(e) {
    
        var feature = e.target.getFeatures().getArray()[0];
    
        document.getElementById('status').innerHTML = ' ' +
    
        feature.get("name") + '  ' + feature.getId();
    
    });
    }