1. 程式人生 > 實用技巧 >openlayers地圖畫線+打點

openlayers地圖畫線+打點

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")
  })
}