zn-admin-vue3-wcs/src/views/mapPage/example/转换成实际坐标demo.vue
2025-02-15 17:15:48 +08:00

152 lines
3.4 KiB
Vue

<template>
<div class="map-container" ref="mapContainer">
<!-- 地图 -->
<div
class="map"
:style="{
backgroundImage: `url(${mapImage})`,
transform: `scale(${scale})`,
transformOrigin: '0 0',
width: `${mapWidth}px`,
height: `${mapHeight}px`
}"
@click="addLocation"
>
<!-- 库位 -->
<div
v-for="(location, index) in locations"
:key="index"
class="location"
:style="{
left: `${location.projectX}px`,
top: `${location.projectY}px`,
transform: `scale(${scale})` // 反向缩放库位图片
}"
>
<img src="@/assets/location-icon.png" alt="库位" />
</div>
</div>
<!-- 放大缩小按钮 -->
<div class="controls">
<button @click="zoomIn">放大</button>
<button @click="zoomOut">缩小</button>
<button @click="saveLocations">保存</button>
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import mapImage from '@/assets/warehouse-map.png' // 扫描图路径
import locationIcon from '@/assets/location-icon.png' // 库位图标路径
const origin = [-54.4, -34.2]
const resolution = 0.05
const mapContainer = ref(null) // 地图容器
const scale = ref(1) // 缩放比例
const locations = ref([]) // 库位列表
const mapWidth = ref(0) // 地图宽度
const mapHeight = ref(0) // 地图高度
// 加载地图图片并设置初始尺寸
onMounted(() => {
const img = new Image()
img.src = mapImage
img.onload = () => {
mapWidth.value = img.width
mapHeight.value = img.height
}
})
// 添加库位
const addLocation = (event) => {
const rect = mapContainer.value.getBoundingClientRect()
const scrollLeft = mapContainer.value.scrollLeft // 水平滚动条偏移量
const scrollTop = mapContainer.value.scrollTop // 垂直滚动条偏移量
const devicePixelRatio = window.devicePixelRatio || 1
// 计算页面坐标(考虑设备像素比和滚动条偏移量)
const projectX = (event.clientX - rect.left + scrollLeft) / scale.value / devicePixelRatio
const projectY = (event.clientY - rect.top + scrollTop) / scale.value / devicePixelRatio
// 转换为实际坐标
const actualX = (projectX - origin[0]) / resolution
const actualY = (projectY - origin[1]) / resolution
// 添加库位
locations.value.push({
projectX,
projectY,
actualX,
actualY
})
}
// 放大
const zoomIn = () => {
scale.value *= 1.2
}
// 缩小
const zoomOut = () => {
scale.value /= 1.2
}
// 保存点位坐标
const saveLocations = () => {
console.log(
'项目点位坐标:',
locations.value.map((loc) => ({ x: loc.projectX, y: loc.projectY }))
)
console.log(
'实际现场点位坐标:',
locations.value.map((loc) => ({ x: loc.actualX, y: loc.actualY }))
)
alert('点位坐标已保存,请查看控制台输出。')
}
</script>
<style scoped>
.map-container {
position: relative;
width: 100%;
height: 80vh;
overflow: auto;
border: 1px solid #ccc;
}
.map {
background-size: contain;
background-repeat: no-repeat;
position: relative;
}
.location {
position: absolute;
width: 20px;
height: 20px;
cursor: pointer;
}
.location img {
width: 100%;
height: 100%;
}
.controls {
position: fixed;
top: 110px;
right: 110px;
display: flex;
gap: 10px;
}
.controls button {
padding: 5px 10px;
font-size: 14px;
cursor: pointer;
}
</style>