在本文中,我们将通过天地图(Tianditu)实现一个简单的 H5/PC 版地图打卡功能。通过实时获取用户的位置,检测其与打卡点的距离,来决定是否可以完成打卡。代码已上传,本文将逐步介绍如何实现这一功能。
效果图:
准备工作
**天地图(Tianditu)**是一款提供免费使用的在线地图服务,适用于 H5 和 PC 端,且提供了详细的 API 文档和丰富的功能支持。在开发中,我们使用了天地图 API 来完成地图展示和用户位置打卡功能。
申请天地图 API Key
首先,进入天地图官网申请 API Key,这是使用天地图服务的必需步骤。申请完成后,记下你的 Key,稍后会在代码中用到。
加载天地图资源
一旦获取到 API Key,接下来我们将使用该 Key 来加载天地图的外部资源。将下面的代码直接复制到你的项目中,并替换为你申请的 Key:
<script src="https://api.tianditu.gov.cn/api?v=4.0&tk=你的key值"></script>
实现步骤
我们将从地图的初始化开始,逐步构建打卡功能。
1. 初始化项目结构
在项目中,我们使用了 Vue.js 来构建前端页面。以下是最基本的 Vue 组件结构,包含地图容器以及打卡按钮。
<template>
<view>
<div id="mapDiv" style="position: absolute; width: 100%; height: 93%"></div>
<div class="dkBtn" @click="test">打卡</div>
</view>
</template>
在这个结构中,#mapDiv
用于显示天地图,而 .dkBtn
则是打卡按钮。
2. 使用 VConsole 调试工具
为了方便在移动端进行调试,我们引入了 VConsole:
<script module="vconsole" lang="renderjs">
import VConsole from 'vconsole'
new VConsole();
</script>
VConsole
是一个轻量级的移动端开发调试工具,方便我们在手机浏览器上查看日志输出。
3. 引入 Proj4 库处理坐标系转换
由于天地图使用的是 CGCS2000 坐标系,而设备默认的 GPS 使用 WGS84 坐标系,因此我们需要用 proj4
库进行坐标转换。
import proj4 from 'proj4';
const WGS84 = '+proj=longlat +datum=WGS84 +no_defs';
const CGCS2000 = '+proj=longlat +datum=CGCS2000 +no_defs';
proj4
库帮助我们将 WGS84 转换为 CGCS2000 坐标,使用户的位置能正确显示在天地图上。
4. 组件数据和生命周期管理
接下来定义数据和生命周期钩子,用于加载地图并定时获取用户位置:
export default {
name: "MapComponent",
data() {
return {
map: null,
zoom: 17,
timer: null,
user: {
userLng: null,
userLat: null
},
userMarker: null, // 保存用户位置的标记
};
},
mounted() {
this.loadScript().then(() => {
this.initMap();
this.timer = setInterval(() => {
this.getLocation();
}, 1000); // 每秒获取一次用户位置
}).catch((error) => {
console.error("加载天地图脚本失败:", error);
});
},
beforeDestroy() {
clearInterval(this.timer); // 清除定时器,避免内存泄漏
},
};
mounted
生命周期钩子中,我们加载了天地图的脚本,并在地图初始化后每秒获取一次用户位置。
5. 获取用户位置并更新地图标记
使用浏览器的 Geolocation API 获取用户的 WGS84 坐标,再转换为 CGCS2000 坐标并在地图上更新标记。
getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
const userLng = position.coords.longitude;
const userLat = position.coords.latitude;
// 转换为 CGCS2000 坐标
const cgcs2000Coordinates = proj4(WGS84, CGCS2000, [userLng, userLat]);
this.user.userLng = cgcs2000Coordinates[0];
this.user.userLat = cgcs2000Coordinates[1];
const centerPoint = new T.LngLat(this.user.userLng, this.user.userLat);
if (this.userMarker) {
this.map.removeOverLay(this.userMarker); // 清除之前的标记
}
// 添加新的用户位置标记
this.userMarker = new T.Marker(centerPoint);
this.map.addOverLay(this.userMarker);
}, (error) => {
console.error("获取位置失败:", error);
});
} else {
console.log("浏览器不支持获取地理位置");
}
},
6. 实现打卡功能
打卡功能的核心是检测用户与目标打卡点的距离。如果用户在 200 米范围内,则允许打卡。
test() {
const userPosition = new T.LngLat(this.user.userLng, this.user.userLat);
const centerPoint = new T.LngLat(117.0953, 31.833); // 预设打卡点
const distance = this.map.getDistance(centerPoint, userPosition); // 计算距离
if (distance <= 200) {
uni.showToast({
title:"打卡成功"
});
} else {
uni.showToast({
title:"未在打卡范围内"
});
}
},
通过 T.Map
提供的 getDistance
方法,我们可以轻松计算用户与打卡点的距离,并通过判断是否小于 200 米来确定是否成功打卡。
7. 加载天地图脚本
通过动态加载天地图的 API 脚本,可以更灵活地处理地图功能的初始化。
loadScript() {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = "https://api.tianditu.gov.cn/api?v=4.0&tk=你的key值";
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
},
8. 地图初始化与标记
在地图初始化时,我们会在中心点添加一个标记,并创建 200 米的打卡范围:
initMap() {
this.map = new T.Map("mapDiv");
const centerPoint = new T.LngLat(117.0953, 31.833);
this.map.centerAndZoom(centerPoint, this.zoom);
this.map.enableScrollWheelZoom();
this.addMarkerWithLabel(centerPoint, "打卡点");
},
结语
通过天地图的免费 API 和 Vue.js 框架,我们可以轻松实现一个 H5/PC 端的打卡功能。本项目中的关键功能包括用户位置获取、坐标转换、距离计算和地图标记等,适用于需要位置打卡功能的业务场景。
github地址:https://github.com/dashen-lvweijie/tian-map-demo.git
代码已上传,欢迎交流和优化。