mapapi.js 2.94 KB
import md5 from '../lib/md5'
import qs from '../lib/qs'
const key = 'F2HBZ-KH73F-7A2J2-JC4UR-WOHCO-UVFGZ'
const secret = 'YBmrM98E5pM4gYeknWiBPaWpFR4AISUl'
const domain = 'https://apis.map.qq.com'
class QQMap {
  setLocaleCompare(params) {
    params.key = key
    let keys = []
    let obj = {}
    Object.keys(params).map(e => keys.push(e))
    keys.sort((a, b) => a.localeCompare(b)).map(e => (obj[e] = params[e]))
    return obj
  }
  getSign(params, methods) {
    let obj = this.setLocaleCompare(params)
    let sign = `${methods}?${decodeURIComponent(qs.stringify(obj))}${secret}`
    return md5(sign)
  }
  get(method, data) {
    return this.request('GET', method, data)
  }
  request(RequestMethods, method, data) {
    return new Promise((resolve, reject) => {
      wx.showNavigationBarLoading()
      if (!data) data = {}
      let header =
        RequestMethods === 'POST'
          ? {
              'content-type': 'application/json'
            }
          : {}
      const sig = this.getSign(data, method)
      let params = {
        ...this.setLocaleCompare(data),
        sig
      }
      wx.request({
        url: `${domain}${method}`,
        data: params,
        method: RequestMethods,
        header,
        dataType: 'json',
        responseType: 'text',
        success({ statusCode, data }) {
          if (statusCode == '200') {
            if (data.status == '0') {
              resolve(data.result || data)
            }
          } else {
            reject(data.result || data)
          }
        },
        fail(error) {
          wx.hideLoading()
          console.error(`接口异常:`, error)
          wx.showToast({
            title: '系统异常',
            icon: 'error'
          })
          reject(error)
        },
        complete() {
          wx.stopPullDownRefresh()
          wx.hideNavigationBarLoading()
        }
      })
    })
  }
  /**计算距离 */
  calculateDistance(from, to) {
    from = from.join(',')
    to = to.join(',')
    return this.get('/ws/distance/v1/', {
      from,
      to,
      mode: 'driving'
    })
  }
  /** 批量距离计算(矩阵) */
  calculateDistanceMatrix(from, toList) {
    from = from.join(',')
    let to = toList.join(';')
    return this.get('/ws/distance/v1/matrix/', {
      from,
      to,
      mode: 'driving'
    })
  }
  /**地址解析(地址转坐标) */
  geocoder(address) {
    return this.get('/ws/geocoder/v1/', {
      address
    })
  }
  /**逆地址解析(坐标位置描述) location=lat<纬度>,lng<经度> */
  detailedAdrress(location) {
    location = location.join(',')
    return this.get('/ws/geocoder/v1/', {
      location
    })
  }
  /**IP定位 */
  getLocationByIp() {
    return this.get('/ws/location/v1/ip')
  }
  /**坐标转换 */
  translate(locations, type = 5) {
    locations = locations.join(';') //格式:纬度前,经度后
    return this.get('/ws/coord/v1/translate', {
      locations,
      type
    })
  }
}
export default new QQMap()