港口定位項目開發筆記1·微信小程序端
最近在和組員開發一個港口定位的項目,我目前主要負責微信小程序端實時獲取人員位置的功能,在此寫這個筆記既是爲了幫助自己溫故知新,也希望可以幫助到需要的碼友
Demo1:手動點擊按鈕獲取當前位置
index.wxml
<view class="longitude info">當前經度:{
{locInfo.longitude}}</view>
<view class="latitude info">當前緯度:{
{locInfo.latitude}}</view>
<view class="speed info">當前速度:{
{locInfo.speed}}</view>
<view class="accuracy info">位置精度:{
{locInfo.accuracy}}</view>
<button type="primary" bindtap="getLoca">獲取當前位置</button>
index.wxss
.info{
border: 1px solid red; padding: 20rpx 20rpx; margin: 10rpx 10rpx; }
index.js
getLoca(){
const that = this;
wx.getLocation({
type: 'wgs84',
isHighAccuracy: true,
success (res) {
const latitude = res.latitude //緯度,範圍爲 -90~90,負數表示南緯
const longitude = res.longitude //經度,範圍爲 -180~180,負數表示西經
const speed = res.speed
const accuracy = res.accuracy //位置的精確度
that.setData({
locInfo:res
})
}
})
}
點擊獲取當前位置
在開發這個demo的過程也出現了下面的問題
獲取位置時“提醒getLocation需求在app.json中聲明permission字段”
在app.json文件中加入下面的代碼即可.
"permission": {
"scope.userLocation": {
"desc": "你的位置信息將用於小程序位置接口的效果展示"
}
},
使用wx.getLocation定位不準確問題
我在上邊開發工具中獲取的位置與我所在的位置偏差是很大的,這是因爲我們使用開發工具定位模擬時使用的是IP定位,這在getgetLocation開發文檔下也有提醒,改爲真機調試即可
wx.getLocation開發文檔
利用setData函數回調值問題
想要把獲取的位置信息res回調到前臺頁面,在代碼中使用
this.setData({
locInfo:res
})
無法實現回調
這是因爲success返回的是閉包,所以我們需要在其中加入一行語句
const that = this;
然後在下面使用
that.setData({
locInfo:res
})
即可實現回調