不同颜色的功能集合的每个功能

时间:2017-07-04 09:19:46

标签: openlayers-3 geojson

我已经在我的地图中使用openlayers 3上传了一个geojson文件.geojson文件是一个FeatureCollection,其中包含5个LineString类型的功能。 如何以不同方式为每个特征着色以区分我的路径? 如果我将颜色添加到geojson文件的样式中,则不会读取该颜色,如果我向笔划添加颜色,则所有要素都会以单一颜色着色。

下面我添加代码。

感谢。

var vector = new ol.layer.Vector({
            source: new ol.source.Vector({
                format: new ol.format.GeoJSON(),
                url: 'http://localhost/joggo_wp/percorsi.geojson'
            }),
            style: new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: "#ff000",
                    width: 2.5,                     
                })
            }),     
        });

文件GEOJSON:

{

“type”:“FeatureCollection”, “crs”:{“type”:“name”,“properties”:{“name”:“urn:ogc:def:crs:EPSG :: 4326”}}, “特征”: [ {“type”:“Feature”,“properties”:{“ID”:1.0,“LUNGH_M”:1970.0,“NOME”:“Percorso 1”,“PARTENZA”:“Via del Poggio Imperiale 4”,“ARRIVO” :“Via di S. Leonardo 59n”,“LUNGHEZZA”:“1,97 km”},“style”:{“color”:“#ff0000”},“geometry”:{“type”:“LineString”, “坐标”:[[11.24203700040032,43.759969754752376],[11.247204649917521,43.750208064502473],[11.247446659153409,43.750240561464494],[11.247746238597509,43.750179530458503],[11.247960306028226,43.750118937742307],[11.248108264989046,43.749966781403657],[11.248240378523741,43.749814084940027],[11.248897533371567, 43.75006527742493],[11.249140299088037,43.750277668555015],[11.250198620263028,43.751078552926899],[11.250259518649738,43.751623211022611],[11.250562891152564,43.751940055106814],[11.250844806161599,43.752116454510677],[11.250976903611187,43.752184285854881],[11.251025276742347,43.752394633135999],[11.251095944135562,43.752551715399683] ,[11.25207575411144 7,43.753064192693351],[11.252260569522404,43.753162663730734],[11.252298216347477,43.753302788154329],[11.252042422884459,43.753607171300693],[11.252089750740879,43.754005360713535],[11.252046702595303,43.754152945071198],[11.251940462780629,43.754342861090443],[11.251887408111035,43.754762904036816]]}}, .........

1 个答案:

答案 0 :(得分:1)

您需要创建一个样式函数来处理这种情况。

所以让你的风格功能:

 var styleFunction = function(feature) {
       console.log(feature);
     //now you can use any property of your feature to identify the different colors
     //I am using the ID property of your data just to demonstrate
      var color;
      if (feature.get("ID")==1){
      color = "red";
      } else if (feature.get("ID")==2){
      color = "green";
      } else {
     color = "black"; 
      }

      var retStyle =   new ol.style.Style({
          stroke: new ol.style.Stroke({ 
            color: color,
            width: 5
          })
        });
       return retStyle;

      };

然后将此函数指定给矢量图层的样式

var vector = new ol.layer.Vector({
            source: new ol.source.Vector({
                format: new ol.format.GeoJSON(),
                url: 'http://localhost/joggo_wp/percorsi.geojson'
            }),
            style: styleFunction     
        });

这是一个fiddle

相关问题