[英]OpenLayers change color of feature on runtime
I use OpenLayers v6.3.1, including the following stylesheet and script: Scriptfile , Stylesheet我使用 OpenLayers v6.3.1,包括以下样式表和脚本: Scriptfile , Stylesheet
Goal:目标:
My goal is to change the color of a feature (LineString) on runtime using javascript.我的目标是使用 javascript 在运行时更改功能(LineString)的颜色。
Setup:设置:
I mainly used the code from this website: OpenLayers我主要使用了这个网站的代码: OpenLayers
var map = new ol.Map({
target: 'map', //<div id="map"></div>
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
projection: 'EPSG:4326',
center: [11.592581, 47.241524],
zoom: 15
})
});
In this piece of code I create a line between two coordinates:在这段代码中,我在两个坐标之间创建了一条线:
var lonlat1 = [11.592581, 47.241524];
var lonlat2 = [11.58554, 47.248958];
//create the line's style
var lineStyle = [
// linestring
new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#000',
width: 2
})
})
];
//create the line
var line = new ol.layer.Vector({
source: new ol.source.Vector({
features: [
new ol.Feature({
geometry: new ol.geom.LineString([lonlat1, lonlat2])
})
]
}),
style: lineStyle
});
map.addLayer(line);
Which gives me this map:这给了我这个 map:
I want to change the color of the line at runtime.我想在运行时更改线条的颜色。
What I tried so far: I tried to change the color using the following code:到目前为止我尝试了什么:我尝试使用以下代码更改颜色:
line.style_[0].stroke_.color_ = '#123';
The value of the color did change, but the color of the line itself remains the same.颜色的值确实发生了变化,但线条本身的颜色保持不变。
OK, i figured it out.好的,我想通了。 The style can be changed with the setStyle() function which is part of the line object.
可以使用 setStyle() function 更改样式,它是 object 行的一部分。
line.setStyle([
new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#123',
width: 2
})
})
]);
This is definitely not the best solution so I am open to anything better.这绝对不是最好的解决方案,所以我愿意接受更好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.