index.js 7.49 KB
/*
 * @Descripttion: api封装类
 * @version: 1.0.0
 * @Author: liweikang
 * @Date: 2023-07-04 17:22:43
 * @LastEditors: limin
 * @LastEditTime: 2023-07-05 15:04:01
 * @FilePath: \glsx-map-sdk\src\index.js
 */
import Request from './request'
class GlMapApi {
  constructor(params = {}) {
    const { key, secret } = params
    this.request = new Request(key, secret)
  }
  /**
   * 定义一个异步方法,用于计算两个坐标之间的距离
   * @param {*} from 起始位置 [lat,lng]
   * @param {*} to 结束位置 [lat,lng]
   * @param {*} type 0:直线距离 , 1:驾车导航距离(仅支持国内坐标) , 3:步行规划距离(仅支持5km之间的距离)
   * @param {*} $attrs 自定义入参 参考https://lbs.amap.com/api/webservice/gettingstarted
   * @returns {Promise<{elements: Array}>}
   */
  async calculateDistance(from, to, type = 1, $attrs = {}) {
    try {
      const destination = JSON.parse(JSON.stringify(from)).reverse().join(','),
        origins = JSON.parse(JSON.stringify(to)).reverse().join(','),
        { results } = await this.request.get('/v3/distance', {
          destination,
          origins,
          type,
          ...$attrs
        })
      return {
        elements: results
      }
    } catch (error) {
      throw error
    }
  }
  /**
   * 批量距离计算(矩阵)
   * @param {*} from 起始位置 [lat,lng]
   * @param {*} toList 终点位置 [[lat,lng],[lat,lng]]
   * @param {*} type 直线距离 , 1:驾车导航距离(仅支持国内坐标) , 3:步行规划距离(仅支持5km之间的距离)
   * @param {*} $attrs 自定义入参 参考https://lbs.amap.com/api/webservice/gettingstarted
   * @returns {Promise<{rows: Array}>}
   */
  async calculateDistanceMatrix(from, toList, type = 1, $attrs = {}) {
    try {
      const destination = JSON.parse(JSON.stringify(from)).reverse().join(','),
        origins = JSON.parse(JSON.stringify(toList))
          .map(e => (e = e.reverse()))
          .join('|'),
        { results } = await this.request.get('/v3/distance', {
          destination,
          origins,
          type,
          ...$attrs
        }),
        res = {
          rows: [
            {
              elements: results
            }
          ]
        }

      return Promise.resolve(res)
    } catch (error) {
      return Promise.reject(error)
    }
  }
  /**
   * 地址解析(地址转坐标)
   * @param {*} address (String)
   * @param {*} $attrs 自定义入参 参考https://lbs.amap.com/api/webservice/gettingstarted
   * @returns
   */
  geocoder(address, $attrs = {}) {
    return this.request.get('/v3/geocode/geo', {
      address,
      ...$attrs
    })
  }
  /**
   * 逆地址解析(坐标位置描述)
   * @param {*} location [lat<纬度>,lng<经度>]
   * @param {*} $attrs 自定义入参 参考https://lbs.amap.com/api/webservice/gettingstarted
   * @returns
   */
  async detailedAdrress(location, $attrs = {}) {
    try {
      const [lat, lng] = location
      const { regeocode } = await this.request.get('/v3/geocode/regeo', {
          location: JSON.parse(JSON.stringify(location)).reverse().join(','),
          ...$attrs
        }),
        { addressComponent, formatted_address } = regeocode,
        address = `${addressComponent.province || ''}${addressComponent.city || ''}${addressComponent.district || ''}${addressComponent.township || ''}`,
        data = {
          ...regeocode,
          address,
          formatted_addresses: {
            recommend: formatted_address,
            rough: formatted_address,
            standard_address: formatted_address
          },
          address_component: {
            city: addressComponent.city,
            district: addressComponent.district,
            nation: addressComponent.country,
            province: addressComponent.province,
            street: addressComponent.township
          },
          ad_info: {
            adcode: addressComponent.adcode,
            city: addressComponent.city,
            city_code: addressComponent.citycode,
            district: addressComponent.district,
            location: {
              lat,
              lng
            },
            name: `${addressComponent.country + ',' || ''}${addressComponent.province + ',' || ''}${addressComponent.city + ',' || ''}${addressComponent.district || ''}`,
            nation: addressComponent.country,
            nation_code: '',
            phone_area_code: addressComponent.citycode,
            province: addressComponent.province
          },
          location: {
            lat,
            lng
          }
        }
      return Promise.resolve(data)
    } catch (error) {
      return Promise.reject(error)
    }
  }
  /**
   * IP定位
   * @param {*} $attrs 自定义入参 参考https://lbs.amap.com/api/webservice/gettingstarted
   * @returns
   */
  getLocationByIp($attrs = {}) {
    return this.request.get('/v3/ip', $attrs)
  }
  /**
   * 坐标转换用于将一组坐标转换为不同的坐标系
   * @param {*} locationsList [[lat,lng],[lat,lng]] 纬度前,经度后 (最多支持40对坐标)
   * @param {*} coordsys 原坐标系(可选值:
                                  gps;
                                  mapbar;
                                  baidu;
                                  autonavi(不进行转换))
   * @param {*} $attrs 自定义入参 参考https://lbs.amap.com/api/webservice/gettingstarted
   * @returns  
   */
  translate(locationsList, coordsys = 'autonavi', $attrs = {}) {
    // 使用数组解构和map方法,将locationsList参数转换为字符串,并反转数组顺序,然后用竖线连接,得到locations字符串
    const locations = JSON.parse(JSON.stringify(locationsList))
      .map(e => (e = e.reverse()))
      .join('|')
    // 调用request对象的get方法,传入请求路径为/v3/assistant/coordinate/convert,请求数据为locations字符串和coordsys参数(默认为autonavi),并返回结果
    return this.request.get('/v3/assistant/coordinate/convert', {
      locations,
      coordsys,
      ...$attrs
    })
  }

  /**
   * 路线规划
   *  @param {*} from 起始位置 [lat,lng] 纬度前,经度后
   *  @param {*} to 终点位置 [lat,lng] 纬度前,经度后
   *  @param {*} type 出行类型 1步行 2骑车 3驾车
   *  @param {*} $attrs 自定义入参 参考https://lbs.amap.com/api/webservice/gettingstarted
   */

  async routePlanning(from, to, type = 3, $attrs = {}) {
    const funName = {
        1: '/v3/direction/walking',
        2: '/v4/direction/bicycling',
        3: '/v3/direction/driving'
      }[type],
      origin = JSON.parse(JSON.stringify(from)).reverse().join(','),
      destination = JSON.parse(JSON.stringify(to)).reverse().join(',')
    try {
      const { route } = await this.request.get(funName, {
        origin,
        destination,
        ...$attrs
      })
      return Promise.resolve(route)
    } catch (error) {
      return Promise.reject(error)
    }
  }
  /**
   * 输入提示
   *  @param {*} keywords  查询关键词
   *  @param {*} location 定位坐标 [lat,lng] 纬度前,经度后
   *  @param {*} $attrs 自定义入参 参考https://lbs.amap.com/api/webservice/gettingstarted
   */
  async keywordSearch(keywords, location, $attrs = {}) {
    try {
      const { tips } = await this.request.get('/v3/assistant/inputtips', {
        keywords,
        location: JSON.parse(JSON.stringify(location)).reverse().join(','),
        ...$attrs
      })
      return Promise.resolve(tips)
    } catch (error) {
      return Promise.reject(error)
    }
  }
}
export default GlMapApi