目录
获取feature后,可以通过Feature.setStyle()函数给feature动态设置样式:
feature.setStyle(
new Style({
//填充色
fill: new Fill({
color: "rgba(255, 255, 255, 0.2)",
}),
//边线颜色
stroke: new Stroke({
color: "#FF0000",
width: 5,
}),
text: new Text({
// 位置
textAlign: "center",
// 基准线
textBaseline: "middle",
// 文字样式
font: "bold 18px 微软雅黑",
// 文本内容
text: `${feature.get("name")}(${feature.get("area")}亩)`,
// 文字颜色
fill: new Fill({ color: "#00FFFF" }),
// 文字背景
stroke: new Stroke({ color: "#353535", width: 1 }),
}),
//点样式,继承image
image: new Circle({
radius: 7,
fill: new Fill({
color: "#ffcc33",
}),
}),
// image: new Icon({
// anchor: [0.5, -0.3],
// src: "https://openlayers.org/en/v4.6.5/examples/data/icon.png",
// scale: 1, //设置大小
// }),
})
);
填充、描边
import "ol/ol.css";
import { Map, View } from "ol";
import { TileWMS, OSM, Vector as VectorSource } from "ol/source";
import { Vector as VectorLayer, Tile as TileLayer } from "ol/layer";
import GeoJSON from "ol/format/GeoJSON";
import { Fill, Stroke, Style, Text, Icon, Circle } from "ol/style";
new VectorLayer({
source: new VectorSource({
url: "xxx",
format: new GeoJSON()
}),
style: new Style({
fill: new Fill({
//矢量图层填充颜色,以及透明度
color: "rgba(33,194,219,0.5)"
}),
stroke: new Stroke({
//边界样式
color: "rgba(100, 90, 209, 0.6)",
width: 3
}),
text: new Text({
//文本样式
font: "12px Calibri,sans-serif",
fill: new Fill({
color: "#000"
}),
stroke: new Stroke({
color: "#fff",
width: 3
})
})
})
})
动态设置文字标注:
随机设置颜色:
let colors = ["orange","red","blue","yellow"];
let color = colors[Math.floor(Math.random()*colors.length)];
添加图标
new VectorLayer({
source: new VectorSource({
features: new GeoJSON().readFeatures(this.geojsonData_sensor),
}),
style: function (feature) {
return new Style({
fill: new Fill({
//矢量图层填充颜色,以及透明度
color: "#4e98f444",
}),
stroke: new Stroke({
//边界样式
color: "rgba(71, 137, 227, 1)",
width: 3,
}),
text: new Text({
// 位置
textAlign: "center",
// 基准线
textBaseline: "middle",
// 文字样式
font: "bold 18px 微软雅黑",
// 文本内容
text: `${feature.get("title")}`,
// 文字颜色
fill: new Fill({
color: "black",
}),
// 文字背景
stroke: new Stroke({ color: "yellow", width: 10 }),
}),
image: new Icon({
anchor: [0.5, -0.3],
src: "https://openlayers.org/en/v4.6.5/examples/data/icon.png",
scale: 1, //设置大小
}),
});
},
zIndex: 999,
}),