先上效果图:
说明: 用了原生的wx.getLocation 定位功能获取 经纬度,然后通过高德解析位置(可以获取位置信息,及附近地址,天气等)
准备:需要下载高德小程序位置组件https://lbs.amap.com/api/wx/download
配置:在创建的项目中,新建一个名为 libs 目录,将 amap-wx.js (amap-wx.js 从相关下载页面下载的 zip 文件解压后得到)文件拷贝到 libs 的本地目录下,如下图所示。
引用高德组件
(下面有完整代码包含城市锚点滚动功能)主要代码如下:
import amapFile from'../../libs/amap-wx.js' //记着引用
methods: {
//定位城市
gpsCity(){
var that=this;
//调用自带位置获取
wx.getLocation({
type: 'gcj02', //返回可以用于wx.openLocation的经纬度
success: function (res) {
var latitude = res.latitude//维度
var longitude = res.longitude//经度
that.loadCity(latitude,longitude);//调用高德
}
})
},
//把当前位置的经纬度传给高德地图,调用高德API获取当前地理位置,天气情况等信
loadCity(latitude, longitude){
var that=this;
var myAmapFun = new amapFile.AMapWX({ key: that.markersData.key });
myAmapFun.getRegeo({
location: '' + longitude + ',' + latitude + '',//location的格式为'经度,纬度'
success: function (data) {
console.log(data);//全部数据
var cityCode=data[0].regeocodeData.addressComponent.adcode//获取城市code
that.gpsCode=cityCode
that.city_name=data[0].regeocodeData.addressComponent.province//获取省份名称
console.log(that.gpsCode);
console.log(that.city_name);
},
fail: function (info) {}
});
},
}
完整页面代码如下(包含锚点滚动城市列表功能博客有篇文章介绍此功能):
{{item.letter}}
定位城市
{{city_name}}
重新定位
热门城市
{{item.name}}
{{item.letter}}
{{item2.name}}
{{item3.name}}