mapCutter.vue 18.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
<!--
 * @Date: 2025-01-22 11:40:12
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-03-04 17:53:13
 * @FilePath: /map-demo/src/views/mapCutter.vue
 * @Description: 文件描述
-->
<template>
  <!-- <div style="display: flex; padding: 1rem 0 0 1rem; gap: 1rem;  align-items: center;">
    <div>目标地图经纬度</div>
    <el-input
      v-model="map_center"
      style="width: 240px"
      placeholder="输入经纬度"
      @blur="onCenterBlur"
    />
  </div> -->
  <div style="display: flex; padding: 1rem; gap: 1rem; position: relative;">
    <div style="display: flex; align-items: center;">
      <div>地图中心坐标:&nbsp;</div>
      <el-input
        v-model="map_center"
        style="width: 240px"
        placeholder="输入经纬度"
        @blur="onCenterBlur"
      />
    </div>

    <div style="display: flex; align-items: center;">
      <div>上传图片左下角坐标:&nbsp;</div>
      <el-input
        v-model="map_left_bottom_range"
        style="width: 240px"
        placeholder="输入左下角经纬度"
        @blur="onLBRangeBlur"
      />
      &nbsp;
      <!-- <el-input
        v-model="map_right_top_range"
        style="width: 240px"
        placeholder="输入右上角的经纬度"
        @blur="onRTRangeBlur"
      /> -->
      <!-- <div>上传图片缩放比例:&nbsp;</div>
      <el-input
        v-model="img_ratio"
        style="width: 240px"
        placeholder="输入比例"
        @blur="onRatioBlur"
      >
      </el-input> -->
    </div>

    <div style="display: flex; align-items: center;">
      <div>地图层级:&nbsp;</div>
      <el-select v-model="map_zoom" placeholder="地图层级" style="width: 80px" @change="onZoomChange">
          <el-option
            v-for="item in zoom_options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
    </div>

    <div v-if="showUpload">
      <!-- 触发上传按钮 -->
      <el-button type="primary" @click="triggerFileInput">上传图片</el-button>
      <input ref="fileInput" type="file" @change="handleImageUpload" style="display: none" />&nbsp;
      <el-button type="primary" @click="cutTiles">切割瓦片</el-button>
    </div>

    <div v-if="log_lnglat" style="position: fixed; top: 5rem; left: 1rem; color: black; background-color: white; padding: 1rem; z-index: 9;">
      <div style=" display: flex; align-items: center; justify-content: center;">经纬度:{{ log_lnglat }}&nbsp;&nbsp;&nbsp;<el-button @click="copyText(log_lnglat)" type="primary" :icon="Brush"  size="small">复制</el-button></div>
    </div>
  </div>
  <div id="map-container"></div>
  <div>

  </div>
  <!-- <div v-if="showUpload" class="controls">
    <el-button type="primary" :icon="Top" @click="moveImage('up')">图片上移</el-button>
    <el-button type="primary" :icon="Bottom" @click="moveImage('down')">图片下移</el-button>
    <el-button type="primary" :icon="Back" @click="moveImage('left')">图片左移</el-button>
    <el-button type="primary" :icon="Right" @click="moveImage('right')">图片右移</el-button>
    <el-button type="primary" :icon="Plus" @click="scaleImage(1.01)">图片放大</el-button>
    <el-button type="primary" :icon="Minus" @click="scaleImage(0.99)">图片缩小</el-button>
    <el-button type="primary" @click="rotateMap(10)">地图顺时针旋转</el-button>
    <el-button type="primary" @click="rotateMap(-10)">地图逆时针旋转</el-button>
  </div> -->

  <div v-if="showUpload && imageURL" class="controls-container">
    <!-- 遥控器界面 -->
    <div class="remote-control">
      <!-- 方向控制 -->
      <div class="direction-control">
        <button class="z-button" @click="moveImage('up')">↑</button>
        <div class="horizontal">
          <button class="z-button" @click="moveImage('left')">←</button>
          <button class="z-button" @click="moveImage('right')">→</button>
        </div>
        <button class="z-button" @click="moveImage('down')">↓</button>
      </div>

      <!-- 缩放控制 -->
      <div class="zoom-control">
        <button class="z-button" @click="scaleImage(1.01)">+</button>
        <button class="z-button" @click="scaleImage(0.99)">-</button>
      </div>

      <!-- 旋转控制 -->
      <div class="rotate-control">
        <button class="z-button" @click="rotateMap(1)">↻</button>
        <button class="z-button" @click="rotateMap(-1)">↺</button>
      </div>

      <!-- 透明度控制 -->
      <div class="opacity-control">
        <div style="margin-bottom: 1rem;">透明度: {{ imageOpacity }}%</div>
        <van-slider v-model="imageOpacity" :min="0" :max="100" @change="handleOpacityChange" style="width: 200px;" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, computed, onBeforeUnmount } from "vue";
