You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
3.0 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

Page({
data: {
// 地图初始中心点(默认北京天安门)
latitude: 39.909,
longitude: 116.397,
scale: 16,
markers: [],
currentAddress: '点击下方按钮获取当前位置',
amapKey: 'b7cf2e80f99e2fbb46fa172ef62e71a0' // 替换为你申请的高德地图API Key
},
onLoad: function(options) {
// 页面加载时不自动获取位置,等待用户点击按钮
},
// 获取当前位置
getCurrentLocation: function() {
const that = this;
// 使用微信原生API获取位置
wx.getLocation({
type: 'gcj02', // 国内一般使用gcj02坐标系
success: function(res) {
const latitude = res.latitude;
const longitude = res.longitude;
console.log('获取到的真实位置:', latitude, longitude); // 调试用
// 更新地图中心点
that.setData({
latitude: latitude,
longitude: longitude
});
// 根据坐标获取地址信息
that.getAddressByCoordinate(latitude, longitude);
// 添加当前位置标记(使用定位图标)
that.addMarker(latitude, longitude, '我的位置');
},
fail: function(err) {
console.error('获取位置失败', err);
wx.showModal({
title: '提示',
content: '无法获取您的位置,请检查是否授权位置权限',
showCancel: false
});
}
});
},
// 根据坐标获取地址信息使用高德地图API
getAddressByCoordinate: function(lat, lng) {
const that = this;
const url = `https://restapi.amap.com/v3/geocode/regeo`;
wx.request({
url: url,
data: {
key: this.data.amapKey,
location: `${lng},${lat}`,
extensions: 'all'
},
method: 'GET',
success: function(res) {
if (res.data.status === '1' && res.data.regeocode) {
const address = res.data.regeocode.formatted_address || '未知位置';
that.setData({
currentAddress: address
});
} else {
that.setData({
currentAddress: '获取地址信息失败'
});
}
},
fail: function(err) {
console.error('获取地址失败', err);
that.setData({
currentAddress: '网络错误,无法获取地址'
});
}
});
},
// 添加标记点
addMarker: function(lat, lng, title) {
const newMarker = {
id: Date.now(),
latitude: lat,
longitude: lng,
title: title,
iconPath:'../../img/location.png', // 使用定位图标,如果不存在可以用系统默认图标
width: 30,
height: 30,
rotate: 0,
alpha: 1,
callout: {
content: title,
display: 'ALWAYS',
padding: 8,
borderRadius: 4,
bgColor: '#ffffff',
color: '#000000',
fontSize: 12,
boxShadow: '0 2rpx 4rpx rgba(0, 0, 0, 0.2)'
}
};
this.setData({
markers: [newMarker] // 只保留当前位置标记
});
}
});