本文将介绍如何在Vue 引入腾讯地图组件,引入后可以直接在页面中渲染腾讯地图,实现 经纬度 与 地图锚点位置的双向绑定,如:
- 1,输入经纬度后,地图自动定位到指定位置;
- 2,鼠标在地图点击后,自动获取到地址的经纬度;
最终实现效果如下:
实现细节
1,引入腾讯地图,需要借助腾讯地图提供的 SDK,先需要在腾讯地图开发平台添加应用,申请对应的调用 key凭证,开发平台地址:https://lbs.qq.com/dev/console/application/mine
2,找到Vue/Vue3 项目中的 index.html , 通过 script 标签 引入 腾讯地图 sdk
<script charset="utf-8" src="https://map.qq.com/api/gljs?v=1.exp&key=你的Key"></script>
3,在组件中实现核心代码,渲染地图组件,
- 监听地图点击事件,实时获取点击地点对应的经纬度;
- 监听文本框输入经纬度值,在地图中渲染目标地点;
<template><div style="display: flex; justify-content: center; flex-direction: column; align-items: center; padding: 300px;"><div><a-form><div style="display: flex;justify-content: flex-start;"><a-form-item label="纬度"><a-input v-model:value="loc.lat"></a-input></a-form-item><a-form-item label="经度"><a-input v-model:value="loc.lng"></a-input></a-form-item></div></a-form></div><div class="common-map-loc"><div id="container"></div></div></div>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue'
let loc = ref({lat: 39.984104,lng: 116.307503,address: ''
})
watch(() => loc.value.lat,(val, o) => {console.log('val is ', val)flushLatLon()}
)watch(() => loc.value.lng,(val, o) => {console.log('val is ', val)flushLatLon()}
)// 刷新地图
function flushLatLon() {var element = document.getElementById("container");while (element.firstChild) {element.removeChild(element.firstChild);}var center = new TMap.LatLng(loc.value.lat, loc.value.lng);//设置中心点坐标//初始化重新定位var map = new TMap.Map("container", {center: center});
}
// 组件挂载后,渲染对应组件
onMounted(() => {var center = new TMap.LatLng(loc.value.lat, loc.value.lng);//设置中心点坐标//初始化地图var map = new TMap.Map("container", {center: center});//绑定点击事件map.on("click", function (evt) {console.log('event is ', evt)var lat = evt.latLng.getLat().toFixed(6);var lng = evt.latLng.getLng().toFixed(6);loc.value.lat = latloc.value.lng = lng})
})</script><style scoped lang="less">
.common-map-loc {position: relative;#ccontainer {width: 100%;height: 100%;}#info {position: absolute;left: 20px;top: 20px;font-size: 14px;background: #FFF;width: 40%;padding: 10px;border-radius: 3px;}
}.search-div {display: flex;justify-content: center;
}
</style>