使用 wx.getLocation 方法获取用户当前位置的经纬度
同时使用腾讯地图的逆地址解析 API,将经纬度转换为具体的地址信息
这里代码里需要获得密钥KEY的值
进入腾讯位置服务 - 立足生态,连接未来,腾讯位置服务官网
注册登录后,点击“应用管理”->“我的应用”->“创建应用”。
在开发者密钥申请页面按要求填写申请信息,包括应用名称、应用类型等
应用创建成功后,进入“应用管理”->“我的应用”->“设置”。
点击“添加Key”,在弹出的窗口中勾选“微信小程序”并填写“授权APP ID”,勾选“WebServiceAPI”,并保存设置。
在“配额管理”->“账户额度”中选择“逆地址解析”,为其分配额度,即可使用。
注意:请选择真机调试,小程序不支持电脑端查看地图定位等信息。
.js文件
Page({
data: {
//自定义标记点数组
markers:[],
//纬度
latitude:'',
//经度
longitude:'',
},
onLoad: function() {
var that = this;
// 获取当前定位的经纬度信息
wx.showLoading({
title:"定位中",
mask:true
})
wx.getLocation({
type: 'gcj02',
altitude:true,//高精度定位
//定位成功,更新定位结果
success: function (res) {
var latitudee = res.latitude
var longitudee = res.longitude
that.setData({
longitude:parseFloat(longitudee),
latitude: parseFloat(latitudee),
});
that.getReverseGeocoder();
},
//定位失败回调
fail:function(){
wx.showToast({
title:"定位失败",
icon:"none"
})
},
complete:function(){
//隐藏定位中信息进度
wx.hideLoading()
}
})
} ,
getReverseGeocoder: function() {
var that = this;
wx.request({
url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${that.data.latitude},${that.data.longitude}&key=你的KEY`,
success(res) {
if (res.data.status === 0) {
that.setData({
address: res.data.result.formatted_addresses.recommend || res.data.result.address
});
console.log('地址已设置', that.data.address);
} else {
console.error('逆地址解析失败', res.data.message);
}
},
fail() {
console.error('逆地址解析请求失败');
}
});
}
});
.wxml文件
<view class="view">
<map id="map"
longitude="{{longitude}}"
latitude="{{latitude}}"
show-location="true"
style="height: 100%;width: 100%;">
</map>
</view >
//显示地图
<view class="address-label">地址:</view>
<view class="address-content">{{address}}</view>
//显示位置信息
.wxss文件
.view {
position: absolute; /* 使用绝对定位 */
width: 100vw; /* 宽度占满整个屏幕 */
height: 80vh; /* 高度占满整个屏幕 */
top: 0; /* 从屏幕顶部开始 */
left: 0; /* 从屏幕左侧开始 */
}
.address-label{
position: fixed; /* 或者使用 absolute */
bottom:0; /* 距离页面底部的距离 */
left: 0;
height: 17%;
width: 80%; /* 宽度占满整个屏幕 */
background-color: #fff; /* 背景颜色 */
padding: 10px; /* 内边距 */
/* box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1); 添加阴影效果 */
/* 字体大小 */
font-size: 28px;
/* 字体颜色 */
color: rgb(3, 3, 3);
/* 字体风格-粗细 */
font-family: 微软雅黑;
font-weight: bold;
}
.address-content{
position: fixed; /* 或者使用 absolute */
bottom:0; /* 距离页面底部的距离 */
margin-left: 20px;
height: 12%;
width: 80%; /* 宽度占满整个屏幕 */
font-size: 20px;
color: rgb(128, 123, 123);
margin-top: 5px;
font-family: 微软雅黑;
z-index: 100; /* 确保显示在其他内容之上 */
}