1.数据准备
首先,接上篇,您已在GeoServer中发布了栅格(tif)数据,点击查看,在跳出的新页面地址栏里会有很长一段连接。如下所示:
其次,我们只需要记住地址中,问号(?)前面的内容和 layers=nurc:3AImg_Sample,即
http://192.168.252.227/geoserver/nurc/wms
layers=nurc:3AImg_Sample
2.OpenLayers中加载代码
首先得有一个项目,具体参考我的其他文章,《Openlayers在vue3.2中的使用》,里面包括了完整的创建vue项目的流程,以及openlayers的安装。
调用代码如下:
<template>
<div :style="{ 'min-height': pageHeight }" id="mymap" class="imap">
</div>
<!-- 注意:div必需指定高度,否则加载不出来 -->
</template>
<script setup>
import { onMounted, ref } from 'vue'
import TileLayer from 'ol/layer/Tile'
import TileWMS from 'ol/source/TileWMS'
import TileLayer from 'ol/layer/Tile'
import { ScaleLine, MousePosition } from 'ol/control' // openlayers控件
import { Map, View, Overlay } from 'ol'
onMounted(() => {
initMap()
})
// 监听页面高度
const pageHeight = ref(window.innerHeight - 60 + 'px')
window.addEventListener('resize', () => {
pageHeight.value = window.innerHeight - 60 + 'px'
})
const initMap = () => {
const layer1 = new TileLayer({
source: new TileWMS({
url: 'http://192.168.252.227/geoserver/nurc/wms',
params: {
'LAYERS': 'nurc:3AImg_Sample',
},
serverType: 'geoserver',
}),
});
// 添加地图控件
const icontrols = [
new ScaleLine(),
new MousePosition({
coordinateFormat: createStringXY(6), // 设置数据格式
projection: 'EPSG:4326', // 设置空间参考系统为'EPSG:4326'
}),
]
// 创建一个地图
map = new Map({
layers: [layer1], // 加载的图层
target: 'mymap', // 绑定div
controls: icontrols, // 设置要显示的控件
view: new View({
center:[120,35], // 中心位置
zoom: 12, // 缩放登级
maxZoom: 18,
projection: 'EPSG:4326' // 使用坐标系
}),
});
}
</script>
<style scoped>
.imap {
min-width: 800px;
height: 800px;
}
</style>