此代码用于微信小程序根据定位获取城市信息,用户取消定位后,再次申请授权定位
小程序JS代码块:
// pages/index/city/city.js
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
},
redingwei: function (e) { //重新申请定位
var that=this
wx.showToast({
title: "重新定位中",
icon: "loading",
mask: false,
duration: 1300
})
//判断是否获得了用户地理位置授权
wx.getSetting({
success: (res) => {
if (!res.authSetting['scope.userLocation']){//未授权 引导用户打开设置
that.openConfirm()
}else{//重新定位
that.dingwei()
}
}
})
},
openConfirm: function () {
var that=this
wx.showModal({
content: '检测到您没打开定位权限,是否去设置打开?',
confirmText: "确认",
cancelText: "取消",
success: function (res) {
//点击“确认”时打开设置页面
if (res.confirm) {
wx.openSetting({
success: (res) => {
//重新定位
that.dingwei()
}
})
} else {
}
}
});
},
dingwei:function(){
var that=this
wx.getLocation({
type: 'wgs84',
success(res) {
//拿到坐标 请求接口 返回code和城市名
wx.request({
url: 'API接口地址,通过坐标请求接口去换取code或者城市名等信息,具体代码见下方',
data: {
latitude: res.latitude,
longitude: res.longitude
},
headers: {
'Content-Type': 'application/json'
},
method: "POST",
success: function (res) {
that.setData({
city: res.data.data.name,
code: res.data.data.code
})
//返回首页
wx.showToast({
title: "重新定位成功",
icon: "success",
mask: true,
duration: 2000
})
setTimeout(function () {
wx.navigateBack({
delta: 1
})
}, 1000)
}
})
},
fail(res) {
}
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
})
服务器接口代码块(PHP形式):
$post_data = $_POST;
$latitude=$post_data['latitude'];
$longitude=$post_data['longitude'];
$ak='你的百度开发ak';
$url='http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location='.$latitude.','.$longitude.'&output=json&pois=0&ak='.$ak;
$result=curl_get_https($url);
$result=str_replace('renderReverse&&renderReverse(','',$result);
$result=trim($result,')');
$info=json_decode($result);
$info=object_array($info); //最终地点信息
echo json_encode(info);
function curl_get_https($url){
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
$tmpInfo = curl_exec($curl); //返回api的json对象
//关闭URL请求
curl_close($curl);
return $tmpInfo; //返回json对象
}
function object_array($array) {
if(is_object($array)) {
$array = (array)$array;
} if(is_array($array)) {
foreach($array as $key=>$value) {
$array[$key] = object_array($value);
}
}
return $array;
}