腾讯地图API实战:5分钟搞定经纬度录入与地图选点功能(Vue版)

news2026/3/28 8:13:44
腾讯地图API实战5分钟搞定经纬度录入与地图选点功能Vue版在当今的Web开发中地图功能已成为许多应用的标配需求。无论是电商平台的店铺定位还是社交应用的位置分享甚至是企业内部系统的区域管理都离不开地图功能的支持。作为国内主流的地图服务提供商之一腾讯地图API以其稳定的性能和友好的开发者体验赢得了众多前端开发者的青睐。本文将聚焦于一个非常实际且高频的开发场景如何在一个Vue项目中快速集成腾讯地图API实现同时支持手动输入经纬度和地图点击选点的功能组合。这种需求在各类表单提交场景中尤为常见比如商家入驻时的位置登记、活动地点的设置等。我们将从零开始一步步构建这个功能确保即使是刚接触腾讯地图API的开发者也能在5分钟内完成集成。1. 环境准备与基础配置在开始编码之前我们需要完成一些基础准备工作。首先确保你已经创建好一个Vue项目Vue 2或Vue 3均可本文示例基于Vue 2但核心逻辑在Vue 3中同样适用。1.1 获取腾讯地图API密钥要使用腾讯地图服务首先需要申请开发者密钥访问腾讯位置服务官网注册/登录开发者账号进入控制台→应用管理→创建应用获取你的API Key通常以XXXXX-XXXXX-XXXXX形式呈现提示在开发测试阶段你可以使用无限制的测试key但正式上线前请务必申请绑定域名后的正式key避免服务被限制。1.2 引入腾讯地图JS SDK腾讯地图提供了多种引入方式我们推荐直接在public/index.html中通过script标签引入!-- 放在public/index.html的head或body底部 -- script srchttps://map.qq.com/api/gljs?v2.expkey你的KEY/script如果你的项目需要用到地图编辑工具如绘制多边形、测量距离等则需要额外引入tools库script srchttps://map.qq.com/api/gljs?librariestoolsv2.expkey你的KEY/script2. 构建地图选点组件接下来我们创建一个可复用的地图选点组件这将是我们功能的核心部分。2.1 基础地图组件结构新建components/MapPicker.vue文件构建基本框架template div classmap-picker-container div v-ifvisible classmap-modal div classmap-header h3请在地图上选择位置/h3 button clickclose×/button /div div :idmapId classmap-container/div div classmap-footer button clickconfirmSelection确认选择/button button clickclose取消/button /div /div /div /template script export default { name: MapPicker, props: { visible: Boolean, initialPosition: { // 初始位置格式{lat: xx, lng: xx} type: Object, default: null } }, data() { return { mapId: map-${Date.now()}, map: null, marker: null, selectedPosition: null } }, methods: { initMap() { // 初始化地图逻辑 }, close() { this.$emit(close) }, confirmSelection() { if (this.selectedPosition) { this.$emit(select, this.selectedPosition) } this.close() } }, mounted() { if (this.visible) { this.$nextTick(this.initMap) } } } /script style scoped .map-modal { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 80%; height: 70%; background: white; z-index: 1000; box-shadow: 0 0 20px rgba(0,0,0,0.2); display: flex; flex-direction: column; } .map-header, .map-footer { padding: 15px; background: #f5f5f5; display: flex; justify-content: space-between; align-items: center; } .map-container { flex: 1; width: 100%; } /style2.2 实现地图初始化与交互完善initMap方法添加地图交互逻辑initMap() { // 设置默认中心点北京天安门 const defaultCenter this.initialPosition || { lat: 39.9042, lng: 116.4074 } // 初始化地图实例 this.map new TMap.Map(this.mapId, { center: new TMap.LatLng(defaultCenter.lat, defaultCenter.lng), zoom: 13 }) // 添加点击事件监听 this.map.on(click, (evt) { this.selectedPosition { lat: evt.latLng.lat, lng: evt.latLng.lng } // 清除旧标记 if (this.marker) { this.marker.setMap(null) } // 添加新标记 this.marker new TMap.MultiMarker({ map: this.map, styles: { marker: new TMap.MarkerStyle({ width: 25, height: 35, anchor: { x: 16, y: 32 } }) }, geometries: [{ position: new TMap.LatLng( this.selectedPosition.lat, this.selectedPosition.lng ) }] }) }) // 如果有初始位置添加标记 if (this.initialPosition) { this.selectedPosition {...this.initialPosition} this.marker new TMap.MultiMarker({ map: this.map, styles: { marker: new TMap.MarkerStyle({ width: 25, height: 35, anchor: { x: 16, y: 32 } }) }, geometries: [{ position: new TMap.LatLng( this.initialPosition.lat, this.initialPosition.lng ) }] }) } }3. 集成到表单中使用现在我们已经有了一个功能完整的地图选点组件接下来看看如何将其集成到实际表单中使用。3.1 创建位置输入组件新建components/LocationInput.vuetemplate div classlocation-input input v-modelpositionText placeholder请输入经纬度格式纬度,经度 changehandleInputChange / button clickopenMapPicker地图选点/button MapPicker refmapPicker :visibleshowMapPicker :initial-positioncurrentPosition selecthandleMapSelect closeshowMapPicker false / /div /template script import MapPicker from ./MapPicker.vue export default { name: LocationInput, components: { MapPicker }, props: { value: { // 接收v-model的值 type: String, default: } }, data() { return { showMapPicker: false, currentPosition: null } }, computed: { positionText: { get() { return this.value }, set(val) { this.$emit(input, val) } } }, methods: { openMapPicker() { // 如果已有值解析为初始位置 if (this.value) { const [lat, lng] this.value.split(,).map(Number) if (!isNaN(lat) !isNaN(lng)) { this.currentPosition { lat, lng } } } this.showMapPicker true }, handleMapSelect(position) { this.positionText ${position.lat},${position.lng} }, handleInputChange() { // 验证输入格式 const [lat, lng] this.value.split(,).map(Number) if (!isNaN(lat) !isNaN(lng)) { this.currentPosition { lat, lng } } } } } /script style scoped .location-input { display: flex; gap: 10px; } .location-input input { flex: 1; padding: 8px; border: 1px solid #ddd; border-radius: 4px; } .location-input button { padding: 8px 15px; background: #1890ff; color: white; border: none; border-radius: 4px; cursor: pointer; } /style3.2 在父组件中使用在需要使用位置输入的页面中可以这样使用我们的组件template div classform-container h2位置信息/h2 form submit.preventhandleSubmit div classform-group label地点名称/label input v-modelformData.name / /div div classform-group label地理位置/label LocationInput v-modelformData.position / /div button typesubmit提交/button /form /div /template script import LocationInput from /components/LocationInput.vue export default { components: { LocationInput }, data() { return { formData: { name: , position: // 格式纬度,经度 } } }, methods: { handleSubmit() { console.log(提交数据:, this.formData) // 这里可以添加表单提交逻辑 } } } /script4. 高级功能与优化基础功能实现后我们可以进一步优化用户体验和功能完整性。4.1 添加地址反解析功能腾讯地图提供了逆地址解析API可以根据经纬度获取详细地址信息。我们可以扩展我们的组件在用户选择位置后自动填充地址名称。首先在MapPicker.vue中添加地址解析方法async reverseGeocode(lat, lng) { try { const response await fetch( https://apis.map.qq.com/ws/geocoder/v1/?location${lat},${lng}key你的KEY ) const data await response.json() if (data.status 0) { return data.result.address } return null } catch (error) { console.error(地址解析失败:, error) return null } }然后修改confirmSelection方法async confirmSelection() { if (this.selectedPosition) { const address await this.reverseGeocode( this.selectedPosition.lat, this.selectedPosition.lng ) this.$emit(select, { ...this.selectedPosition, address }) } this.close() }4.2 添加输入验证在LocationInput.vue中我们可以添加更严格的输入验证handleInputChange() { const [latStr, lngStr] this.value.split(,) const lat parseFloat(latStr) const lng parseFloat(lngStr) if (!isNaN(lat) !isNaN(lng) lat -90 lat 90 lng -180 lng 180) { this.currentPosition { lat, lng } this.$emit(valid, true) } else { this.currentPosition null this.$emit(valid, false) } }4.3 性能优化与内存管理地图实例会占用较多内存我们需要确保组件销毁时正确清理beforeDestroy() { if (this.map) { this.map.destroy() this.map null } }同时我们可以添加地图加载状态提示template div classmap-picker-container !-- ... -- div v-ifloading classmap-loading 地图加载中... /div div v-else :idmapId classmap-container/div !-- ... -- /div /template script export default { data() { return { loading: true } }, methods: { initMap() { this.loading true // ...地图初始化代码 this.map.on(tilesloaded, () { this.loading false }) } } } /script5. 常见问题与解决方案在实际开发中你可能会遇到以下问题这里提供一些解决方案。5.1 地图不显示或白屏可能原因及解决方案API Key未正确配置检查key是否有效确认key绑定的域名与当前使用域名一致容器尺寸问题确保地图容器有明确的宽高设置添加CSS.map-container { width: 100%; height: 100%; }初始化时机不当确保DOM已经渲染完成再初始化地图使用$nextTick确保元素存在5.2 移动端适配问题移动端使用时需要注意添加viewport meta标签meta nameviewport contentwidthdevice-width, initial-scale1.0, maximum-scale1.0, user-scalableno处理手势冲突// 在初始化地图时添加 this.map.enableScrollWheelZoom() this.map.enableDragging()调整弹窗样式media (max-width: 768px) { .map-modal { width: 95%; height: 80%; } }5.3 坐标转换问题腾讯地图使用的坐标体系与其他地图可能不同需要注意GCJ-02坐标系腾讯地图使用的坐标系WGS-84坐标系GPS设备使用的坐标系BD-09坐标系百度地图使用的坐标系如果需要转换可以使用腾讯地图提供的转换方法// 将WGS84坐标转换为GCJ02坐标 TMap.convertor.translate( new TMap.LatLng(lat, lng), 1, // 1表示WGS84转GCJ02 (result) { console.log(转换后坐标:, result) } )6. 完整代码示例与扩展思路为了帮助开发者快速上手这里提供一个完整的实现方案并探讨可能的扩展方向。6.1 完整组件代码MapPicker.vue完整实现template div classmap-picker-container div v-ifvisible classmap-modal div classmap-header h3请在地图上选择位置/h3 button clickclose×/button /div div v-ifloading classmap-loading 地图加载中... /div div v-else :idmapId classmap-container/div div classmap-footer div classcoordinates 当前选择: {{ selectedPosition ? ${selectedPosition.lat}, ${selectedPosition.lng} : 未选择 }} /div div classactions button clickconfirmSelection :disabled!selectedPosition 确认选择 /button button clickclose取消/button /div /div /div /div /template script export default { name: MapPicker, props: { visible: Boolean, initialPosition: { type: Object, default: null } }, data() { return { mapId: map-${Date.now()}, map: null, marker: null, selectedPosition: null, loading: true } }, watch: { visible(newVal) { if (newVal) { this.$nextTick(this.initMap) } } }, methods: { async initMap() { this.loading true // 设置默认中心点 const defaultCenter this.initialPosition || { lat: 39.9042, lng: 116.4074 } try { // 初始化地图实例 this.map new TMap.Map(this.mapId, { center: new TMap.LatLng(defaultCenter.lat, defaultCenter.lng), zoom: 13 }) // 添加控件 this.map.addControl(new TMap.Control.Zoom()) this.map.addControl(new TMap.Control.Scale()) // 添加点击事件监听 this.map.on(click, (evt) { this.selectedPosition { lat: evt.latLng.lat, lng: evt.latLng.lng } this.updateMarker() }) // 如果有初始位置添加标记 if (this.initialPosition) { this.selectedPosition {...this.initialPosition} this.updateMarker() } // 地图加载完成 this.map.on(tilesloaded, () { this.loading false }) } catch (error) { console.error(地图初始化失败:, error) this.loading false this.$emit(error, 地图加载失败请刷新重试) } }, updateMarker() { // 清除旧标记 if (this.marker) { this.marker.setMap(null) } // 添加新标记 this.marker new TMap.MultiMarker({ map: this.map, styles: { marker: new TMap.MarkerStyle({ width: 25, height: 35, anchor: { x: 16, y: 32 } }) }, geometries: [{ position: new TMap.LatLng( this.selectedPosition.lat, this.selectedPosition.lng ) }] }) }, async reverseGeocode(lat, lng) { try { const response await fetch( https://apis.map.qq.com/ws/geocoder/v1/?location${lat},${lng}key你的KEY ) const data await response.json() if (data.status 0) { return data.result.address } return null } catch (error) { console.error(地址解析失败:, error) return null } }, async confirmSelection() { if (this.selectedPosition) { const address await this.reverseGeocode( this.selectedPosition.lat, this.selectedPosition.lng ) this.$emit(select, { ...this.selectedPosition, address }) } this.close() }, close() { this.$emit(close) } }, beforeDestroy() { if (this.map) { this.map.destroy() this.map null } } } /script style scoped .map-modal { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 80%; height: 70%; background: white; z-index: 1000; box-shadow: 0 0 20px rgba(0,0,0,0.2); display: flex; flex-direction: column; } .map-header { padding: 15px; background: #f5f5f5; display: flex; justify-content: space-between; align-items: center; } .map-header h3 { margin: 0; } .map-container, .map-loading { flex: 1; width: 100%; } .map-loading { display: flex; justify-content: center; align-items: center; background: #f9f9f9; color: #666; } .map-footer { padding: 10px 15px; background: #f5f5f5; display: flex; justify-content: space-between; align-items: center; } .coordinates { font-size: 14px; color: #666; } .actions { display: flex; gap: 10px; } button { padding: 8px 15px; background: #1890ff; color: white; border: none; border-radius: 4px; cursor: pointer; } button:disabled { background: #ccc; cursor: not-allowed; } button[typebutton] { background: #f5f5f5; color: #333; border: 1px solid #ddd; } media (max-width: 768px) { .map-modal { width: 95%; height: 80%; } } /style6.2 扩展功能思路基于这个基础实现你可以考虑添加以下扩展功能多位置标记允许用户在地图上标记多个位置区域选择支持绘制多边形区域并获取边界坐标路线规划集成腾讯地图的路线规划功能地点搜索添加搜索框支持按地名搜索位置离线缓存对常用地图区域进行离线缓存3D地图切换到腾讯地图的3D模式热力图展示特定数据的分布热力图这些扩展功能都可以通过腾讯地图API提供的丰富接口实现为你的应用增添更多价值。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2457292.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…

