1. openlayer地圖畫線+打點
/**
* 注:
* 創建openlayer圖層三步驟:
* 1. 創建圖層
* 2. 創建圖層源
* 3. 創建源特征
* 特別重要的一句話:圖層是圖層,點是點,點是add到圖層上面的。
* 圖層什么概念呢?千層餅吃過吧,,,當地圖上圖層很多的時候回非常卡,所以地圖上不要同時加載很多圖層,要及時釋放空間。
*
*/
import { Vector as SourceVec } from 'ol/source'
import VectorLayer from 'ol/layer/Vector';
import Feature from 'ol/Feature';
import LineString from 'ol/geom/LineString';
import Style from 'ol/style/Style'
import Stroke from 'ol/style/Stroke';
import { asArray } from 'ol/color';
import Point from 'ol/geom/Point';
import Icon from 'ol/style/Icon';
import { toSize } from 'ol/size';
/**
* 創建線
* @param {經緯度數組} lnglats
* @param {參數,有color顏色,width線的粗細} params
*/
export function addLineString(lnglats,params) {
if (!params) {
params = {}
}
if (!params['color']) {
params['color'] = '#3498db'
}
if (!params['width']) {
params['width'] = 8
}
// 設置源特征
let feature = new Feature({
geometry: new LineString(lnglats),
name: 'Line'
})
// 創建圖層源
let sourceVec = new SourceVec({
features: [feature]
})
// 創建圖層
let vercorLayer = new VectorLayer({
source: sourceVec,
style: new Style({
stroke: new Stroke({
width: params.width,
color: asArray(params.color)
})
})
})
return vercorLayer
}
/**
* 地圖打點
* @param {經緯度數組} lnglats
* @param {圖標地址} icon
* @param {圖標大小} size
*/
export function addMarker(lnglats,icon,size) {
if (!size) {
size = 0.12
}
let features = []
//創建圖標特性
lnglats.forEach(lnglat => {
features.push(createFeature(lnglat))
})
// 創建矢量容器
var vectorSource = new SourceVec({
features: features
})
//創建圖標樣式
var iconStyle = new Style({
image: new Icon({
opacity: 0.75,
src: icon,
scale: toSize(size)
})
})
//創建矢量層
var vectorLayer = new VectorLayer({
source: vectorSource,
style: iconStyle
});
return vectorLayer
}
function createFeature(lnglat) {
return new Feature({
geometry: new Point(lnglat, "XY")
})
}