小程序 api 关于位置的三个方法
- wx.openLocation(Object object) //使用微信内置地图查看位置
- wx.getLocation(Object object) //获取当前的地理位置、速度。
- wx.chooseLocation(Object object) //打开地图选择位置
注:wx.getLocation() 拿到的没有位置名称,需要一个坐标解析位置的插件,腾讯地图为小程序提供了接口SDK来获取位置信息,
文档 http://lbs.qq.com/qqmap_wx_jssdk/index.html
简略步骤:
1.申请开发者密钥(key)
2.下载微信小程序JavaScriptSDK
3.设置安全域名 :https://apis.map.qq.com ()
//小程序公众平台地址 https://mp.weixin.qq.com/
开发 -- >> 开发设置 -->> 服务器域名 添加这个 https://apis.map.qq.com
4. 引入 var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');//这改成你自己插件的路径
注:需要全局配置里面 app.json 加上 permission 小程序接口权限设置
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于位置接口的效果展示"
}
}
(还是写代码吧)
码:(样式不写了)
wxml
<view>
<view>
您当前位置为
<text>{{curCityAddress}}</text>
</view>
<view bindtap='changeLocation'>
手动切换位置
</view>
<view bindtap='openMap'>
打开地图
</view>
</view>
js
var QQMapWX = require("../../libs/qqmap-wx-jssdk.js"); //引入插件
var qqmapsdk; //定义变量(文档那的)
Page({
/**
* 页面的初始数据
*/
data: {
curCityAddress:'未知', // 地址
curLat:0, // 存纬度的 (手动选择地址后 经纬度重新赋值, 打开地图 要用)
curLon:0, //存经度的
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this;
qqmapsdk = new QQMapWX({
key: 'QQSBZ-MGJL5-*************************'
});//新建实例
wx.getLocation({ //小程序 的获取当前的位置经纬度
type: 'wgs84',
success(res) {
that.setData({//给经纬度赋个值吧
curLat:res.latitude,
curLon:res.longitude
})
qqmapsdk.reverseGeocoder({ //腾讯的地图的接口 经纬度查位置 //并没有很精确
location: {
latitude: res.latitude,
longitude: res.longitude
},
success: function (addressRes) {
console.log(addressRes);
// 可看文档取自己需要信息 这只取了address
that.setData({
curCityAddress: addressRes.result.address,
})
},
fail: function (error) {
console.error(error);
},
})
},
fail:function(err){
console.log(err);
//失败的时候 可以查查 用户授权情况
//wx.getSetting();获取用户的当前设置,返回值中只会出现小程序已经向用户请求过的权限
wx.getSetting({
success:function(res){
console.log(res);
console.log(res. authSetting.scope.userLocation); //可以判断用户是否 取消授权了 以便后续可以再次提醒他授权
//授权在这不多做讨论
}
})
}
})
},
changeLocation:function(){
//手动选择事件
var that = this;
wx.chooseLocation({//小程序的手动选择位置
success:function(res){
console.log(res);
//成功以后 取自己需要的信息
that.setData({
curCityAddress: res.name,
curLat:res.latitude,
curLon:res.longitude
})
}
})
},
openMap:function(){
//打开地图
var that = this;
console.log(that);
wx.openLocation({//小程序的打开地图 //如果手动选择过地址 这里就是是刚手动选择完的地址 的 经纬度
latitude:that.data.curLat,
longitude:that.data.curLon,
name: that.data.curCityAddress,
scale: 18
})
}
})
//这样小程序api 位置 三个方法都有用到