高德地图封装绘制线并且居中,批量循环绘制线

/**
 * 绘制单条线并自动居中
 * @param {Array} points 线的坐标数组,格式:[[lng1, lat1], [lng2, lat2], ...]
 * @param {Object} params 线的配置参数
 * @returns {Promise<AMap.Polyline>} 线实例的Promise
 */
function drawLine(points, params = {}) {
  return mapLoad().then((AMap) => {
    // 处理线样式配置
    const style = {
      path: points, // 线的坐标路径
      strokeColor: params.strokeColor || '#FF33FF', // 线颜色
      strokeOpacity: params.strokeOpacity || 1, // 透明度
      strokeWeight: params.strokeWeight || 2, // 线宽
      strokeStyle: params.strokeStyle || 'solid', // 线样式
      zIndex: params.zIndex ?? 10, // 层级
      bubble: true
    };

    // 创建线实例并添加到地图
    const polyline = new AMap.Polyline(style);
    map.add(polyline);

    // 自动居中逻辑(默认启用,可通过params关闭)
    const autoCenter = params.autoCenter !== false;
    if (autoCenter) {
      map.setFitView([polyline], true, [30, 30, 30, 30]); // 边距避免贴边
    }

    // 执行回调(如果有)
    if (typeof params.onComplete === 'function') {
      params.onComplete(polyline);
    }

    return polyline;
  });
}

/**
 * 批量循环绘制多条线并自动居中显示所有线
 * @param {Array} linesData 多条线的数据数组,格式:
 *   [
 *     { points: [[lng1, lat1], ...], style: { strokeColor, ... } },
 *     { points: [[lng2, lat2], ...], style: { ... } }
 *   ]
 * @param {Object} globalParams 全局配置(对所有线生效,单条线的style会覆盖全局)
 * @returns {Promise<Array<AMap.Polyline>>} 所有线实例的Promise数组
 */
function drawLinesBatch(linesData, globalParams = {}) {
  return mapLoad().then(async (AMap) => {
    const allPolylines = []; // 存储所有线实例

    // 循环绘制每条线
    for (const lineItem of linesData) {
      // 合并全局样式和单条线样式(单条线样式优先级更高)
      const mergedParams = {
        ...globalParams,
        ...lineItem.style,
        autoCenter: false // 批量绘制时先禁用单条线的居中,最后统一居中
      };

      // 绘制单条线并添加到数组
      const polyline = await drawLine(lineItem.points, mergedParams);
      allPolylines.push(polyline);
    }

    // 批量居中逻辑(默认启用,可通过globalParams关闭)
    const autoCenter = globalParams.autoCenter !== false;
    if (autoCenter && allPolylines.length > 0) {
      map.setFitView(allPolylines, true, [50, 50, 50, 50]); // 适配所有线的范围
    }

    // 执行批量完成回调(如果有)
    if (typeof globalParams.onBatchComplete === 'function') {
      globalParams.onBatchComplete(allPolylines);
    }

    return allPolylines;
  });
}

使用方法:

// 批量绘制多条线并自动居中显示所有线
const linesData = [
  {
    points: [
      [116.39748, 39.908823],
      [116.403874, 39.914885]
    ],
    style: { strokeColor: '#1890FF' } // 单条线样式(覆盖全局)
  },
  {
    points: [
      [116.403874, 39.914885],
      [116.410703, 39.920821],
      [116.415, 39.925]
    ],
    style: { strokeColor: '#008000', strokeStyle: 'dashed' }
  }
];

drawLinesBatch(linesData, {
  strokeWeight: 2, // 全局线宽(所有线共享)
  onBatchComplete: (allLines) => {
    console.log('所有线绘制完成,共', allLines.length, '条');
  }
});
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容