wordpress后台更新后 前端没变化的解决方法

使用siteground主机的wordpress网站,会出现更新了网站内容和修改了php模板文件、js文件、css文件、图片文件后,网站没有变化的情况。 不熟悉siteground主机的新手,遇到这个问题,就很抓狂,明明是哪都没操作错误&#x…

网络编程(Modbus进阶)

思维导图 Modbus RTU(先学一点理论) 概念 Modbus RTU 是工业自动化领域 最广泛应用的串行通信协议,由 Modicon 公司(现施耐德电气)于 1979 年推出。它以 高效率、强健性、易实现的特点成为工业控制系统的通信标准。 包…

UE5 学习系列(二)用户操作界面及介绍

这篇博客是 UE5 学习系列博客的第二篇,在第一篇的基础上展开这篇内容。博客参考的 B 站视频资料和第一篇的链接如下: 【Note】:如果你已经完成安装等操作,可以只执行第一篇博客中 2. 新建一个空白游戏项目 章节操作,重…

IDEA运行Tomcat出现乱码问题解决汇总

最近正值期末周,有很多同学在写期末Java web作业时,运行tomcat出现乱码问题,经过多次解决与研究,我做了如下整理: 原因: IDEA本身编码与tomcat的编码与Windows编码不同导致,Windows 系统控制台…

