2017-06-18 152 views
0

我試圖在我的地圖中創建一個工具來選擇要應用於特定圖層的顏色。 我試圖在這下面的代碼隨意改變顏色,如:使用顏色選擇器更改圖層樣式顏色

function getRandomColor() { 
     var letters = 'ABCDEF'; 
     var color = '#'; 
     for (var i = 0; i < 6; i++) { 
      color += letters[Math.floor(Math.random() * 16)]; 
     } 
     return color; 

    } 

var ab =new ol.layer.Vector({ 
    source: vectorSource, 
    style: new ol.style.Style({ 
    stroke: new ol.style.Stroke({ 
     color: 'rgba(0, 0, 255, 0.0)', 
     width: 0.3 
    }), 
    fill : new ol.style.Fill({ 
    color: getRandomColor() 
    }) 
    }) 
}); 
var map = new ol.Map({ 
    layers: [ 
    new ol.layer.Tile({ source: new ol.source.OSM() }), 
    ab 
    ], 
    target: document.getElementById('mapid'), 
    view: new ol.View({ 
    center: [-1095791.453557, 3422374.879112], 
    maxZoom: 19, 
    zoom: 5 
    }) 
}); 

我發現財產以後這樣的:https://jsfiddle.net/7g7Lh2L2/2/

,但我不知道如何與層禮儀

感謝取代'#background''background-color'您;

回答

0

您應該創建一個樣式函數以實現您正在尋找的fill屬性。樣式功能將被要求在地圖圖層中的每個對象,你可以檢查該功能的屬性來確定fill它或致電getRandomColor()功能:

var styleFunction = function() { 
    return function(feature,resolution) { 
    var style; 
    var objProperty = feature.get('<Layer Property Name>'); //Retrieve feature property value 
    style = new ol.style.Style({ 
     image: new ol.style.Circle({ 
     radius: 10, 
     fill: createFillStyle(feature), //Would call function for each map layer feature to determine fill color 
     stroke: createStrokeStyle(feature,resolution) //Example calls function to create stroke for an individual layer feature 
     }), 
     text: createTextStyle(feature, resolution) //Example calls function to create text style for individual layer feature 
    }); 
    return [style]; 
    }; 
}; 

var ab =new ol.layer.Vector({ 
    source: vectorSource, 
    style: styleFunction() 
}); 

var createFillStyle = function(feature) { 
    var fillColor = getRandomColor(); 
    return new ol.style.Fill({color: fillColor}); 
} 

上面的例子將調用getRandomColor()的每個功能上地圖圖層(每個要素在地圖圖層上都有不同的顏色)。如果地圖圖層上的所有要素只有一種顏色,請在var ab =new ol.layer.Vector之前撥打getRandomColor()爲地圖上的所有地圖要素設置一種隨機顏色。

查找openlayers style function查詢更多示例。