根据坐标逆定位查询位置所在城市信息
onLoad: function (options) { let that = this wx.getLocation({ type: ‘wgs84‘, // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标 success: res => { const latitude = res.latitude const longitude = res.longitude wx.request({ //GET请求 location 位置坐标,格式:location= 39.984154,116.307490 // get_poi 是否返回周边POI列表:1.返回;0不返回(默认) get_poi=1 // key 是开发密钥(Key) url: "https://apis.map.qq.com/ws/geocoder/v1/?location=" + latitude + "," + longitude + "&key=" + locationId, success: (res) => { console.log(res) } }) }, }) }
根据两坐标计算距离
distance.js
function distance(la1, lo1, la2, lo2) { var La1 = la1 * Math.PI / 180.0; var La2 = la2 * Math.PI / 180.0; var La3 = La1 - La2; var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0; var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2))); s = s * 6378.164; //地球半径 return s = Math.round(s * 1000000000) / 1000000000; } export { distance }
onLoad: function (options) {
let that = this
wx.getLocation({
type: ‘wgs84‘, // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标
success: res => {
// // success
const latitude = res.latitude
const longitude = res.longitude
that.setData({
latitude: latitude,
longitude: longitude,
show: false
})
let CITY = wx.getStorageSync(‘city‘)
wx.setStorageSync("location", res);
wx.request({
url: "https://apis.map.qq.com/ws/geocoder/v1/?location=" + latitude + "," +
longitude + "&key=" + locationId,
success: (res) => {
if (res.statusCode == 200) {
let city = res.data.result.address_component.city
let address = res.data.result.ad_info.city_code //city_code
let data = {}
if (CITY != ‘‘) {
if (city == CITY.cityName) {
data.cityNo = address
} else {
data.cityCode = CITY.cityCode
}
that.setData({
cityName: CITY.cityName,
city: city
// code: address
})
} else {
data.cityNo = address
that.setData({
cityName: city,
city: city
// code: address
})
}
// 搜索学校
http.request({
url: ‘school/list‘,
data: data,
success: (res) => {
let location = wx.getStorageSync("location")
let schoolDataListArr = [...res.data.list]
if (location != ‘‘) {
schoolDataListArr.forEach(element => {
let m_x = location.latitude
let m_y = location.longitude
let s_x = element.location_X
let s_y = element.location_Y
let s = distance(m_x, m_y, s_x, s_y)
if (s > 1) {
let S = parseInt(s)
element.d_tance = S + "km"
} else {
let S = (s * 1000).toFixed(1)
element.d_tance = S + "m"
}
})
}
this.setData({
show: false,
schoolDataList: schoolDataListArr
});
},
fail: function (err) {
wx.showToast({
title: ‘网络错误‘,
icon: "none"
})
}
})
} else {
that.setData({
show: true
});
}
},
fail: function (err) {
that.setData({
show: true
});
}
})
},
fail: function (err) {
that.setData({
show: true
});
}
})