利用最小二乘法找圆心和半径

#include <iostream> #include <vector> #include <cmath> #include <Eigen/Dense> // 需安装Eigen库用于矩阵运算 // 定义点结构 struct Point { double x, y; Point(double x_, double y_) : x(x_), y(y_) {} }; // 最小二乘法求圆心和半径 …

使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式

一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明&#xff1a;假设每台服务器已…

XML Group端口详解

在XML数据映射过程中&#xff0c;经常需要对数据进行分组聚合操作。例如&#xff0c;当处理包含多个物料明细的XML文件时&#xff0c;可能需要将相同物料号的明细归为一组&#xff0c;或对相同物料号的数量进行求和计算。传统实现方式通常需要编写脚本代码&#xff0c;增加了开…

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造&#xff0c;完美适配AGV和无人叉车。同时&#xff0c;集成以太网与语音合成技术&#xff0c;为各类高级系统&#xff08;如MES、调度系统、库位管理、立库等&#xff09;提供高效便捷的语音交互体验。 L…

(LeetCode 每日一题) 3442. 奇偶频次间的最大差值 I (哈希、字符串)

题目&#xff1a;3442. 奇偶频次间的最大差值 I 思路 &#xff1a;哈希&#xff0c;时间复杂度0(n)。 用哈希表来记录每个字符串中字符的分布情况&#xff0c;哈希表这里用数组即可实现。 C版本&#xff1a; class Solution { public:int maxDifference(string s) {int a[26]…

