小程序如果用户位置不在地图范围内,将用户位置设置在范围里代码
时间: 2023-05-25 07:07:00 浏览: 49
获取地图范围的代码:
```
wx.getLocation({
type: 'gcj02', //使用国测局坐标系
success: function(res) {
var latitude = res.latitude
var longitude = res.longitude
var accuracy = res.accuracy
//获取地图范围
wx.getSetting({
success: function(res) {
var scope = res.authSetting['scope.userLocation']
if (scope) {
wx.chooseLocation({
success: function(res) {
var latitudeScope = res.latitude
var longitudeScope = res.longitude
//计算距离
var distance = getDistance(latitude, longitude, latitudeScope, longitudeScope)
if(distance > scope) {
//用户位置不在地图范围内,设置用户位置在范围里
wx.showToast({
title: '当前位置不在地图范围内',
icon: 'none',
duration: 2000
})
wx.openLocation({
latitude: latitudeScope,
longitude: longitudeScope,
scale: 28
})
}
}
})
} else {
wx.showToast({
title: '地图范围获取失败',
icon: 'none',
duration: 2000
})
}
}
})
}
})
//计算距离
function getDistance(lat1, lng1, lat2, lng2) {
var radLat1 = lat1 * Math.PI / 180.0;
var radLat2 = lat2 * Math.PI / 180.0;
var a = radLat1 - radLat2;
var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
s = s * 6378.137;//地球半径,单位千米
s = Math.round(s * 10000) / 10000;
return s;
}
```
以上代码中的`getDistance`函数是计算两点间距离的函数,需要先定义好。若用户位置不在地图范围内,则通过`wx.openLocation`函数将用户位置设置在范围里,并给予用户提示。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)