使用openlayers乍迄,初始化一個地圖泌霍,一般使用如下代碼:
//HTML代碼創(chuàng)建一個div
<div id="map"></div>
var map = new ol.Map({
//地圖容器div的ID
target: 'map',
、钥星、、满着、谦炒、
});
但是在vue3項(xiàng)目中,一般是不建議給html標(biāo)簽設(shè)置id屬性风喇,那么我們在vue3組件中使用openlayers宁改,要如何給target傳值呢?
請參考如下代碼:
代碼有如下關(guān)鍵點(diǎ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>