How to use a different color for topojson objects with openlayers 3

I have a topojson with a bunch of objects like level1 , level2 , level3 :

{
    "type": "Topology",
    "transform": …,
    "objects": {
        "level1": {
            "id":"level1",
            "type":"GeometryCollection",
            "geometries":[
                {"type":"Polygon","arcs":[[0]]}
            ]
         },
        "level2": …,
        "level3": …,
    },
    "arcs": …
}

      

and I would like to define a different color for another object. I use it in openlayers 3 as a vector layer:

new ol.layer.Vector({
    source: new ol.source.TopoJSON({
        projection: 'EPSG:3857',
        url: "url to my topojson"
    }),
    style: function(feature) {
        return new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: '#09a7ee',
                width: 1
            })
        });
    }
})

      

My idea is to get the id of the object (level1) and select its color or something. But I don't know how to get the id of the property in the style function.

...
style: function(feature) {
    var id = feature.get('id'); //This is not working
    var colors = {
        'level1': '#09a7ee',
        'level2': '#aaa7ee',
        ...
    }

    return new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: colors[id],
            width: 1
        })
    });
}

      

+3


source to share


1 answer


ol.format.TopoJSON

does not store group keys, so you will need to create an index from TopoJSON:

var geometries, geometry;
for (var key in response.objects) {
    geometries = response.objects[key].geometries || [];
    for (var i = 0, ii = geometries.length; i < ii; ++i) {
        geometry = geometries[i];
        objectsByKey[geometry.id] = key;
    }
}
var features = new ol.format.TopoJSON()
    .readFeatures(response, {featureProjection: 'EPSG:3857'});

      

The above assumes that response

is a JSON object containing your TopoJSON and that you are going to build a vector source with features

.



After that, you can do something like this in styleFunction

:

...
style: (function(feature) {
    var colors = {
        'level1': '#09a7ee',
        'level2': '#aaa7ee',
        ...
    };
    var style = new ol.style.Style({
      stroke: new ol.style.Stroke({
        width: 1
      })
    });
    var styles = [style];

    return function(feature) {
      var group = objectsByKey[feature.getId()];
      style.getStroke().setColor(colors[group]);
      return styles;
    });
})()

      

+2


source







All Articles