openlayers二次簡(jiǎn)單封裝 線性好芭、點(diǎn)

從自己的角度,簡(jiǎn)單的二次封裝了一下openlayer,在這里提供一下我的思路!
1.添加一個(gè)底圖對(duì)象 map
2.向底圖對(duì)象上添加線層或者點(diǎn)層 line-map與 point-map

效果圖


image.png

前端組件引用

<div style="height:500px">
    <map :baseMap="baseMap" @handleDownEvent="handleDownEvent" ref="map">
        <template slot="yl-map-layers">
            <line-map :lineData="lineData" :fun="lineFun"></line-map>
            <point-map :pointData="pointData" :fun="pointFun"></point-map>
        </template>
        <template slot="map-overlay" slot-scope="scope">
            {{scope.content}}
        </template>
    </map>
</div>

<script>
//  注意:
//    1.傳入地圖地圖需引用 :
//      import TileLayer from "ol/layer/Tile";
//      import XYZ from "ol/source/XYZ";

//todo:1.其它地圖交互事件暴露

import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";

export default {
  name: "yl-map-sam",
  data() {
    return {
        pointFun:(e)=>{
            return {
                src:null,
                scale:null
            }
        },//點(diǎn)樣式
        lineFun:(e)=>{
            return {
                color:null,
                width:null
            }
        },//線樣式
        lineData:[
            {
                data:[
                    [[104,30],[106,28]],//路段1
                    [[108,22],[105,33]],//路段2
                ],
                info:'路線1'
            }
        ],//線性數(shù)據(jù)結(jié)構(gòu)
        pointData:[
            {lng:104,lat:30,info:'點(diǎn)1'},//點(diǎn)1
            {lng:108,lat:24,info:'點(diǎn)2'}//點(diǎn)2
        ],//點(diǎn)數(shù)據(jù)結(jié)構(gòu)
        baseMap:new TileLayer({
          source: new XYZ({
            projection: "EPSG:3857",
            url:
              "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}"
          }),
          name: "底圖"
        })
    }
  },
  methods:{
      //地圖元素點(diǎn)擊事件
      handleDownEvent(feature){
        //點(diǎn)擊后將對(duì)應(yīng)元素移動(dòng)至地圖中間
        this.fitView(feature);
      },

    //注意:closeOverlay()吆你、refMapData()胧后、fitView()使用:  給地圖添加ref
    
    //關(guān)閉彈框
    closeOverlay(){
        this.$refs.map.close();
    },
    //刷新地圖疊加層數(shù)據(jù)
    refMapData(){
        this.$bus.$emit(this.$refs.map.mapId + "ready", {});
    },
    //移動(dòng)焦點(diǎn)位置   傳入值features:Array
    fitView(feature){
        this.$refs.map.fitViewfeatures([feature]);
    }
  }
}
</script>

地圖組件層 map

<template>
  <div class="wapper">
    <div :id="mapId" :ref="mapId" style="height:100%;width:100%;">
      <slot name="yl-map-layers"></slot>
      <div id="popup" class="ol-popup" v-show="content!=null">
        <span class="popup-close" @click="close">
          <i class="el-icon-close" />
        </span>
        <div id="popup-content">
          <slot name="yl-map-overlay" :content="content"></slot>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import "ol/ol.css";
import { Map, View } from "ol";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import { Cluster, OSM, Vector as VectorSource } from "ol/source";
import Feature from "ol/Feature";
import VectorLayer from "ol/layer/Vector";
import Icon from "ol/style/Icon";
import GeoJSON from "ol/format/GeoJSON";
import { Circle as CircleStyle, Fill, Stroke, Style, Text } from "ol/style";
import * as olSize from "ol/size";

import request from "@/utils/request";

//彈框
import Overlay from "ol/Overlay";

//自定義事件方法
import {
  defaults as defaultInteractions,
  Pointer as PointerInteraction,
} from "ol/interaction";

export default {
  name: "yl-map",
  props: {
    baseMap: {
      type: Object,
      default: function () {
        return new TileLayer({
          source: new XYZ({
            projection: "EPSG:3857",
            url:
              "https://mt1.google.cn/vt/lyrs=y@113&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}&s=",
          }),
          name: "底圖",
        });
      },
    },
  },
  data() {
    return {
      timeout: null,
      content: null, //內(nèi)容
      mapId: null, //地圖id
      map: null, //地圖
      view: null,
      overlay: null, //彈框
    };
  },
  methods: {
    close() {
      //彈窗關(guān)閉方法(防止外部調(diào)用此方法——所以先要判斷是否為空)
      this.overlay ? this.overlay.setPosition(undefined) : "";
    },
  },
  created() {
    console.info("map-created");
    this.mapId = "map" + new Date().getTime();
  },
  mounted() {
    console.info("地圖組件掛載,id:" + this.mapId);
    let view = new View({
      center: [104.06, 30.67],
      projection: "EPSG:4326",
      zoom: 8,
      minZoom: 6,
      maxZoom: 20,
    });
    this.view = view;
    const map = new Map({
      target: this.$refs[this.mapId],
      layers: [this.baseMap],
      view: view,
    });
    this.map = map;
    this.$bus.$emit(this.mapId + "ready", {});
  },
};
</script>

<style lang="scss" scoped>
.wapper {
  position: relative;
  width: 100%;
  height: 100%;
  font-size: 80%;
  font-family: Source Han Sans CN;
  font-weight: 400;
}
.popup-close {
  position: absolute;
  right: 5px;
  top: 5px;
  cursor: pointer;
}
.ol-popup {
  background-color: #fff;
  padding: 10px;
  border-radius: 5px;
}
</style>

線性層 line-map

