# vue 項目安裝 openlayer


vue 項目安裝 openlayer

今天呢,稍微說一下關於 vue 項目使用 openlayer 的一些操作,我也是剛開始學習,在摸索。

比較討厭的一點就是他的官網說明文檔啥的都是英文的,對英語不好的很不友好,我也看不懂,但是我下了一個有道翻譯,關鍵是剛接觸,不了解,都不知道怎么檢索能得到答案,沒目的性,很難受。但是沒關系,等我以后有錢了,我就收購了openlayer,然后拿着刀架在那群開發的洋鬼子脖子上逼他們把開發文檔一個詞一個詞的給你們翻譯成中文的。加油!

相關資料

openlayer 官網:https://openlayers.org/
openlayer API:https://openlayers.org/en/latest/apidoc/
openlayer 官網案例:https://openlayers.org/en/latest/examples/

vue 項目安裝 openlayer

接下來就進入正題吧,就是 vue 項目中引入 openlayer 。

添加依賴

就是下面這一行命令。

npm install ol

然后等他安裝完就可以了。
在這里插入圖片描述

使用 openlayer

然后在我們需要使用openlayer的頁面寫一個div來放置地圖,首先一點哈,要保證這個div有高度和寬度,不然顯示不出來,有的人找了好久原因,發現是因為存放地圖的div沒有設置寬高,吃了這個虧。

<div id="map" ref="map"></div>

接下來就可以寫ts代碼接入openlayer了。

<script>
  // 首先引入幾個會用的到庫,具體可以查看官網API文檔
  import 'ol/ol.css';
  import Map from 'ol/Map';
  import OSM from 'ol/source/OSM';
  import TileLayer from 'ol/layer/Tile';
  import View from 'ol/View';

  var map = null   // 創建一個地圖實例
  export default {
    name: "Home",
    data() {
      return {

      }
    },
    mounted() {
      this.initMap()  // 調用初始化地圖服務
    },
    methods: {
      // 初始化地圖
      initMap() {
        map = new Map({  // 創建一個地圖
          layers: [
            new TileLayer({
              source: new OSM(),
            }),
          ],
          target: 'map',
          view: new View({
            center: [0, 0],
            zoom: 2,
          }),
        });
      }
    },
  };

</script>

OK。上面的代碼地圖就展示出來了!奈斯!
在這里插入圖片描述

加載高德地圖底圖

	  // 初始化地圖
      initMap() {
        map = new Map({
          layers: [
            new TileLayer({
              visible: true,
              source: new XYZ({
                visible: true,
                url: 'http://webrd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=2&scale=1&style=8',
              })
            })
          ],
          target: 'map',
          view: new View({
            center: [116.403218, 39.92372],
            zoom:12,
            maxZoom: 18,
            projection: 'EPSG:4326',
            constrainResolution: true,  // 設置縮放級別為整數 
            smoothResolutionConstraint: false,  // 關閉無級縮放地圖
          }),
        });
      }

下面是加載進來的效果。
在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM