使用openlayers,初始化一个地图,一般使用如下代码:
//HTML代码创建一个div
<div id="map"></div>
var map = new ol.Map({
//地图容器div的ID
target: 'map',
、、、、、
});
但是在vue3项目中,一般是不建议给html标签设置id属性,那么我们在vue3组件中使用openlayers,要如何给target传值呢?
请参考如下代码:
代码有如下关键点:
1、渲染地图div不要设置id属性,使用ref属性,要为div制定宽和高。
2、在script标签中通过mapRef=ref();mapRef.value获取html对象
3、new Map的options参数的tarfget传值是mapRef.value
4、new Map要写在onMounted钩子函数中,直接写在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
// 创建source,图层数据源
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', // 坐标系,有EPSG:4326和EPSG:3857
center: [114.064839, 22.548857], // 深圳坐标
minZoom: 10, // 地图缩放最小级别
zoom: 12 // 地图缩放级别(打开页面时默认级别)
})
function initMap(): Map {
return new Map({
layers: [tdLayer],
target: mapRef.value,
view: view,
controls: []
})
}
onMounted(() => {
map = initMap()
})
</script>
<style scoped></style>