使用Vue CLI 3和ol5搭建基礎地圖頁面

設計目標

利用Vue的特性,結合Openlayers 5搭建一個單頁地圖應用。佈局草圖如圖1所示,頁面的主體爲地圖,在地圖上添加查詢框、工具欄、信息欄等內容。


圖1 佈局草圖
圖1 佈局草圖


創建項目

安裝Vue CLI 3

npm install -g @vue/cli

創建Vue項目,可以使用命令行創建,並在其中配置插件、依賴等

vue create hi-story

也可以使用GUI創建,按照提示來即可

vue ui

修改文檔結構

創建後的文檔結構如圖2所示,主要的代碼位於/src文件夾中,該文件夾的格式如圖3所示


圖2 文檔結構
圖2 文檔結構



圖3 src文件夾結構
圖3 src文件夾結構


由於主體只有一個地圖,功能全都體現在地圖上的對話框,不需要使用多頁面跳轉的功能,因此可以放棄vue-router,使用模塊化開發,搭建地圖。首先將App.vue文件改名爲HiMap.vue,然後刪掉/views/components/HelloWorld.vuerouter.js,在/src/components中添加名爲MainMap.vue的文件。修改後的/src文件夾結構如圖4所示。


圖4 修改後的文件夾結構
圖4 修改後的文件夾結構


修改代碼

詳細內容如代碼所示。

main.js

import Vue from 'vue'
import HiMap from './HiMap.vue'
import store from './store'

Vue.config.productionTip = false

new Vue({
  store,
  render: function (h) { return h(HiMap) }
}).$mount('#app')

HiMap.vue

<template>
  <div id="app">
    <main-map></main-map>
  </div>
</template>

<script>
// Map
import MainMap from './components/MainMap.vue';

export default {
  name: 'HiMap',
  components: {
    MainMap
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
html, body, div {
  margin: 0;
}
</style>

/components/MainMap.vue

<template>
  <div id="map" :style="MapStyle"></div>
</template>

<script>
// Openlayers based modules
import 'ol/ol.css';
import {Map, View} from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

// Map Control
import {defaults} from 'ol/control'

export default {
  name: 'MainMap',
  data() {
    return {
      Map: {},
      View: {},
      Layers: [],
      MapStyle: {
        height: innerHeight + 'px',
        width: innerWidth + 'px'
      }
    }
  },

  created() {
    const self = this;

    onresize = e => {
      let win = e.currentTarget;
      self.MapStyle.height = win.innerHeight + 'px';
      self.MapStyle.width = win.innerWidth + 'px';
    }
  },


  mounted() {
    const self = this;
    // View
    const center = [12175093.67465372, 4209022.808896985];
    const zoom = 4;
    const projecton = 'EPSG:3857';

    self.View = new View({
      center: center,
      zoom: zoom,
      projecton: projecton,
    });

    // Layers
    const osmLayer = new TileLayer({
      source: new OSM(),
      opacity: 1
    });
    self.Layers.push(osmLayer);

    // Map
    self.Map = new Map({
      target: 'map',
      view: self.View,
      layers: self.Layers,
      controls: defaults({
        attribution: false,
        rotate: false,
        zoom: false
      }),
    });

    self.map.on('click', event => {
      console.log('(' + event.coordinate.toString() + ') ' + event.map.getView().getZoom());
    });
  },
}
</script>

<style scoped>

</style>

運行

在命令行輸入如下命令,即可編譯運行,之後在瀏覽器中打開即可。

cd hi-story
npm run serve

或者使用vue ui命令在瀏覽器中打開GUI,運行項目。

基本地圖頁面搭建完成:
圖5 基本地圖頁面
圖5 基本地圖頁面

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章