✨ 写在前面
在地图类项目开发中,一个常见需求就是:实时获取用户鼠标在地图上的经纬度坐标,并展示在地图上。
本文将通过一个简单的案例,手把手带大家在 Vue 3 项目中集成 OpenLayers 地图库,并实现以下功能:
-
加载 OpenStreetMap 地图瓦片
-
鼠标移动时显示实时坐标(经纬度)
-
使用
MousePosition
控件格式化坐标 -
支持 Vue 3 Composition API
🔧 技术栈
-
Vue 3 +
<script setup>
-
Vite 5+ 构建工具(也支持 Vue CLI)
-
OpenLayers v7+
-
原生 CSS + Tailwind class(可选)
📦 环境安装
npm install ol
或使用 yarn:
yarn add ol
确保你使用的是 Vue 3 项目结构。如果你还没有项目,可以用 Vite 快速初始化:
npm create vite@latest vue3-openlayers-demo --template vue
cd vue3-openlayers-demo
npm install
npm install ol
npm run dev
🧩 核心代码实现
我们来直接上代码吧,以下是一个完整的 Vue 组件文件:
MouseCoordinateMap.vue
<!--* @Author: 彭麒* @Date: 2025/4/7* @Email: 1062470959@qq.com* @Description: 此源码版权归吉檀迦俐所有,可供学习和借鉴或商用。-->
<template><div class="container"><div class="w-full flex justify-center flex-wrap"><div class="font-bold text-[24px]">在Vue3中使用OpenLayers实现鼠标在地图上移动显示坐标信息</div></div><div id="vue-openlayers" class="map-x"><div class="mouse" ref="mousePositionTxt"></div></div></div>
</template><script setup>
import { onMounted, ref } from 'vue'
import 'ol/ol.css'
import { Map, View } from 'ol'
import Tile from 'ol/layer/Tile'
import { OSM } from 'ol/source'
import * as control from 'ol/control'
import * as coordinate from 'ol/coordinate'const mousePositionTxt = ref(null)
let map = nullconst initMap = () => {map = new Map({target: 'vue-openlayers',controls: control.defaults().extend([new control.MousePosition({coordinateFormat: coordinate.createStringXY(4),projection: 'EPSG:4326',target: mousePositionTxt.value})]),layers: [new Tile({source: new OSM()})],view: new View({projection: 'EPSG:4326',center: [114.064839, 22.548857],zoom: 4})})
}onMounted(() => {initMap()
})
</script><style scoped>
.container {width: 840px;height: 520px;margin: 0 auto;border: 1px solid #42B983;
}
#vue-openlayers {width: 800px;height: 400px;margin: 0 auto;border: 1px solid #42B983;position: relative;
}
.mouse {position: absolute;bottom: 50px;right: 20px;z-index: 10;color: #f00;width: 150px;
}
</style>
📚 关键点解析
1️⃣ MousePosition
控件的作用
这是 OpenLayers 内置的控件,用于监听鼠标事件并展示坐标信息。
new control.MousePosition({ coordinateFormat: coordinate.createStringXY(4), projection: 'EPSG:4326', target: this.$refs.mousePositionTxt
})
在 Vue 3 Composition API 中,需要使用
ref
拿到 DOM 节点,再绑定到target
。
2️⃣ 坐标格式化函数
你可以自定义经纬度显示格式,比如:
coordinateFormat: (coord) => `经度: ${coord[0].toFixed(4)}, 纬度: ${coord[1].toFixed(4)}`
也可以用内置的 createStringXY(4)
,表示保留 4 位小数。
✅ 最终效果截图
🖱 当你将鼠标移动到地图上时,右下角会实时显示当前经纬度坐标,效果如下图所示:
🎯 小结
通过本篇文章,我们成功实现了一个非常实用的地图功能:鼠标坐标跟踪器。这个功能在 GIS、智能驾驶、地图展示等场景中都非常常见。
本案例核心掌握点:
-
熟悉 OpenLayers 的基本使用
-
使用
MousePosition
控件监听坐标 -
结合 Vue 3 Composition API 实现逻辑
🙋♀️ 后续扩展建议
-
鼠标点击地图标记点
-
实时绘制轨迹线
-
集成地理编码(坐标转地址)
-
加入地图测量工具(长度/面积)
💬 欢迎交流
如果你在项目中也有地图相关需求,欢迎在评论区留言交流!觉得有帮助也请点个赞/收藏支持一下,持续分享更多 Vue + 地图技术干货!