第二期 微信云开发之位置信息获取(wx.getLocation)

这篇具有很好参考价值的文章主要介绍了第二期 微信云开发之位置信息获取(wx.getLocation)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

很多小伙伴在开发微信小程序的时候,需要获取当前用户位置信息时,都会遇到该如何获取位置详细信息的问题,以下是我的处理方法。
首先,我在生活智打卡小程序使用的是微信小程序自带的获取用户的位置信息的接口(wx.getLocation),但是这个接口不会返回具体的地址信息(比如xxx地名),主要调用方法和返回参数如下:

wx.getLocation({
	type: 'gcj02', // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标
	success: function (res) {
		console.log("定位成功", res);
	}
});

//返回结果
{	// 位置的精确度,反应与真实位置之间的接近程度,可以理解成10即与真实位置相差10m,越小越精确
	accuracy: 65
	errMsg: "getLocation:ok"
	// 水平精度,单位 m
	horizontalAccuracy: 65
	latitude: 纬度
	longitude: 经度
	// 速度
	speed: -1
	// 垂直精度,单位 m
	verticalAccuracy: 65
}

要想获取具体位置信息,还需要做下一步处理
首先,进入腾讯地图开发者平台,没有账号的先完成账号注册,随后进入控制台应用管理列表添加应用
第二期 微信云开发之位置信息获取(wx.getLocation)
添加key
第二期 微信云开发之位置信息获取(wx.getLocation)
最后可查看官方文档进行逆地址解析了,以下是我写的示例,仅供参考:

wx.request({
	url: 'https://apis.map.qq.com/ws/geocoder/v1/?l&get_poi=1',
	data: {
		"key": "你申请的key",
		"location": "39.984154,116.307490"
	},
	method: 'GET',
	success: function (res) {
    	// success
    	console.log(res.data);
        console.log("请求数据:" + address);
    },
    fail: function () {
    	// fail
    	console.log("请求失败");
    },
    complete: function () {
    // complete
    	console.log("请求完成");
    }
});

部分响应结果(详细可查看官方文档)第二期 微信云开发之位置信息获取(wx.getLocation)

第二期 微信云开发之位置信息获取(wx.getLocation)
如何在地图上展示当前位置图标?请查看以下代码
第二期 微信云开发之位置信息获取(wx.getLocation)
// 前端

<!--pages/position/position.wxml-->
<view class="container">
	<view class="map">
		<map id="myMap" longitude="{{longitude}}" latitude="{{latitude}}" scale="16" markers="{{markers}}"
			polyline="{{polyline}}" show-location="true" show-location style="width: 100%; height: 400rpx;font-size:32rpx"></map>
		<view class="address">位置:{{address}}</view>
		<view class="address">详细地址:{{detail}}</view>
		<view class="address" wx:if="{{!isPosition}}" style="color:red;font-size:24rpx;">请打开手机位置服务,才可以打卡</view>
	</view>
	<view class="content" style="{{'margin-top:'+ marginTop +'rpx'}}">
		<scroll-view scroll-y="true">
			<block wx:if="{{clock_in}}">
				<view class="clockinfo" wx:for="{{clock_in}}" wx:key="item">
					<i-card title="地址:{{clock_in[index].address}}">
						<view slot="content">详细地址:{{clock_in[index].detail}}</view>
						<view slot="footer">打卡时间:{{clock_in[index].time}}</view>
					</i-card>
				</view>
			</block>
			<view wx:if="{{!ifData}}" style="text-align: center;">暂无打卡记录</view>
		</scroll-view>
	</view>
	<view class="btn">
		<button class="button" bindtap="onAdd" type='primary'>开始打卡</button>
	</view>
	<view wx:if="{{showCon}}" class="modal-mask" bindtap="changeModalCancel">
		<view class="modal-dialog">
			<view class="modal-title">温馨提示</view>
			<view class="modal-content">
				获取定位失败,请前往设置打开定位权限,我们将用于定位打卡功能。
			</view>
			<view class="modal-footer">
				<view class="btn-cancel" catchtap="changeModalCancel">取消</view>
				<button open-type="openSetting" class="btn-confirm button-on-view" style="padding:16rpx;"
					catchtap="changeModalCancel">设置</button>
			</view>
		</view>
	</view>