【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型

摘要 拍照搜题系统采用“三层管道&#xff08;多模态 OCR → 语义检索 → 答案渲染&#xff09;、两级检索&#xff08;倒排 BM25 向量 HNSW&#xff09;并以大语言模型兜底”的整体框架&#xff1a; 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后&#xff0c;分别用…

【Axure高保真原型】引导弹窗

今天和大家中分享引导弹窗的原型模板&#xff0c;载入页面后&#xff0c;会显示引导弹窗&#xff0c;适用于引导用户使用页面&#xff0c;点击完成后&#xff0c;会显示下一个引导弹窗&#xff0c;直至最后一个引导弹窗完成后进入首页。具体效果可以点击下方视频观看或打开下方…

接口测试中缓存处理策略

在接口测试中&#xff0c;缓存处理策略是一个关键环节&#xff0c;直接影响测试结果的准确性和可靠性。合理的缓存处理策略能够确保测试环境的一致性&#xff0c;避免因缓存数据导致的测试偏差。以下是接口测试中常见的缓存处理策略及其详细说明&#xff1a; 一、缓存处理的核…

龙虎榜——20250610

上证指数放量收阴线&#xff0c;个股多数下跌&#xff0c;盘中受消息影响大幅波动。 深证指数放量收阴线形成顶分型&#xff0c;指数短线有调整的需求&#xff0c;大概需要一两天。 2025年6月10日龙虎榜行业方向分析 1. 金融科技 代表标的&#xff1a;御银股份、雄帝科技 驱动…

