[GIS] Render order of vector features in OpenLayers 3

featuresopenlayersvector

In a web map application I have a vector layer from a GeoJSON source of country borders. The layer loads perfectly and interactions such as ol.interaction.select works fine as well.

I want to style individual features from the layer when the map loads and this is where I have some problems. The features in the GeoJSON file is ordered according to the id property, in ascending order. Since the id of the features to be styled are retrieved from a database, similar order (or id) of the features in the db and in OpenLayers is crucial.

In OpenLayers I now try to retrieve features from the GeoJSON source assuming that the order of the features is the same as in the file, but the ordering of the features seems completely random. Since the features are not assigned id in OpenLayers I loop through the array of features from the source and assign them ids just to be able to compare the ordering between file and OpenLayers.

 map.beforeRender(function () {
     var features = countrySource.getFeatures();

     //Assigning id to features
     for (i = 0; features.length > i; i++) {
          features[i].setId(i);
        }
    });

map.on('singleclick',function(evt){

    //alerts the id of the clicked country, id from file
    var fileId = select.getFeatures().item(0).get('id')
    alert(fileId);


    //alerts the assigned id 
    var openLayerId= countrySource.getFeatures()[fileId].getId();
    alert(openLayerId);

});

This gives me completely different id from the two alerts. It seems to me that the order of the features in the resulting array from source.getFeatures() method is random compared to the file.

Here is a line from the GeoJSON file:

{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },

"features": [
{ "type": "Feature", "properties": { "X": 66.0867, "Y": 33.8564, "id": 0, "country": 
"Afghanistan" }, "geometry": { "type": "Polygon", "coordinates": [ [ 
[ 61.210817091725744, 35.650072333309225 ], [ 62.230651483005886 ......

According to the API there is a 'renderOrder' option when creating vector layers, http://openlayers.org/en/v3.1.1/apidoc/ol.layer.Vector.html?unstable=true

Is this something I can use to control the ordering of the features when loading them into my vector layer? Or is there another way around my problem of styling the right features based on id?

Best Answer

That's probably because in your Geojson data there is no ID so the function getId() won't return anything or at least not what you expected.

The ID you are using is just an attribute (property ) in your Geojson data like the name or X, Y ...

You can keep using it with get('id') or recreate your geojson data and set a real ID not a property one