如何使用openlayers 3为topojson对象使用不同的颜色

时间:2015-04-19 19:15:40

标签: openlayers-3 topojson

我的topojson包含一系列对象,例如 level1 level2 level3

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

我想为不同的对象定义不同的颜色。我在openlayers 3中使用它作为矢量图层:

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
            })
        });
    }
})

我的想法是获取对象(level1)id并通过它或类似的东西选择颜色。但我不知道如何在样式函数中获取属性id。

...
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
        })
    });
}

1 个答案:

答案 0 :(得分:2)

ol.format.TopoJSON不存储组密钥,因此您必须从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'});

以上假设response是包含TopoJSON的JSON对象,并且您将使用features构建矢量源。

完成此操作后,您可以在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;
    });
})()