import { useRoute, useRouter } from 'vue-router'
// import AMapLoader from "@amap/amap-jsapi-loader";
import { TileCutter } from "@/utils/TileCutter";
import { Top, Bottom, Back, Right, Plus, Minus, Brush } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { mapAPI } from '@/api/map.js'

const $route = useRoute();
const $router = useRouter();

const map = ref(null);
const imageLayer = ref(null);
const imageURL = ref(""); // 存储上传的图片
const bounds = ref(null); // 图片覆盖的边界
const mapRotation = ref(0); // 存储地图旋转角度
const zooms = ref([17, 19]);

const map_zoom = ref(17)
const img_ratio = ref(0.5); // 图片缩放比例

const zoom_options = [
  {
    value: 17,
    label: 17,
  },
  {
    value: 18,
    label: 18,
  },
]

const map_left_bottom_range = ref(null); // 120.583625,31.311858
const map_right_top_range = ref(null); // 120.591047,31.318265

const map_center = ref([117.13291,26.873757]);

const log_lnglat = ref('') // 获取当前地址经纬度

const fileInput = ref(null); // 绑定隐藏的 input 元素

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click();
};

const handleKeydown = (e) => { // 键盘控制
  if (e.shiftKey && e.key === '=') {
    // 一些键盘可能需要 Shift 才能输入 `+`,但 `e.key` 实际上是 `=`
    scaleImage(1.01)
  } else {
    switch(e.key) {
      case 'ArrowUp':
        moveImage('up')
        break
      case 'ArrowDown':
        moveImage('down')
        break
      case 'ArrowLeft':
        moveImage('left')
        break
      case 'ArrowRight':
        moveImage('right')
        break
      case '+':
        scaleImage(1.01)
        break
      case '-':
        scaleImage(0.99)
        break
      // case 'r':
      //   rotateMap(10)
      //   break
      // case 'R':
      //   rotateMap(-10)
      //   break
    }
  }
}

onMounted(async () => {
  // 地图中心点
  const code = $route.query.id;
  const { data } = await mapAPI({ i: code });
  map_center.value = data.map.center.map(item => Number(item));
  loadMap();
  window.addEventListener('keydown', handleKeydown)
});

onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeydown)
})

function loadMap() {
  // 初始化地图
  map.value = new AMap.Map('map-container', {
    zoom: 17,
    zooms: zooms.value,
    center: map_center.value,
    rotation: 0, // 初始地图角度
    layers: [
      new AMap.TileLayer.RoadNet(),
      new AMap.TileLayer.Satellite(),
    ],
    keyboardEnable: false
  });


  // Canvas作为切片
  var layer1 = new AMap.TileLayer.Flexible({
    tileSize: 256,
    // cacheSize: 300,
    zIndex: 200,
    createTile: function (x, y, z, success, fail) {
      var c = document.createElement('canvas');
      c.width = c.height = 256;

      var cxt = c.getContext("2d");
      cxt.font = "15px Verdana";
      cxt.fillStyle = "#ff976a";
      cxt.strokeStyle = "#ff976a";
      cxt.strokeRect(0, 0, 256, 256);
      cxt.fillText('(' + [x, y, z].join(',') + ')', 10, 30);

      // 通知API切片创建完成
      success(c);
    }
  });

  layer1.setMap(map.value);

  // 监听 zoomchange 事件
  // map.value.on('zoomchange', () => {
  //   const currentZoom = map.value.getZoom();
  //   if (currentZoom === 18) {
  //     map_zoom.value = 18;
  //   } else {
  //     map_zoom.value = 17;
  //   }
  // });

  // 添加地图点击事件
  map.value.on("click", showInfoClick);
}

