request封装
为小程序get/post的promise封装
rq.js
export function request(url, data={}, param={}, method='POST') {
return new Promise((resolve, reject)=>{
let postParam = {
url,
method,
data,
// timeout
// dataType
// responseType
header: {
'content-type': 'application/json' // 默认值
},
success(res) {
resolve(res)
},
error: function (e) {
reject(e)
}
}
postParam = Object.assign(postParam, param)
postParam.fail = postParam.error
if (postParam.url) wx.request(postParam)
})
}
module.exports = {
get(url, data, param){
return request(url, data={}, param={}, method='GET')
},
post(){
return request.apply(null, arguments)
}
}
位置服务方法
需要开通小程序的位置服务功能,在小程序控制台
简单的封装了三个位置服务的方法
- 所在地城市
- 地区搜索
- 范围搜索
// request的promise封装
const iKit = request('./rq.js')
// key为开通位置服务所获取的查询值
// 下面这个key是随便写的
let key = 'JKDBZ-XZVLW-IAQR8-OROZ1-XR3G9-UYBD5'
export function searchRegion(kw, region) {
let opts = {
keyword: encodeURI(kw),
boundary: region ? `region(${encodeURI(region)}, 0)` : '', // 0 为限定范围搜搜索,1为开放范围搜素偶
page_size: 10, // 搜索结果分页最大条数
page_index: 1, // 指定分页
key
}
return new Promise((resolve, rej)=>{
iKit.get('https://apis.map.qq.com/ws/place/v1/search', opts).then(res=>{
resolve(res.data.data)
})
})
}
export function searchCircle(kw, params={}) {
let {lat, lng, distance} = params
if (!lat && !lng) return
if (!distance) distance = 1000 // 搜索范围默认1000米
let opts = {
keyword: encodeURI(kw),
boundary: `nearby(${lat},${lng},${distance})`,
orderby: '_distance', // 范围搜索支持排序,由近及远
page_size: 20, // 搜索结果分页最大条数
page_index: 1, // 指定分页
key
}
return new Promise((resolve, rej)=>{
iKit.get('https://apis.map.qq.com/ws/place/v1/search', opts).then(res=>{
resolve(res.data.data)
})
})
}
// 所在地的城市,省份等区域信息
export function myCity(lat, lng) {
return new Promise((resolve, rej)=>{
let opts = {
location: `${lat},${lng}`,
key
}
iKit.get(`https://apis.map.qq.com/ws/geocoder/v1/`, opts).then(res => {
resolve(res.data.result)
})
})
}
调用
wx.getLocation({
type: 'wgs84',
success(location) {
locationPosition = location
// 所在地信息
myCity(location.latitude, location.longitude).then(res => {
let myCityInfo = res.ad_info
let {city, nation, province, city_code, adcode} = myCityInfo
console.log({title: `国家: ${nation},省份: ${province},城市: ${city}`})
})
// 附近搜索
searchCircle('快餐', {
lat: location.latitude,
lng: location.longitude,
distance: 500
}).then(res=>{
console.log(res)
})
// 地区搜索
searchRegion('酒店', '广州').then(res=>{
console.log(res)
})
}
})
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



