openlayers学习二
实现地图标记路线
地图上的点位在openlayers中都抽象为特征点。翻阅文档说明
ol/Feature~Feature
import Feature from 'ol/Feature';
A vector object for geographic features with a geometry and other attribute properties, similar to the features in vector file formats like GeoJSON.
Features can be styled individually with setStyle
; otherwise they use the style of their vector layer.
Note that attribute properties are set as module:ol/Object~BaseObject
properties on the feature object, so they are observable, and have get/set accessors.
Typically, a feature has a single geometry property. You can set the geometry using the setGeometry
method and get it with getGeometry
. It is possible to store more than one geometry on a feature using attribute properties. By default, the geometry used for rendering is identified by the property name geometry
. If you want to use another geometry property for rendering, use the setGeometryName
method to change the attribute property associated with the geometry for the feature. For example:
import Feature from 'ol/Feature';
import Polygon from 'ol/geom/Polygon';
import Point from 'ol/geom/Point';
var feature = new Feature({
geometry: new Polygon(polyCoords),
labelPoint: new Point(labelCoords),
name: 'My Polygon'
});
// get the polygon geometry
var poly = feature.getGeometry();
// Render the feature as a point using the coordinates from labelPoint
feature.setGeometryName('labelPoint');
// get the point geometry
var point = feature.getGeometry();
Feature可以用来描述点、线。接受的参数是point和、lineString
let endLocation = new Feature({
geometry: new Point([record.range[2], record.range[3]])
});
let routerLine = new Feature({
geometry: new LineString(lineArry)
});
可以使用前端WKT的readGeometry()方法解析空间几何对象转化为Poin和LineString对象所需要的二维点数组、数组
let format = new WKT();
let lineArry = format.readGeometry(record.geom).getCoordinates();
线路,点位设计样式。
源码中提示,这里设计性能问题。把创建的样式存储在数组中,在使用的时候直接挂载到图层上即可,减少for循环大量创建特征点导致的卡顿现象,减少浏览器内存开销
let clickStyles = {
startStyle : new Style({
image: new Icon({
src: new URL(`../assets/start.svg`, import.meta.url).href,
anchor: [0.5, 1],
})
}),
endStyle : new Style({
image: new Icon({
src: new URL(`../assets/end.svg`, import.meta.url).href,
anchor: [0.5, 1],
})
}),
routeClickStyle : new Style({
stroke: new Stroke({
width: 2, //线的宽度
color: "#ffc641", //线的颜色
}),
}),
// 1 = 已完成
routeNotClickStyle : new Style({
stroke: new Stroke({
width: 2, //线的宽度
color: "#7af55d", //线的颜色
}),
}),
// 0 = 进行中
routeNotClickStatusIngStyle : new Style({
stroke: new Stroke({
width: 2, //线的宽度
color: "#1958ee", //线的颜色
}),
})
}
特征点挂载样式
startLocation.setStyle(clickStyles.startStyle);
endLocation.setStyle(clickStyles.endStyle);
routerLine.setStyle(clickStyles.routeClickStyle);
图像层挂载路线图层,连续在layerIcon添加3组特征点即可
layerIcon.getSource().addFeature(startLocation);
layerIcon.getSource().addFeature(endLocation);
layerIcon.getSource().addFeature(routerLine);
最终挂载到图像层上
let layerIcon = new VectorLayer({
source: new VectorSource(),
})
layerIcon.getSource().addFeature(routerLine);