function handleImageUpload(event) {
  const file = event.target.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = (e) => {
    imageURL.value = e.target.result;
    addImageToMap(imageURL.value);
  };
  reader.readAsDataURL(file);

  // **解决问题:清空 input,让下次选择同一文件也能触发 change**
  event.target.value = "";
}

const imageOpacity = ref(60); // 默认透明度为60%

const handleOpacityChange = (value) => {
  if (imageLayer.value) {
    imageLayer.value.setOpacity(value / 100);
  }
};

async function addImageToMap(url) {
  if (imageLayer.value) {
    map.value.remove(imageLayer.value);
  }

  // 计算图片右上角经纬度
  const img = new Image();
  img.src = url;

  await new Promise((resolve) => {
    img.onload = resolve;
  });

  const imgWidth = img.width;
  const imgHeight = img.height;
  const aspectRatio = Number((imgWidth / imgHeight).toFixed(3)); // 图片宽高比

  // 获取左下角经纬度
  const [lng1, lat1] = map_left_bottom_range.value;

  // 计算地理坐标的范围(保持图片比例)
  const mapBounds = map.value.getBounds(); // 获取当前地图可视范围
  const southWest = mapBounds.getSouthWest();
  const northEast = mapBounds.getNorthEast();

  // 计算地图当前可视区域的宽高
  const mapLngWidth = Math.abs(northEast.lng - southWest.lng);
  const mapLatHeight = Math.abs(northEast.lat - southWest.lat);

  // 让地图范围的宽高比匹配图片的宽高比
  let lat2, lng2;
  if (mapLngWidth / mapLatHeight > aspectRatio) {
    // 地图太宽了,需要基于高度调整宽度
    const latHeight = mapLatHeight * img_ratio.value; // 设定图片占地图的比例(可以调整)
    const lngWidth = latHeight * (aspectRatio + 0.2);

    lat2 = lat1 + latHeight;
    lng2 = lng1 + lngWidth;
  } else {
    // 地图太高了,需要基于宽度调整高度
    const lngWidth = mapLngWidth * img_ratio.value; // 设定图片占地图的比例(可以调整)
    const latHeight = lngWidth / aspectRatio;

    lat2 = lat1 + latHeight;
    lng2 = lng1 + lngWidth;
  }

  // 更新右上角坐标
  map_right_top_range.value = [lng2, lat2];

  // TAG: 设置图片范围
  bounds.value = new AMap.Bounds(map_left_bottom_range.value, map_right_top_range.value); // 设置图片范围 左下角 (西南) -> 右上角 (东北)
  imageLayer.value = new AMap.ImageLayer({
    url: url,
    bounds: bounds.value,
    zooms: [17, 19],
    opacity: imageOpacity.value / 100 // 使用响应式的透明度值
  });

  map.value.add(imageLayer.value);
}


function cutTiles() {
  if (!imageURL.value) {
    alert("请先上传图片");
    return;
  }
  // TAG: 切割瓦片等级
  TileCutter(imageURL.value, bounds.value, map_zoom.value, imageRotation.value); // 传入图片、地图范围、缩放级别和旋转角度
}

// ✅ 1. 位置移动
const moveImage = (direction) => {
const offset = 0.000002; // 移动步长(经纬度差值)
const sw = bounds.value.getSouthWest();
const ne = bounds.value.getNorthEast();

let newBounds;
switch (direction) {
  case "up":
    newBounds = new AMap.Bounds([sw.lng, sw.lat + offset], [ne.lng, ne.lat + offset]);
    break;
  case "down":
    newBounds = new AMap.Bounds([sw.lng, sw.lat - offset], [ne.lng, ne.lat - offset]);
    break;
  case "left":
    newBounds = new AMap.Bounds([sw.lng - offset, sw.lat], [ne.lng - offset, ne.lat]);
    break;
  case "right":
    newBounds = new AMap.Bounds([sw.lng + offset, sw.lat], [ne.lng + offset, ne.lat]);
    break;
}

bounds.value = newBounds;
imageLayer.value.setBounds(bounds.value);
};

