index.js 6.19 KB
import Request from './request'
class GlMapApi {
  constructor(params = {}) {
    const { key, secret } = params
    this.request = new Request(key, secret)
  }
  /** 定义一个异步方法,用于计算两个坐标之间的距离
   *  from 起始位置 [lat,lng]
   * to 结束位置 [lat,lng]
   * type 0:直线距离 , 1:驾车导航距离(仅支持国内坐标) , 3:步行规划距离(仅支持5km之间的距离)
   */
  async calculateDistance(from, to, type = 1) {
    try {
      // 使用数组解构和map方法,将from和to参数转换为字符串,并反转数组顺序,然后用逗号连接,得到目的地坐标和出发地坐标
      const [destination, origins] = [from, to].map(coord => JSON.stringify(coord).reverse().join(','))
      // 调用request对象的get方法,传入请求路径为/v3/distance,请求数据为目的地坐标,出发地坐标和距离类型(默认为1),并等待异步结果,并解构响应数据中的results属性
      const { results } = await this.request.get('/v3/distance', {
        destination,
        origins,
        type
      })
      // 返回一个包含elements属性的对象,值为results
      return { elements: results }
    } catch (error) {
      // 如果发生异常,则抛出错误对象
      throw error
    }
  }
  /** 批量距离计算(矩阵)
   * from 起始位置 [lat,lng]
   * toList 重点位置 [[lat,lng],[lat,lng]]
   * type 0:直线距离 , 1:驾车导航距离(仅支持国内坐标) , 3:步行规划距离(仅支持5km之间的距离)
   */
  async calculateDistanceMatrix(from, toList, type = 1) {
    try {
      // 使用数组解构和map方法,将from和toList参数转换为字符串,并反转数组顺序,然后用逗号或竖线连接,得到目的地坐标和出发地坐标
      const [destination, origins] = [from, toList].map(coord =>
        JSON.stringify(coord)
          .reverse()
          .join(coord === from ? ',' : '|')
      )
      // 调用request对象的get方法,传入请求路径为/v3/distance,请求数据为目的地坐标,出发地坐标和距离类型(默认为1),并等待异步结果,并解构响应数据中的results属性
      const { results } = await this.request.get('/v3/distance', {
        destination,
        origins,
        type
      })
      // 返回一个包含rows属性的对象,值为一个包含elements属性的对象数组,值为results
      return { rows: [{ elements: results }] }
    } catch (error) {
      // 如果发生异常,则抛出错误对象
      throw error
    }
  }
  /**地址解析(地址转坐标)
   *  address (String)
   */
  geocoder(address) {
    return this.request.get('/v3/geocode/geo', {
      address
    })
  }
  /**逆地址解析(坐标位置描述)
   *  location [lat<纬度>,lng<经度>] */
  async detailedAdrress(location) {
    try {
      // 使用数组解构,将location参数分解为纬度和经度
      const [lat, lng] = location
      // 调用request对象的get方法,传入请求路径为/v3/geocode/regeo,请求数据为坐标字符串(反转数组顺序并用逗号连接),并等待异步结果,并解构响应数据中的regeocode属性
      const { regeocode } = await this.request.get('/v3/geocode/regeo', {
          location: JSON.stringify(location).reverse().join(',')
        }),
        // 解构regeocode对象中的addressComponent和formatted_address属性
        { addressComponent, formatted_address } = regeocode,
        // 拼接省市区乡镇作为地址
        address = `${addressComponent.province || ''}${addressComponent.city || ''}${addressComponent.district || ''}${addressComponent.township || ''}`,
        // 定义一个返回数据对象,包含regeocode对象中的所有属性,以及一些格式化后的地址信息和坐标信息
        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
          }
        }

      // 返回一个成功的Promise对象,值为返回数据对象
      return data
    } catch (error) {
      // 如果发生异常,则抛出错误对象
      throw error
    }
  }
  /**IP定位 */
  getLocationByIp() {
    return this.request.get('/v3/ip')
  }
  /**坐标转换
   * locationsList:[[lat,lng],[lat,lng]] 纬度前,经度后 (最多支持40对坐标)
   * coordsys 原坐标系(可选值:
      gps;
      mapbar;
      baidu;
      autonavi(不进行转换))
    *
   */
  // 定义一个方法,用于将一组坐标转换为不同的坐标系
  translate(locationsList, coordsys = 'autonavi') {
    // 使用数组解构和map方法,将locationsList参数转换为字符串,并反转数组顺序,然后用竖线连接,得到locations字符串
    const [locations] = [locationsList].map(coord => JSON.stringify(coord).reverse().join('|'))
    // 调用request对象的get方法,传入请求路径为/v3/assistant/coordinate/convert,请求数据为locations字符串和coordsys参数(默认为autonavi),并返回结果
    return this.request.get('/v3/assistant/coordinate/convert', {
      locations,
      coordsys
    })
  }
}
export default GlMapApi