观成科技:隐蔽隧道工具Ligolo-ng加密流量分析

1.工具介绍 Ligolo-ng是一款由go编写的高效隧道工具&#xff0c;该工具基于TUN接口实现其功能&#xff0c;利用反向TCP/TLS连接建立一条隐蔽的通信信道&#xff0c;支持使用Let’s Encrypt自动生成证书。Ligolo-ng的通信隐蔽性体现在其支持多种连接方式&#xff0c;适应复杂网…

铭豹扩展坞 USB转网口 突然无法识别解决方法

当 USB 转网口扩展坞在一台笔记本上无法识别,但在其他电脑上正常工作时,问题通常出在笔记本自身或其与扩展坞的兼容性上。以下是系统化的定位思路和排查步骤,帮助你快速找到故障原因: 背景: 一个M-pard(铭豹)扩展坞的网卡突然无法识别了,扩展出来的三个USB接口正常。…

未来机器人的大脑:如何用神经网络模拟器实现更智能的决策?

编辑&#xff1a;陈萍萍的公主一点人工一点智能 未来机器人的大脑&#xff1a;如何用神经网络模拟器实现更智能的决策&#xff1f;RWM通过双自回归机制有效解决了复合误差、部分可观测性和随机动力学等关键挑战&#xff0c;在不依赖领域特定归纳偏见的条件下实现了卓越的预测准…

Linux应用开发之网络套接字编程(实例篇)

服务端与客户端单连接 服务端代码 #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <pthread.h> …

华为云AI开发平台ModelArts

华为云ModelArts&#xff1a;重塑AI开发流程的“智能引擎”与“创新加速器”&#xff01; 在人工智能浪潮席卷全球的2025年&#xff0c;企业拥抱AI的意愿空前高涨&#xff0c;但技术门槛高、流程复杂、资源投入巨大的现实&#xff0c;却让许多创新构想止步于实验室。数据科学家…

深度学习在微纳光子学中的应用

深度学习在微纳光子学中的主要应用方向 深度学习与微纳光子学的结合主要集中在以下几个方向&#xff1a; 逆向设计 通过神经网络快速预测微纳结构的光学响应&#xff0c;替代传统耗时的数值模拟方法。例如设计超表面、光子晶体等结构。 特征提取与优化 从复杂的光学数据中自…