2017-07-04 75 views
0

我已經使用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,      
       }) 
      }),  
     }); 

FILE以GeoJSON:

{ 

「類型」: 「的FeatureCollection」, 「CRS」:{ 「類型」: 「姓名」, 「屬性」:{ 「名稱」:「甕:ogc:def:crs:EPSG :: 4326「}}, 」features「:[ {」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「:{顏色「:」#ff0000「},」幾何「:{」type「:」LineString「,」coordinates「:[[11.24203700040032,43.759969754752376],[11.24720464991 7521,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.252075754111447,43.753064192693351],[11.252260569522404,43.753162663730734] ,[11.252298216347477,43.753302788154329],[11.252042422884459,43.753607171300693],[11.252089750740879,43.754005360713535],[11.252046702595303,43.554152945071198],[11.251940462780629,43.754342861090443],[11.251887408111035,43.754762904036816]]}}, .........

回答

0

您需要創建一個樣式函數來處理這種情況。

因此,讓你的風格功能:

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