? 寫在前面
在地圖類項目開發中,一個常見需求就是:實時獲取用戶鼠標在地圖上的經緯度坐標,并展示在地圖上。
本文將通過一個簡單的案例,手把手帶大家在 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 + 地圖技術干貨!