</view>

js代码

const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        address: '',
        latitude: '',
        longitude: '',
        detail: '',
        markers: [],
        _openid: '',
        clock_in: '',
        showCon: false,
        marginTop: 0, // 距离顶部高度
        city: '',
        district: '',
        isPosition: true,
        ifData: true
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        wx.showNavigationBarLoading() //在标题栏中显示加载
        this.getCityNameOFLocation();
        setTimeout(function () {
            wx.hideNavigationBarLoading() //完成停止加载
            wx.stopPullDownRefresh() //停止下拉刷新
        }, 1000);
    },
    changeModalCancel: function () {
        this.setData({
            showCon: false
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.startPullDownRefresh() //下拉刷新
        this.setData({
            _openid: app.getOpenid()
        })
        var that = this;
        setTimeout(function () {
            that.onList();
        }, 1000)
    },
    getCityNameOFLocation: function () {
        var that = this;
        wx.getLocation({
            type: 'gcj02', // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标
            success: function (res) {
                console.log("定位成功", res);
                var latitude = res.latitude;
                var longitude = res.longitude;
                var locationString = latitude + "," + longitude;
                wx.request({
                    url: 'https://apis.map.qq.com/ws/geocoder/v1/?l&get_poi=1',
                    data: {
                        "key": "你申请的key",
                        "location": locationString
                    },
                    method: 'GET',
                    // header: {}, 
                    success: function (res) {
                        // success
                        console.log(res.data);
                        var address = res.data.result.address
                        var detail = res.data.result.formatted_addresses.rough
                        console.log("请求数据:" + address);
                        that.setData({
                            markers: [{
                                iconPath: "",
                                id: 0,
                                latitude: latitude,
                                longitude: longitude,
                                width: 50,
                                height: 50
                            }],
                            address: address,
                            detail: detail,
                            latitude: latitude,
                            longitude: longitude,
                            city: res.data.result.ad_info.city,
                            district: res.data.result.ad_info.district
                        })
                    },
                    fail: function () {
                        // fail
                        console.log("请求失败");
                    },
                    complete: function () {
                        // complete
                        console.log("请求完成");
                    }
                })
            },
            fail: function () {
                // fail
                console.log("定位失败");
                wx.getSetting({
                    success: (res) => {
                        if (!res.authSetting['scope.userLocation']) {
                            that.setData({
                                showCon: true,
                                isPosition: false
                            })
                        }
                    }
                })
            },
            complete: function () {
                // complete
                console.log("定位完成");
            }
        })
    },
    //添加位置信息
    onAdd: function () {
        if (this.data.address) {
            var time = util.formatTime(new Date);
            const db = wx.cloud.database();
            db.collection('position').add({
                data: {
                    address: this.data.address,
                    detail: this.data.detail,
                    latitude: this.data.latitude,
                    longitude: this.data.longitude,
                    time: new Date(time),
                    city: this.data.city,
                    district: this.data.district
                },
                success: res => {
                    // 在返回结果
                    wx.showToast({
                        title: '添加成功',
                    })
                    var that = this;
                    setTimeout(function () {
                        that.onList()
                    }, 1000)
                },
                fail: err => {
                    wx.showToast({
                        icon: 'none',
                        title: '添加失败'
                    })
                    console.error('[数据库] [新增记录] 失败:', err)
                }
            })
        } else {
            wx.showToast({
                title: '请打开位置服务,才可以打卡',
                icon: 'none'
            })
        }
    },
    //查询打卡记录
    onList: function () {
        const db = wx.cloud.database();
        db.collection('position').where({
                _openid: this.data._openid
            }).skip(0).orderBy('time', 'desc')
            .get({
                success: res => {
                    console.log(res.data);
                    if (res.data.length > 0) {
                        var info = [{}];
                        for (var i = 0; i < res.data.length; i++) {
                            var date = new Date(res.data[i].time);
                            var date_value = util.formatTime(date);
                            info[i] = {
                                time: date_value,
                                address: res.data[i].address,
                                detail: res.data[i].detail
                            };
                            // console.log(date_value)
                        }
                        this.setData({
                            clock_in: info
                        })
                    } else {
                        this.setData({
                            ifData: false
                        })
                    }
                    // console.log('[数据库] [查询记录] 成功: ', this.data.clock_in)
                },
                fail: err => {
                    wx.showToast({
                        icon: 'none',
                        title: '查询失败',
                    })
                    console.log(' 获取 clock_in 失败,请检查是否有部署云函数,错误信息:', err)
                }
            });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady(e) {
        var that = this
        // 页面渲染完成
        setTimeout(() => {
            var query = wx.createSelectorQuery();
            query.select('.map').boundingClientRect();
            query.selectViewport().scrollOffset();
            query.exec((res) => {
                console.log(res)
                var listHeight = res[0].height; // 获取list高度
                that.setData({
                    marginTop: listHeight * 2 + 20
                })
            });
        }, 1000)

    }
})

css代码

page {
	background: #F6F6F6;
}
.address{
	margin: 20rpx 20rpx 20rpx 40rpx;
  font-size:30rpx;
}
.map {
  width: 100%;
  position: fixed;
	top: 0;
  z-index: 1;
	background: white;
	box-shadow: 1px 1px rgba(0, 0, 0, 0.1);
}
.title {
	margin: 20rpx 0 20rpx 0;
	width: 100%;
  text-align: center;
	font-weight: bold;
}
.clockinfo {
	margin-top:20rpx;
  width: 100%;
  float: left;
}
.content {
  font-size: 28rpx;
  margin-bottom: 200rpx;
}
.btn {
	position: fixed;
  height: 140rpx;
  text-align: center;
	width: 100%;
  bottom: 0rpx;
  background-color: white;
}
.button {
  margin-top: 24rpx;
}
.modal-mask {
	width: 100%;
	height: 100%;
	position: fixed;
	top: 0;
	left: 0;
	background-color: rgba(0, 0, 0, 0.5);
	overflow: hidden;
	z-index: 9999;
	display: flex;
	align-items: center;
	justify-content: center;
}
.modal-dialog {
	width: 540rpx;
	overflow: hidden;
	z-index: 9999;
	background: #f9f9f9;
	border-radius: 5rpx;
}
.modal-title {
	padding-top: 30rpx;
	font-size: 32rpx;
	color: #030303;
	text-align: center;
}
.modal-content {
	padding: 20rpx 32rpx;
	font-size: 28rpx;
}
.modal-footer {
	display: flex;
	flex-direction: row;
	height: 86rpx;
	border-top: 1px solid #dedede;
	font-size: 34rpx;
	line-height: 86rpx;
}
.btn-cancel {
	width: 50%;
	color: #abb4bd;
	text-align: center;
	border-right: 1px solid #dedede;
}
.btn-confirm {
	width: 50%;
	color: #6fb64b;
	text-align: center;
	font-weight: 500;
}

好了,在此如果有什么不懂的在评论区留言或者私信联系作者,感谢您的支持!!!文章来源地址https://www.toymoban.com/news/detail-493892.html

到了这里,关于第二期 微信云开发之位置信息获取(wx.getLocation)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 微信小程序地理位置接口wx.getLocation接口申请方法技巧

    我们在开发微信小程序的时候,提交审核微信官方就会检测咱们的小程序有没有用到位置功能,涉及用到哪个位置接口,然后就会要求我们先申请相应的位置接口,审核通过后才可以发布小程序。 这个接口审核一直是让大家头痛的事情,有的小伙伴申请几十次都不给过,有时

    2024年02月13日
    浏览(29)
  • 微信小程序申请地理位置接口wx.getLocation不通过的应对方案 过率很高

    1、 你好,你的小程序“xxxxxx”申请的wx.getLocation接口因你提供的申请原因/辅助图片/网页/视频内容无法确认申请接口使用场景审核不通过,建议修改后重新提交。 2、 你好,你的小程序“xxxxx”申请的wx.getLocation接口因你所描述的小程序接口使用场景,目前未符合接入wx.getL

    2024年02月15日
    浏览(39)
  • uniapp开发指南1 -- 微信小程序申请 wx.getLocation、wx.chooseLocation API指南

    最近项目中要使用微信小程序的地理位置信息采集的功能,需要使用 wx.chooseLocation 和 wx.getLocation 两个API接口。于是我全程负责从申请到开发,下面由我来简述一下申请和开发指南。 这是地址: 微信公众平台 首先我们进入的小程序后台,点击 “ 设置 ” 进入 “ 基本设置

    2024年02月03日
    浏览(42)
  • uni-app(微信小程序)获取当前位置uni.getLocation

     1、微信公众平台  开发  开发管理   2、开通之后到项目文件    3、下载腾讯地图插件并引入到文件中    

    2024年02月11日
    浏览(40)
  • 微信小程序开发,小程序类目符合,线上版本无权限申请wx.getLocation接口

    我开发 的小程序类目符合wx.getLocation接口的申请标准      但是却还是显示无权限申请 后来研究好久才发现,小程序需要在发布线上版本时提交用户隐私保护指引  如未设置也可以在 设置-服务内容声明-用户隐私保护指引-声明处理用户信息项并补充填写后提交用户隐私协议

    2024年02月15日
    浏览(39)
  • 小程序地理位置接口wx.getLocation申请审核解决方法(详细说明及避坑)

    本人申请了三次才最终通过,简单说一下坑 前几天想实现定位功能改了一天代码手机上也不行。 晚上登上小程序管理界面才发现那个功能要申请。。。那就申请呗 申请路径 :小程序页面-开发-开发管理-接口设置-地理位置 之后就提交申请,两次都不过就不理解了。特地去问

    2024年01月16日
    浏览(41)
  • 【踩坑记录】微信开发者工具已授权位置getLocation时却显示未授权

    前提:uniapp的wx小程序项目,接手别人的老项目,getLocation时开发者工具报未授权,顺着授权步骤走却发现已经授权了。已经上线的小程序没问题。遇到有段时间了,今天有时间看看:      如上图:明明已经授权了 排查流程: 1.uni.authorize()查询是否已授权 结果:  2.查看g

    2024年02月12日
    浏览(54)
  • 微信使用wx.getLocation

    1,小程序管理后台 -「开发」-「开发管理」-「接口设置」” 中完成权限申请; 2,需在 app.json 中声明其需调用的地理位置相关接口 3,在页面使用  

    2024年01月17日
    浏览(50)
  • 小程序发布提审被驳回,提示当前提审小程序代码包中地理位置相关接口wx.getLocation暂未开通

    如图所示,提示地理位置相关接口wx.getLocation暂未开通,这是因为从2022年4月18日开始,在代码审核环节将检测该接口是否已完成开通,如未开通,将在代码提审环节进行拦截。 以下提供解决办法: 首先确认自己的小程序是否是在允许使用的类目中——需要先通过类目审核。

    2024年02月16日
    浏览(37)
  • 微信小程序wx.getLocation接口审核不通过

    审核不通过的原因一般包含这几种: 一、当前提审小程序代码包中地理位置相关接口( wx.getLocation )暂未开通 分析原因:接口未开通。 解决方法:按下图申请开通对应的接口即可。 二、你所描述的小程序接口使用场景,目前未符合接入wx.getLocation(获取当前的地理位置、速度

    2024年02月09日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包