官网demo地址:
上一篇我们使用星星表示了地震数据,能绘制星星图形主要依靠 openlayers中的RegularShape类,那如果想要绘制自定义图形该怎么写呢,这篇提供了解决方案。
const vector = new VectorLayer({
source: new VectorSource({
url: "https://openlayers.org/en/latest/examples/data/kml/2012_Earthquakes_Mag5.kml",
format: new KML({
extractStyles: false,
}),
}),
style: styleFunction,
});
依然是通过样式函数styleFunction设置图形。
styleCache做了一个缓存,以免每次都要重新生成。
从feature中获取自定义属性地震等级大小name决定图形大小。
const styleFunction = function (feature) {
const name = feature.get("name");
const magnitude = parseFloat(name.substr(2));
const size = parseInt(10 + 40 * (magnitude - 5), 10);
scale = size / 10;
let style = styleCache[size];
if (!style) {
styleCache[size] = style;
}
return style;
};
symbol
是一个坐标数组,定义了一个多边形的形状。scaleFunction
根据当前的缩放比例 scale
对每个坐标进行缩放。
const symbol = [
[0, 0],
[4, 2]