1. 引入騰訊地圖API
JavaScript API | 騰訊位置服務 (qq.com)
首先在官網注冊賬號 并正確獲取并配置key后? 找到合適的引入方式? 本文不涉及版本操作和附加庫? ?據體引入參數參考如下圖

?
在項目根目錄 index.html 中 寫入如下代碼
<!-- 引入騰訊地圖 -->
<script src="https://map.qq.com/api/gljs?v=1.exp&key=你的key"></script>
? 粘貼后key替換為自己的key
2. 創建容器
<div class="map_container" ref="mapRef"></div>
.map_container {width: 500px;height: 500px;position: relative;// 阻止復制-webkit-user-select: none; /* Safari */-moz-user-select: none; /* Firefox */-ms-user-select: none; /* IE/Edge */user-select: none; /* 標準語法 */
}
?
3. 渲染地圖
<script setup>
import { nextTick, ref, onMounted } from 'vue';onMounted(() => {// 渲染地圖nextTick(() => {initMap();});
});// 經緯度
const formData = ref({lat: 39.98412,lng: 116.307484,
})// 地圖實例
let map = null// marker圖層
let markerLayer = null// 初始化地圖
const mapRef = ref(null)
const TMap = window.TMap
const initMap = () => {//定義地圖中心點坐標const mapCenter = new TMap.LatLng(formData.value.lat, formData.value.lng)map = new TMap.Map(mapRef.value, {center: mapCenter, //設置地圖中心點坐標zoom: 17, //設置地圖縮放級別pitch: 0, //設置俯仰角rotation: 0, //設置地圖旋轉角度viewMode: '2D'})// 以下代碼按需添加// 移除logo以及左下角信息// let logoInfo = document.querySelector('canvas+div:last-child')// logoInfo.style.display = 'none'// 禁止拖拽// map.setDraggable(false);// 禁止縮放// map.setScrollable(false);//移除控件縮放// map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ZOOM);// 移除比例尺控件// map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.SCALE);// 移除旋轉控件// map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ROTATION);}
</script>
4. 點擊地圖? 添加單個標注
添加多個標注只需刪除以下函數即可
markerLayer.setGeometries([])
示例代碼:?
<script setup>
import { nextTick, ref, onMounted } from 'vue';onMounted(() => {// 渲染地圖nextTick(() => {initMap();});
});// 經緯度
const formData = ref({lat: 39.98412,lng: 116.307484,
})// 地圖實例
let map = null
// marker圖層
let markerLayer = null
// 初始化地圖
const mapRef = ref(null)
const TMap = window.TMap
const initMap = () => {//定義地圖中心點坐標const mapCenter = new TMap.LatLng(formData.value.lat, formData.value.lng)map = new TMap.Map(mapRef.value, {center: mapCenter, //設置地圖中心點坐標zoom: 17, //設置地圖縮放級別pitch: 0, //設置俯仰角rotation: 0, //設置地圖旋轉角度viewMode: '2D'})// 以下代碼按需添加// 移除logo以及左下角信息// let logoInfo = document.querySelector('canvas+div:last-child')// logoInfo.style.display = 'none'// 禁止拖拽// map.setDraggable(false);// 禁止縮放// map.setScrollable(false);//移除控件縮放// map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ZOOM);// 移除比例尺控件// map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.SCALE);// 移除旋轉控件// map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ROTATION);//初始化marker圖層markerLayer = new TMap.MultiMarker({map: map})addMarker()map.on('click', clickHandler)
}// 地圖點擊事件
const clickHandler = (event) => {const { lat, lng } = event.latLngformData.value.lat = String(lat).slice(0, 8)formData.value.lng = String(lng).slice(0, 8)addMarker()
}// 添加標注
const addMarker = () => {// 清空標注 使其始終為一個markerLayer.setGeometries([])markerLayer.add({position: new TMap.LatLng(formData.value.lat, formData.value.lng)})
}</script>