Note that you have to turn on location information before you can use this feature.
Now app.json is configured
{
"pages": [
"pages/map/map"."pages/index/index"."pages/register/register"."pages/logs/logs"]."window": {
"backgroundTextStyle": "light"."navigationBarBackgroundColor": "#fff"."navigationBarTitleText": "WeChat"."navigationBarTextStyle": "black"
},
"permission": {
"scope.userLocationBackground": {
"desc": "Location information will be used to show the location."}},"requiredBackgroundModes": ["location"]."sitemapLocation": "sitemap.json"
}
Copy the code
Page JS code
getUserLocation() {
wx.getSetting({
success(res) {
console.log(res)
if (res.authSetting['scope.userLocationBackground']) {
wx.startLocationUpdateBackground({
success: (res) = > {
console.log('startLocationUpdate-res', res)
},
fail: (err) = > {
console.log('startLocationUpdate-err', err)
}
})
} else {
if (res.authSetting['scope.userLocation'] = =false) {
console.log('Open the Settings page to authorize')}else {
wx.startLocationUpdateBackground({
success: (res) = > {
console.log('startLocationUpdate-res', res)
},
fail: (err) = > {
console.log('startLocationUpdate-err', err)
}
})
}
}
}
})
},
Copy the code
Then onShow listens for real-time user location information
onShow() {
this.getUserLocation();
const _locationChangeFn = res= > {
console.log('location change', res.latitude, res.longitude)
}
wx.onLocationChange(_locationChangeFn);
},
Copy the code