// ✅ 2. 缩放图片
const scaleImage = (factor) => {
  const sw = bounds.value.getSouthWest();
  const ne = bounds.value.getNorthEast();

  const centerX = (sw.lng + ne.lng) / 2;
  const centerY = (sw.lat + ne.lat) / 2;
  const newWidth = (ne.lng - sw.lng) * factor;
  const newHeight = (ne.lat - sw.lat) * factor;

  bounds.value = new AMap.Bounds(
    [centerX - newWidth / 2, centerY - newHeight / 2],
    [centerX + newWidth / 2, centerY + newHeight / 2]
  );

  imageLayer.value.setBounds(bounds.value);
};

// 在 script setup 顶部添加图片旋转角度变量
const imageRotation = ref(0);

// 修改 rotateMap 方法,只旋转图片
const rotateMap = (deltaAngle) => {
  if (!imageLayer.value || !imageURL.value) return;

  imageRotation.value = (imageRotation.value + deltaAngle) % 360;
  // console.log(`图片旋转: ${imageRotation.value}°`);

  const img = new Image();
  img.src = imageURL.value;

  img.onload = () => {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    // 计算旋转后的画布大小
    const angleRad = (imageRotation.value * Math.PI) / 180;
    const cosAngle = Math.abs(Math.cos(angleRad));
    const sinAngle = Math.abs(Math.sin(angleRad));

    // 计算旋转后需要的画布尺寸
    const newWidth = img.width * cosAngle + img.height * sinAngle;
    const newHeight = img.width * sinAngle + img.height * cosAngle;

    // 设置画布大小为旋转后的尺寸
    canvas.width = newWidth;
    canvas.height = newHeight;

    // 移动到画布中心点
    ctx.translate(newWidth / 2, newHeight / 2);
    // 旋转画布
    ctx.rotate(angleRad);
    // 绘制图片,从中心点开始绘制
    ctx.drawImage(img, -img.width / 2, -img.height / 2);

    // 获取旋转后的图片 URL
    const rotatedImageURL = canvas.toDataURL();

    // 重新计算边界框以适应旋转后的图片
    const sw = bounds.value.getSouthWest();
    const ne = bounds.value.getNorthEast();
    const centerLng = (sw.lng + ne.lng) / 2;
    const centerLat = (sw.lat + ne.lat) / 2;

    // 计算四个角的经纬度
    const calculateCorner = (x, y, centerX, centerY) => {
      const angle = imageRotation.value * Math.PI / 180;
      const rotatedX = centerX + (x - centerX) * Math.cos(angle) - (y - centerY) * Math.sin(angle);
      const rotatedY = centerY + (x - centerX) * Math.sin(angle) + (y - centerY) * Math.cos(angle);
      return { lng: rotatedX, lat: rotatedY };
    };

    // 以图片中心点为基准
    const centerX = centerLng;
    const centerY = centerLat;

    const topLeft = calculateCorner(sw.lng, ne.lat, centerX, centerY);
    const topRight = calculateCorner(ne.lng, ne.lat, centerX, centerY);
    const bottomLeft = calculateCorner(sw.lng, sw.lat, centerX, centerY);
    const bottomRight = calculateCorner(ne.lng, sw.lat, centerX, centerY);

    // 找到四个角的最小和最大经纬度
    const minLng = Math.min(topLeft.lng, topRight.lng, bottomLeft.lng, bottomRight.lng);
    const maxLng = Math.max(topLeft.lng, topRight.lng, bottomLeft.lng, bottomRight.lng);
    const minLat = Math.min(topLeft.lat, topRight.lat, bottomLeft.lat, bottomRight.lat);
    const maxLat = Math.max(topLeft.lat, topRight.lat, bottomLeft.lat, bottomRight.lat);

    const newBounds = new AMap.Bounds(
      [minLng, minLat],
      [maxLng, maxLat]
    );

    // 更新图层
    if (imageLayer.value) {
      map.value.remove(imageLayer.value);
    }

    imageLayer.value = new AMap.ImageLayer({
      url: rotatedImageURL,
      bounds: newBounds,
      zooms: [17, 19],
      opacity: imageOpacity.value / 100
    });

    map.value.add(imageLayer.value);
    // FIXME: 旋转后的图片位置会有偏移,需要调整
    moveImage('down')
  };
};

