2.vue3+openlayers加载OpenStreetMap地图
效果图:
代码如下:
<!--
* @Author: 彭麒
* @Date: 2024/12/1
* @Email: 1062470959@qq.com
* @Description: 此源码版权归吉檀迦俐所有,可供学习和借鉴或商用。
-->
<template>
<button class="back-button" @click="goBack">返回</button>
<div class="container">
<div class="w-full flex justify-center">
<div class="font-bold text-[24px]">在Vue3中使用OpenLayers加载OpenStreetMap地图</div></div>
<div id="vue-openlayers"></div>
</div>
</template>
<script setup>
import 'ol/ol.css';
import { ref, onMounted } from 'vue';
import { Map, View } from 'ol';
import { Tile as TileLayer } from 'ol/layer';
import { OSM } from 'ol/source';
import router from "@/router";
const goBack = () => {
router.push('/OpenLayers');
};
// 创建 ref 来持有 map 对象
const map = ref(null);
// 初始化地图的函数
const initMap = () => {
const osmLayer = new TileLayer({
source: new OSM(),
zIndex: 1,
});
map.value = new Map({
target: 'vue-openlayers',
layers: [osmLayer],
view: new View({
projection: 'EPSG:4326',
center: [104.389, 30.903],
zoom: 9,
}),
});
};
// 在组件挂载后调用初始化地图函数
onMounted(() => {
initMap();
});
</script>
<style scoped>
.container {
width: 840px;
height: 570px;
margin: 150px auto;
border: 1px solid #42B983;
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
}
#vue-openlayers {
width: 800px;
height: 450px;
margin: 0 auto;
border: 1px solid #42B983;
position: relative;
}
</style>