Search code examples
javascriptopenlayersgeojson

Openlayers Get Value Properties from Geoson File


I have a question, I have a sqlite.geojson file and I would like to get so information from it, for example, how can I get the "ORIENTATION" value that is "30"?

here is the sqlite.geojson

{
"type": "FeatureCollection",
"name": "TARGET",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "ID": 1, "COORDINATEX": "23", "COORDINATEY": "46", "ORIENTATION": "30" }, "geometry": null },
{ "type": "Feature", "properties": { "ID": 2, "COORDINATEX": "25", "COORDINATEY": "46", "ORIENTATION": "90" }, "geometry": null }
]
}

and the Js code

var vectorGeojson = new VectorSource({
  format: new GeoJSON(),
  url: 'data/sqlite.geojson'
});

var vectorGeojsonLayer = new VectorLayer({
  source: vectorGeojson,
  style: styleFunction
});

var map = new Map({
    controls: defaultControls().extend([mousePositionControl]),
    layers: [rasterLayer, vectorLayer, vectorGeojsonLayer],
    target: 'map',
    view: new View({
      center:fromLonLat([-46.68, -23.59]),
      zoom: 2
    })
});

Solution

  • If you didn't get any loading error about that Geojson and it loaded correctly, First you need to get features from source by this:

    var features = vectorGeojson.getFeaturesCollection();
    

    After getting features from layer now you can iterate them by a loop and get attribute you need, something like this:

    features.forEach(function(feature){
        var attribute = feature.get("attribute name");
        // Do something
    });
    

    This will give you a specific field for all features. Also, you can add some if statement. for example, you only want second "ORIENTATION".

    features.forEach(function(feature){
        if(feature.get("ID") == 2){
            var attribute = feature.get("attribute name");
            // Do something
        }
    });
    

    Hope it helps.