<template></template>   

<script>
/**
 * 線
 */

import "ol/ol.css";
import { Map, View } from "ol";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import VectorSource from "ol/source/Vector";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import VectorLayer from "ol/layer/Vector";
import Icon from "ol/style/Icon";
import GeoJSON from "ol/format/GeoJSON";
import { Circle as CircleStyle, Fill, Stroke, Style, Text } from "ol/style";
import * as olSize from "ol/size";

//線性
import LineString from "ol/geom/LineString";

import { getSessionMotif, getUserInfo } from "@/utils/auth";

import { localConvertArray } from "./../../../../../examples/utils/gps";

export default {
  name: "yl-line-map",
  props: {
    lineData: {
      type: Array,
      default: function () {
        return [];
      },
    },
    fun: {
      type: Function,
      default: function (data) {
        return (e) => {
          return {
            color: null,
            width: null,
          };
        };
      },
    },
  },
  watch: {
    lineData(val) {
      if (this.map == null) {
        this.map = this.$parent.map;
      }
      if (this.mapLayers.length > 0) {
        for (let i in this.mapLayers) {
          this.map.removeLayer(this.mapLayers[i]);
        }
        this.mapLayers = [];
      }
      this.addLineLayer();
    },
  },
  data() {
    return {
      mapLayers: [],
      map: null,
    };
  },
  methods: {
    setLineStyle(info) {
      if (this.fun(info).color && this.fun(info).width) {
        let lintStyle = new Style({
          stroke: new Stroke({
            //地圖連線的樣式
            color: this.fun(info).color,
            width: this.fun(info).width,
          }),
        });
        return lintStyle;
      } else {
        return null;
      }
    },
    addLineLayer() {
      let featureLines = [];
      if (this.lineData && this.lineData.length > 0) {
        for (let i in this.lineData) {
          if (this.lineData[i].data.length > 0) {
            for (let x in this.lineData[i].data) {
              if (this.lineData[i].data[x].length > 1) {
                // 設(shè)置  feature
                let featureLine = new Feature({
                  geometry: new LineString(
                    localConvertArray(this.lineData[i].data[x])
                  ),
                  _md_: this.lineData[i].info,
                });
                featureLine.setStyle(this.setLineStyle(this.lineData[i].info));
                featureLines.push(featureLine);
              }
            }
          }
        }
        if (featureLines.length > 0) {
          // 設(shè)置  線性數(shù)據(jù)源
          let LineSource = new VectorSource({
            features: featureLines,
          });
          // 設(shè)置  線性圖層
          let LineLayer = new VectorLayer({
            source: LineSource,
            style: new Style({
              stroke: new Stroke({
                width: 6,
              }),
            }),
            type: "Line",
          });
          //添加  線性圖層
          this.map.addLayer(LineLayer);
          this.mapLayers.push(LineLayer);
        }
      }
    },
  },
  beforeCreate() {},
  created() {
    this.$bus.$on(this.$parent.mapId + "ready", () => {
      if (this.map == null) {
        this.map = this.$parent.map;
      }
      if (this.mapLayers.length > 0) {
        for (let i in this.mapLayers) {
          this.map.removeLayer(this.mapLayers[i]);
        }
        this.mapLayers = [];
      }
      this.addLineLayer();
    });
  },
  beforeMount() {},
  mounted() {},
};
</script>

<style lang="scss" scoped>
</style>

todo:點(diǎn)層

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市科盛,隨后出現(xiàn)的幾起案子帽衙,更是在濱河造成了極大的恐慌,老刑警劉巖贞绵,帶你破解...
    沈念sama閱讀 221,548評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件厉萝,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)谴垫,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門章母,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人翩剪,你說(shuō)我怎么就攤上這事乳怎。” “怎么了前弯?”我有些...
    開(kāi)封第一講書人閱讀 167,990評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵蚪缀,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我博杖,道長(zhǎng)椿胯,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 59,618評(píng)論 1 296
  • 正文 為了忘掉前任剃根,我火速辦了婚禮哩盲,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘狈醉。我一直安慰自己廉油,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,618評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布苗傅。 她就那樣靜靜地躺著抒线,像睡著了一般。 火紅的嫁衣襯著肌膚如雪渣慕。 梳的紋絲不亂的頭發(fā)上嘶炭,一...
    開(kāi)封第一講書人閱讀 52,246評(píng)論 1 308
  • 那天,我揣著相機(jī)與錄音逊桦,去河邊找鬼眨猎。 笑死,一個(gè)胖子當(dāng)著我的面吹牛强经,可吹牛的內(nèi)容都是我干的睡陪。 我是一名探鬼主播,決...
    沈念sama閱讀 40,819評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼匿情,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼兰迫!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起炬称,我...
    開(kāi)封第一講書人閱讀 39,725評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤汁果,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后玲躯,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體须鼎,經(jīng)...
    沈念sama閱讀 46,268評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡鲸伴,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,356評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了晋控。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,488評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡姓赤,死狀恐怖赡译,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情不铆,我是刑警寧澤蝌焚,帶...
    沈念sama閱讀 36,181評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站誓斥,受9級(jí)特大地震影響只洒,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜劳坑,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,862評(píng)論 3 333
  • 文/蒙蒙 一毕谴、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧距芬,春花似錦涝开、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 32,331評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至离斩,卻和暖如春银舱,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背跛梗。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,445評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工寻馏, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人茄袖。 一個(gè)月前我還...
    沈念sama閱讀 48,897評(píng)論 3 376
  • 正文 我出身青樓操软,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親宪祥。 傳聞我的和親對(duì)象是個(gè)殘疾皇子聂薪,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,500評(píng)論 2 359