https://www.jb51.net/javascript/328114d1e.htm
一、前期准备
申请腾讯地图密钥
前往腾讯位置服务官网注册账号
创建应用并获取密钥(Key)
小程序配置
javascript
// app.json 中配置权限
{
"permission": {
"scope.userLocation": {
"desc": "需要获取您的地理位置用于距离计算"
}
},
"requiredPrivateInfos": ["getLocation"]
}
二、核心代码实现
javascript
// 引入SDK(在app.js中全局引入)
import qqMap from './libs/qqmap-wx-jssdk.min.js';
const qqmapsdk = new qqMap({
key: '您的腾讯地图KEY'
});
Page({
data: {
branches: [], // 分公司列表
currentLocation: null, // 当前位置
distances: [] // 计算后的距离数据
},
// 生命周期函数
onLoad() {
this.initBranches();
this.getUserLocation();
},
// 初始化分公司数据(可从服务器获取)
initBranches() {
const branches = [
{ id: 1, name: '上海分公司', lat: 31.2304, lng: 121.4737 },
{ id: 2, name: '北京分公司', lat: 39.9042, lng: 116.4074 },
// 添加更多分公司...
];
this.setData({ branches });
},
// 获取用户位置
getUserLocation() {
wx.getLocation({
type: 'wgs84',
success: (res) => {
this.setData({ currentLocation: res });
this.calculateAllDistances();
},
fail: (err) => {
wx.showToast({ title: '获取位置失败', icon: 'none' });
}
});
},
// 计算所有距离
calculateAllDistances() {
const { branches, currentLocation } = this.data;
if (!currentLocation) return;
const distances = branches.map(branch => {
const distance = qqmapsdk.geometry.distance(
[currentLocation.latitude, currentLocation.longitude],
[branch.lat, branch.lng]
);
return {
...branch,
distance: this.formatDistance(distance)
};
});
// 按距离排序
distances.sort((a, b) => a.distance - b.distance);
this.setData({ distances });
},
// 格式化距离显示
formatDistance(meters) {
if (meters >= 1000) {
return (meters / 1000).toFixed(1) + '公里';
}
return Math.round(meters) + '米';
}
});
三、模板展示
html
<view class="container">
<view class="current-location" wx:if="{{currentLocation}}">
当前位置:纬度{{currentLocation.latitude}}, 经度{{currentLocation.longitude}}
</view>
<view class="branch-list">
<view class="branch-item" wx:for="{{distances}}" wx:key="id">
<text class="branch-name">{{item.name}}</text>
<text class="distance">{{item.distance}}</text>
</view>
</view>
</view>
四、注意事项
距离计算类型:
qqmapsdk.geometry.distance 计算的是直线距离
如需计算实际路线距离,需使用路线规划API:
javascript
qqmapsdk.direction({
mode: 'driving',
from: `${currentLocation.latitude},${currentLocation.longitude}`,
to: `${branch.lat},${branch.lng}`,
success: (res) => {
const distance = res.result.routes[0].distance;
}
});
性能优化建议:
当分公司数量较多时(超过50个),建议分页加载
使用缓存机制存储位置信息(通过wx.setStorage)
添加加载状态提示(wx.showLoading)
错误处理:
javascript
// 在calculateAllDistances中添加catch处理
.catch(err => {
console.error('距离计算失败:', err);
wx.showToast({ title: '距离计算失败', icon: 'none' });
});
样式优化建议:
添加地图可视化展示
使用图标区分不同距离范围
添加路线导航功能按钮
完整实现需要根据具体业务需求进行调整,建议在实际开发时:
将地图操作封装成独立模块
添加自动定位失败后的手动选择位置功能
对接后端API获取动态分公司数据
添加位置变化监听(wx.onLocationChange)