const onZoomChange = (value) => { // 调整地图图层
  // map.value.setZoom(value);
}

const onLBRangeBlur = () => {
  const str = map_left_bottom_range.value;
  if (map_left_bottom_range.value) {
    const formattedArray = str?.split(',').map(Number);
    map_left_bottom_range.value = formattedArray;
  }
}
const onRTRangeBlur = () => {
  const str = map_right_top_range.value;
  const formattedArray = str?.split(',').map(Number);
  map_right_top_range.value = formattedArray;
}

const showUpload = computed(() => {
  return map_left_bottom_range.value ? true : false;
});

const onCenterBlur = () => {
  const str = map_center.value;
  const formattedArray = str.split(',').map(Number);
  map.value.setCenter(formattedArray);
}

const showInfoClick = (e) => {
  var text =
    e.lnglat.getLng() +
    "," +
    e.lnglat.getLat()
  console.log(text);
  log_lnglat.value = text;
}

const copyText = (text) => {
  navigator.clipboard.writeText(text)
  .then(() => {
    ElMessage({
      message: '复制成功',
      type: 'success',
      plain: true,
    })
  })
  .catch(err => {
    ElMessage({
      message: '复制失败',
      type: 'warning',
      plain: true,
    })
    console.error('复制失败:', err);
  });
}

// 控制对象的状态
const position = ref({ x: 0, y: 0 })
const scale = ref(1)
const rotation = ref(0)

// 移动步长
const MOVE_STEP = 10
// 缩放比例
const ZOOM_FACTOR = 1.2
// 旋转步长
const ROTATE_STEP = 30

// 移动控制
const move = (direction) => {
  switch(direction) {
    case 'up':
      position.value.y -= MOVE_STEP
      break
    case 'down':
      position.value.y += MOVE_STEP
      break
    case 'left':
      position.value.x -= MOVE_STEP
      break
    case 'right':
      position.value.x += MOVE_STEP
      break
  }
}

// 放大
const zoomIn = () => {
  scale.value *= ZOOM_FACTOR
}

// 缩小
const zoomOut = () => {
  scale.value /= ZOOM_FACTOR
}

// 旋转
const rotate = (angle) => {
  rotation.value += angle
}

// 组合样式
const objectStyle = computed(() => ({
  transform: `
    translate(${position.value.x}px, ${position.value.y}px)
    scale(${scale.value})
    rotate(${rotation.value}deg)
  `,
  transition: 'transform 0.3s ease-in-out'
}));

const onRatioBlur = () => {
  if (imageURL.value) {
    addImageToMap(imageURL.value);
  }
}
</script>

<style>
#map-container {
  width: 100%;
  height: 100vh;
}

.controls {
  position: absolute;
  top: 8rem;
  right: 10px;
  background: rgba(255, 255, 255, 0.8);
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}


.controls-container {
  position: absolute;
  top: 8rem;
  right: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2rem;
}

.remote-control {
  display: flex;
  gap: 1rem;
  padding: 1rem;
  background: #f0f0f0;
  border-radius: 10px;
}

.opacity-control {
  background: #f0f0f0;
  padding: 1rem 0;
  text-align: center;
}

.direction-control {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.horizontal {
  display: flex;
  gap: 5px;
}

button.z-button {
  width: 50px;
  height: 50px;
  font-size: 20px;
  cursor: pointer;
  border: 1px solid #ccc;
  border-radius: 5px;
  background: white;
  transition: all 0.2s;
}

button.z-button:hover {
  background: #e0e0e0;
}

button.z-button:active {
  transform: scale(0.95);
}

.zoom-control, .rotate-control {
  display: flex;
  flex-direction: column;
  gap: 5px;
}
</style>