当前位置: 首页 > news >正文

腾讯地图 vue3 使用 封装 地图组件

目录

  • map
    • index.ts
    • index.vue

index.ts

// src/utils/loadTMap.ts
declare global {interface Window {TMap?: any;}
}
// 参数名就是腾讯地图的Key
export function loadTMap(key: string): Promise<void> {console.log(key,"key")return new Promise((resolve, reject) => {if (window.TMap) {resolve()return}const script = document.createElement('script')script.type = 'text/javascript'//&libraries=service 这个加上 才可以使用地图的一些方法script.src = `https://map.qq.com/api/gljs?v=1.exp&key=${key}&libraries=service`script.async = truescript.onload = () => {if (window.TMap) {resolve()} else {reject(new Error('TMap 未正确加载'))}}script.onerror = () => reject(new Error('腾讯地图脚本加载失败'))document.head.insertBefore(script, document.head.firstChild)})
}

index.vue

<template><div><div id="container" ref="mapContainer"></div></div>
</template><script setup lang="ts">
import { ref, defineExpose } from 'vue'
import { loadTMap } from './index' // 你封装的腾讯地图加载器import { ElMessage } from 'element-plus'// 类型定义
interface Position {lat: numberlng: number
}interface GeocoderResultDetail {location: Position, //经纬度address: string ,//详细地址[key: string]: any  //省市区
}// Props
const props = withDefaults(defineProps<{lat?: numberlon?: numbermapKey: string,region?:string //城市
}>(), {lat: 30.570676,lon: 104.065173,region:"成都市"
})// Emits
const emit = defineEmits<{(e: 'getCoordinates', detail: GeocoderResultDetail): void
}>()const mapContainer = ref<HTMLElement | null>(null)
const mapInstance = ref<any>(null)
const geocoder = ref<any>(null)
const marker = ref<any>(null)
const resultDetail = ref<GeocoderResultDetail | null>(null)
const hasLoaded = ref(false)
const TMap=ref()
// 初始化地图
const initMap = async () => {if (hasLoaded.value) returntry {if (!props.mapKey) return console.warn('地图Key为空')await loadTMap(props.mapKey)const TMap = window.TMapif (!TMap || !mapContainer.value) throw new Error('TMap 加载失败')const center = new TMap.LatLng(props.lat, props.lon)mapInstance.value = new TMap.Map(mapContainer.value, {center,zoom: 15})// 初始化地理编码器geocoder.value = new TMap.service.Geocoder()// 初始点反查地址geocoder.value.getAddress({ location: center })// 点击地图获取坐标并反查地址mapInstance.value.on('click', (e: any) => {const latLng = new TMap.LatLng(e.latLng.lat, e.latLng.lng)setMarker(latLng)geocoder.value.getAddress({location: latLng,success: (res: { result: GeocoderResultDetail }) => {resultDetail.value = res.resultconsole.log("哈哈哈", res.result)// emit('getCoordinates', {//   location: latLng,// })},fail: (err: any) => {console.error('地址解析失败:', err)}})})hasLoaded.value = true} catch (error) {console.error('地图初始化失败:', error)}
}// 打点函数
const setMarker = (latLng: Position) => {if (marker.value) marker.value.setMap(null)
const center = new window.TMap.LatLng(latLng.lat, latLng.lng)const point = new window.TMap.LatLng(latLng.lat, latLng.lng)// 设置地图中心点mapInstance.value.setCenter(center)try{marker.value = new window.TMap.MultiMarker({map: mapInstance.value,styles: {marker: new window.TMap.MarkerStyle({width: 25,height: 35,anchor: { x: 16, y: 32 },src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png'})},geometries:[{"id": "1","styleId": 'marker',"position": point,"properties": {"title": "marker4"}}]})geocoder.value.getAddress({location: point,}).then((res:{result:GeocoderResultDetail })=>{const {result}=resemit('getCoordinates', {type: 'getAddress',location: {lat:result.location.lat,lng:result.location.lng},address: result.address,addressInfo: {province:result.ad_info.province,city:result.ad_info.city,district:result.ad_info.district}})});}catch(err){console.log(err,"家家爱")}
}// 父组件传入地址,地图定位并打点
const setAddress = (address: string) => {if (!geocoder.value || !mapInstance.value) returngeocoder.value.getLocation({address: address,}).then((res:{result:GeocoderResultDetail })=>{const {result}=res
setMarker({lat:result.location.lat,lng: result.location.lng
})emit('getCoordinates', {type: 'getLocation',location: {lat:result.location.lat,lng:result.location.lng},address: result.address,addressInfo: {province:result.ad_info.province,city:result.ad_info.city,district:result.ad_info.district}})}).catch( (e:any) =>{console.log(e)ElMessage.error(e.message)})}// 暴露方法给父组件
defineExpose({initMap,setAddress,getMap: () => mapInstance.value
})
</script><style scoped>
#container {width: 100%;height: 450px;
}
</style>

父组件调用

 <Map :mapKey="defalutKey.txMapKey" ref="tMapRef"  ></Map>import Map from "@/components/map/index.vue"
const tMapRef = ref<InstanceType<typeof Map> | null>(null)
// mapKey地图key 
// 中文地址转经纬度,并地图上标点
tMapRef.value?.setAddress(ruleForm.value.mer_address.trim())
tMapRef.value?.initMap()// 地图更新后, 获取更新后的数据
const getCoordinates = (data: any) => {ruleForm.value.long=data.location.lng
ruleForm.value.lat=data.location.lat
if(data.type=="getAddress"){ruleForm.value.mer_address=data.address}else{ruleForm.value.province=data.addressInfo.provinceruleForm.value.city=data.addressInfo.cityruleForm.value.district=data.addressInfo.district}
}
http://www.dtcms.com/a/269086.html

相关文章:

  • 赛事开启|第三届视觉语音识别挑战赛 CNVSRC 2025 启动
  • 自动驾驶ROS2应用技术详解
  • 鸿蒙arkts使用关系型数据库,使用DB Browser for SQLite连接和查看数据库数据?使用TaskPool进行频繁数据库操作
  • Python 异步编程从基础到高级全面指南
  • 模拟数字电路基础-2
  • 初识Neo4j之Cypher(三)
  • leetcode1089.复写零
  • 代码审计-SQL注入
  • 简单的安卓ANR与卡顿分析
  • 要将本地分支强制更新为与远程分支完全一致(以远程为主
  • c++文字游戏_闯关打怪2.0(开源)
  • paimon.disk包:磁盘处理
  • 关于Novatek B/G-R/G白平衡色温坐标系再探究
  • 谢飞机的Java高级开发面试:从Spring Boot到分布式架构的蜕变之旅
  • 安卓10.0系统修改定制化____如何修改ROM 实现开机自动开启开发者选项与隐藏开发者选项
  • 基于区块链的电子签署系统的设计与实现(源码+文档+部署讲解)
  • da y54
  • LED 闪烁 LED 流水灯 蜂鸣器
  • IROS 2025|RL vs MPC性能对比:加州理工无人机实测,谁在「变形控制」中更胜一筹?
  • pg_class 系统表信息
  • React + Express 传输加密以及不可逆加密
  • OpenCV人脸分析------绘制面部关键点函数drawFacemarks()
  • day08-Elasticsearch
  • MinIO与SpringBoot集成完整指南
  • maven 发布到中央仓库常用脚本-02
  • 视频序列和射频信号多模态融合算法Fusion-Vital解读
  • 力扣 hot100 Day37
  • C++笔记之和的区别
  • Isaac Lab:让机器人学习更简单的开源框架
  • Go defer(二):从汇编的角度理解延迟调用的实现