在Vue3中引入openlayers如何給map對象的target傳值

使用openlayers,初始化一個地圖,一般使用如下代碼:

//HTML代碼創(chuàng)建一個div
<div id="map"></div>
var map = new ol.Map({
            //地圖容器div的ID
            target: 'map',
            、、、、、
        });

但是在vue3項目中,一般是不建議給html標(biāo)簽設(shè)置id屬性,那么我們在vue3組件中使用openlayers,要如何給target傳值呢?
請參考如下代碼:
代碼有如下關(guān)鍵點:
1、渲染地圖div不要設(shè)置id屬性,使用ref屬性,要為div制定寬和高。
2、在script標(biāo)簽中通過mapRef=ref();mapRef.value獲取html對象
3、new Map的options參數(shù)的tarfget傳值是mapRef.value
4、new Map要寫在onMounted鉤子函數(shù)中,直接寫在setup中,mapRef還沒有渲染完成,html對象為空。

<template>
   <div>
      <div ref="mapRef" style="width: 80%; height: 500px;"></div>
   </div>
</template>

<script setup lang="ts">

import { onMounted, ref } from 'vue'
import Map from 'ol/Map.js'
import TileLayer from 'ol/layer/Tile.js'
import View from 'ol/View.js'
import WMTS from 'ol/source/WMTS.js'
import WMTSTileGrid from 'ol/tilegrid/WMTS.js'
import { getTopLeft, getWidth } from 'ol/extent.js'
import { get as getProjection } from 'ol/proj.js'

//天地圖密鑰
const TIANDI_KEY = '3e03f9d1741d4e44a4b0d6632cf5c537'

let mapRef = ref()
let map: Map

// 創(chuàng)建source,圖層數(shù)據(jù)源
const projection = getProjection('EPSG:4326')
const projectionExtent = projection?.getExtent()
const size = getWidth(projectionExtent) / 256
const resolutions = new Array(19)
const matrixIds = new Array(19)
for (let z = 0; z < 19; ++z) {
   resolutions[z] = size / Math.pow(2, z)
   matrixIds[z] = z
}
const tileGrid = new WMTSTileGrid({
   origin: getTopLeft(projectionExtent),
   resolutions,
   matrixIds
})
const source = new WMTS({
   name: '矢量底圖',
   url: `http://t0.tianditu.gov.cn/img_c/wmts?tk=${TIANDI_KEY}`,
   layer: 'mylayer',
   matrixSet: 'EPSG:4326',
   style: 'default',
   format: 'tiles',
   wrapX: true,
   tileGrid
})
const tdLayer = new TileLayer({
   // 使用瓦片渲染方法
   source
})

const view = new View({
   // 地圖視圖
   projection: 'EPSG:4326', // 坐標(biāo)系,有EPSG:4326和EPSG:3857
   center: [114.064839, 22.548857], // 深圳坐標(biāo)
   minZoom: 10, // 地圖縮放最小級別
   zoom: 12 // 地圖縮放級別(打開頁面時默認(rèn)級別)
})
function initMap(): Map {
   return new Map({
      layers: [tdLayer],
      target: mapRef.value,
      view: view,
      controls: []
   })
}

onMounted(() => {
   map = initMap()
})
</script>

<style scoped></style>


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容