新增街道

This commit is contained in:
TigerNiu
2025-11-18 19:42:38 +08:00
parent acdec7e776
commit 51ba89192e
12 changed files with 249291 additions and 168 deletions

View File

@@ -20,16 +20,36 @@
</button>
</div>
</div>
<PlotPopup
:visible="popupVisible"
:data="popupData"
:position="popupPos"
@enter-sample="showSamples"
@enter-side="showSideTrees"
/>
<SamplePopup
:visible="samplePopupVisible"
:data="samplePopupData"
:position="samplePopupPos"
/>
</template>
<script setup>
import { onMounted, ref, watch } from "vue";
import { onMounted, onBeforeUnmount, ref, watch } from "vue";
import maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import { TDT_KEY } from "../assets/tdt_key.js";
import IndicatorSelector from "./IndicatorSelector.vue";
import Legend from "./Legend.vue";
import { plotGeoJSON, samplePlots, sideTrees } from "../assets/mockPlotData.js";
import PlotPopup from "./PlotPopup.vue";
import SamplePopup from "./SamplePopup.vue";
import bbox from "@turf/bbox";
const popupVisible = ref(false);
const popupData = ref({});
const popupPos = ref({ x: 0, y: 0 });
// 天津市行政区划数据(区级)
const districtUrl =
@@ -93,6 +113,34 @@ const currentDistrict = ref(""); // 当前区名
const mapContainer = ref(null);
let map = null;
const legendItems = ref([]);
let allStreetsData = null;
// 加载街道
async function loadAllStreets() {
if (!allStreetsData) {
const res = await fetch("/data/tianjin_street.geojson");
allStreetsData = await res.json();
}
}
// 定义点击区级多边形的处理函数
async function handleDistrictClick(e) {
const districtName = e.features[0].properties.name;
showStreetLevel(districtName);
}
// 定义点击空白返回的处理函数
function handleMapClick(e) {
const queryLayers = ["tianjin-fill"];
if (map.getLayer("street-fill")) queryLayers.push("street-fill");
const features = map.queryRenderedFeatures(e.point, {
layers: queryLayers,
});
if (!features.length && currentLevel.value === "street") {
backToDistrict();
}
}
// 初始化地图
onMounted(async () => {
@@ -152,26 +200,11 @@ onMounted(async () => {
updateMapColors();
// 点击区多边形,下钻街道级
map.on("click", "tianjin-fill", async (e) => {
const feature = e.features[0];
const districtName = feature.properties.name;
const adcode = feature.properties.adcode;
await showStreetLevel(districtName, adcode);
});
map.off("click", "tianjin-fill", handleDistrictClick);
map.on("click", "tianjin-fill", handleDistrictClick);
// 点击空白返回
map.on("click", (e) => {
// 只查询当前存在的图层
const queryLayers = ["tianjin-fill"];
if (map.getLayer("street-fill")) queryLayers.push("street-fill");
const features = map.queryRenderedFeatures(e.point, {
layers: queryLayers,
});
if (!features.length && currentLevel.value === "street") {
backToDistrict();
}
});
map.off("click", handleMapClick);
map.on("click", handleMapClick);
});
// 缩放监听14级以上显示图斑
@@ -228,52 +261,80 @@ function updateMapColors(level = currentLevel.value) {
}
// 下钻显示街道级
async function showStreetLevel(districtName, adcode) {
try {
const url = `https://geo.datav.aliyun.com/areas_v3/bound/${adcode}_full.json`;
const res = await fetch(url);
const streetGeo = await res.json();
async function showStreetLevel(districtName) {
await loadAllStreets();
if (map.getSource("street")) {
map.removeLayer("street-fill");
map.removeLayer("street-outline");
map.removeSource("street");
}
// ✅ 筛选出该区所有街道
const filteredFeatures = allStreetsData.features.filter(
(f) => f.properties. === districtName
);
map.addSource("street", { type: "geojson", data: streetGeo });
map.addLayer({
id: "street-fill",
type: "fill",
source: "street",
paint: { "fill-color": ["get", "color"], "fill-opacity": 0.65 },
});
map.addLayer({
id: "street-outline",
type: "line",
source: "street",
paint: { "line-color": "#333", "line-width": 1 },
});
if (filteredFeatures.length === 0) {
alert(`区【${districtName}】没有找到街道数据`);
return;
}
// 隐藏区级
// ✅ 构建新的 GeoJSON只包含这个区的街道
const streetGeo = {
type: "FeatureCollection",
features: filteredFeatures,
};
// ✅ 清除旧图层
if (map.getSource("street")) {
map.removeLayer("street-fill");
map.removeLayer("street-outline");
map.removeSource("street");
}
// ✅ 添加新的街道层
map.addSource("street", {
type: "geojson",
data: streetGeo,
});
map.addLayer({
id: "street-fill",
type: "fill",
source: "street",
paint: {
"fill-color": ["get", "color"], // 根据指标设色
"fill-opacity": 0.65,
},
});
map.addLayer({
id: "street-outline",
type: "line",
source: "street",
paint: { "line-width": 1, "line-color": "#333" },
});
currentLevel.value = "street";
currentDistrict.value = districtName;
updateMapColors("street");
// ✅ 隐藏区级图层
if (map.getLayer("tianjin-fill"))
map.setLayoutProperty("tianjin-fill", "visibility", "none");
if (map.getLayer("tianjin-outline"))
map.setLayoutProperty("tianjin-outline", "visibility", "none");
currentLevel.value = "street";
currentDistrict.value = districtName;
// ✅ 自动缩放到该区所有街道范围
const extent = bbox(streetGeo); // [minX, minY, maxX, maxY]
updateMapColors("street");
// 定位到该区
const bounds = new maplibregl.LngLatBounds();
streetGeo.features.forEach((f) => {
const coords = f.geometry.coordinates.flat(3);
coords.forEach(([lng, lat]) => bounds.extend([lng, lat]));
});
map.fitBounds(bounds, { padding: 40, duration: 800 });
} catch (err) {
console.error("加载街道数据失败", err);
alert(`该区(${districtName})暂无街道数据`);
}
map.fitBounds(
[
[extent[0], extent[1]],
[extent[2], extent[3]],
],
{
padding: 40,
duration: 800,
}
);
}
// 返回区级图层
@@ -290,6 +351,50 @@ function backToDistrict() {
updateMapColors("district");
}
// 点击图斑显示弹窗
function handlePlotClick(e) {
const feature = e.features[0];
let prop = feature.properties;
// --- 解析属性 ---
let images = prop.images;
let videos = prop.videos;
if (typeof images === "string") {
try {
images = JSON.parse(images);
} catch {
images = [];
}
}
if (typeof videos === "string") {
try {
videos = JSON.parse(videos);
} catch {
videos = [];
}
}
// 计算屏幕像素位置
const canvas = map.getCanvas().getBoundingClientRect();
const pos = map.project(e.lngLat);
popupPos.value = {
x: pos.x + canvas.left,
y: pos.y + canvas.top,
};
popupData.value = { ...prop, images, videos };
popupVisible.value = true;
}
// 点击空白关闭弹窗
function handleMapClickClosePopup(e) {
const features = map.queryRenderedFeatures(e.point, {
layers: ["plot-fill"],
});
if (!features.length) popupVisible.value = false;
}
// === 图斑层控制 ===
function showPlotLayer() {
// 已存在则直接显示
@@ -351,96 +456,54 @@ function showPlotLayer() {
];
// === 小班点击事件 ===
map.on("click", "plot-fill", (e) => {
const feature = e.features[0];
const prop = feature.properties;
// --- 关键修复 ---
let images = prop.images;
let videos = prop.videos;
map.off("click", "plot-fill", handlePlotClick);
map.off("click", handleMapClickClosePopup);
// 1. 检查 'images' 是否为字符串,如果是,则解析它
if (typeof images === "string") {
try {
images = JSON.parse(images);
} catch (err) {
console.error("解析 'images' 属性失败:", err, images);
images = []; // 解析失败时,提供一个空数组以避免后续错误
}
}
// 2. 检查 'videos' 是否为字符串,如果是,则解析它
if (typeof videos === "string") {
try {
videos = JSON.parse(videos);
} catch (err) {
console.error("解析 'videos' 属性失败:", err, videos);
videos = []; // 解析失败时,提供一个空数组
}
}
// 3. (保险措施) 确保 'images' 和 'videos' 最终一定是数组
// (处理它们可能是 null, undefined, 或解析后不是数组的情况)
if (!Array.isArray(images)) {
images = [];
}
if (!Array.isArray(videos)) {
videos = [];
}
// --- 修复结束 ---
// 动态生成图片与视频轮播HTML
const imgHTML = images
.map(
(src) =>
`<img src="${src}" style="width:100%;border-radius:8px;margin-bottom:6px;">`
)
.join("");
const vidHTML = videos
.map(
(src) =>
`<video controls style="width:100%;border-radius:8px;margin-bottom:6px;"><source src="${src}" type="video/mp4"></video>`
)
.join("");
const popupHTML = `
<div style="width:280px;font-size:13px;">
<h4 style="margin:0 0 8px 0;">${prop.name}</h4>
<p>类型:${prop.type}</p>
<p>面积:${prop.area} ha</p>
<p>采集人员:${prop.collector}</p>
<p>优势树种:${prop.species}</p>
<div style="overflow-y:auto;max-height:200px;">${imgHTML}${vidHTML}</div>
<div style="display:flex;justify-content:space-between;margin-top:8px;">
<button id="enter-sample" style="background:#1976d2;color:white;border:none;padding:4px 8px;border-radius:4px;">进入样地</button>
<button id="enter-side" style="background:#388e3c;color:white;border:none;padding:4px 8px;border-radius:4px;">进入四旁树</button>
</div>
</div>
`;
const popup = new maplibregl.Popup({ closeButton: true })
.setLngLat(e.lngLat)
.setHTML(popupHTML)
.addTo(map);
// 等待DOM加载完后绑定事件
popup.on("open", () => {
document.getElementById("enter-sample").onclick = () => showSamples();
document.getElementById("enter-side").onclick = () => showSideTrees();
});
});
map.on("click", "plot-fill", handlePlotClick);
map.on("click", handleMapClickClosePopup);
}
// === 显示样地 ===
// === 显示样地Polygon ===
function showSamples() {
// 如果之前存在,则移除旧图层和数据源
if (map.getLayer("samples-fill")) map.removeLayer("samples-fill");
if (map.getLayer("samples-outline")) map.removeLayer("samples-outline");
if (map.getSource("samples")) map.removeSource("samples");
if (map.getLayer("samples")) map.removeLayer("samples");
map.addSource("samples", { type: "geojson", data: samplePlots });
map.addLayer({
id: "samples",
type: "circle",
source: "samples",
paint: { "circle-radius": 6, "circle-color": "#1976d2" },
// 添加样地数据源
map.addSource("samples", {
type: "geojson",
data: samplePlots, // ✅ 样地 Polygon 数据
});
// 添加填充图层(样地面)
map.addLayer({
id: "samples-fill",
type: "fill",
source: "samples",
paint: {
"fill-color": "#1976d2",
"fill-opacity": 0.5,
},
});
// 添加轮廓线图层(边界线)
map.addLayer({
id: "samples-outline",
type: "line",
source: "samples",
paint: {
"line-color": "#0d47a1",
"line-width": 2,
},
});
map.off("click", "samples-fill", handleSampleClick);
map.on("click", "samples-fill", handleSampleClick);
map.off("click", handleCloseSamplePopup);
map.on("click", handleCloseSamplePopup);
}
// === 显示四旁树 ===
@@ -462,6 +525,9 @@ function hidePlotLayer() {
if (map.getLayer("plot-fill")) {
map.setLayoutProperty("plot-fill", "visibility", "none");
map.setLayoutProperty("plot-outline", "visibility", "none");
map.setLayoutProperty("samples-fill", "visibility", "none");
map.setLayoutProperty("samples-outline", "visibility", "none");
map.setLayoutProperty("sideTrees", "visibility", "none");
}
// 恢复行政区划或街道层显示
@@ -477,22 +543,73 @@ function hidePlotLayer() {
updateMapColors(currentLevel.value);
}
// === 样地弹窗状态 ===
const samplePopupVisible = ref(false);
const samplePopupData = ref({});
const samplePopupPos = ref({ x: 0, y: 0 });
// === 样地点击事件 ===
function handleSampleClick(e) {
const feature = e.features[0];
let prop = feature.properties;
// 模拟解析样地属性
let images = JSON.parse(prop.images || "[]");
let videos = JSON.parse(prop.videos || "[]");
let trees = JSON.parse(prop.trees || "[]");
const canvas = map.getCanvas().getBoundingClientRect();
const pos = map.project(e.lngLat);
samplePopupPos.value = { x: pos.x + canvas.left, y: pos.y + canvas.top };
samplePopupData.value = { ...prop, images, videos, trees };
samplePopupVisible.value = true;
}
// 点击空白关闭样地弹窗
function handleCloseSamplePopup(e) {
const features = map.queryRenderedFeatures(e.point, {
layers: ["samples-fill"],
});
if (!features.length) samplePopupVisible.value = false;
}
// 监听指标变化
watch(selectedIndicator, () => updateMapColors());
// 页面卸载时销毁地图,释放 WebGL 上下文
onBeforeUnmount(() => {
if (map) {
map.off("click", "tianjin-fill", handleDistrictClick);
map.off("click", handleMapClick);
map.off("click", "plot-fill", handlePlotClick);
map.off("click", handleMapClickClosePopup);
map.remove();
map = null;
}
});
</script>
<style scoped>
.map-wrapper {
position: relative;
.html,
body,
#app,
.map-wrapper,
.map-container {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.map-wrapper {
position: relative;
}
.map-container {
width: 100%;
height: 100%;
}
.legend-panel {
position: absolute;
right: 20px;

View File

@@ -0,0 +1,99 @@
<template>
<div
v-if="visible"
class="plot-popup"
:style="{ left: position.x + 'px', top: position.y + 'px' }"
>
<el-card shadow="always" class="popup-card">
<h4>{{ data.name }}</h4>
<p>类型{{ data.type }}</p>
<p>面积{{ data.area }} ha</p>
<p>采集人员{{ data.collector }}</p>
<p>优势树种{{ data.species }}</p>
<!-- 图片与视频轮播 -->
<el-carousel
height="220px"
indicator-position="outside"
:interval="4000"
arrow="always"
v-if="mediaItems.length"
>
<el-carousel-item
v-for="(item, index) in mediaItems"
:key="index"
class="carousel-item"
>
<template v-if="item.type === 'image'">
<img :src="item.src" class="media" />
</template>
<template v-else-if="item.type === 'video'">
<video controls class="media">
<source :src="item.src" type="video/mp4" />
</video>
</template>
</el-carousel-item>
</el-carousel>
<!-- 操作按钮 -->
<div class="popup-actions">
<el-button type="primary" size="small" @click="$emit('enter-sample')">
进入样地
</el-button>
<el-button type="success" size="small" @click="$emit('enter-side')">
进入四旁树
</el-button>
</div>
</el-card>
</div>
</template>
<script setup>
import { computed } from "vue";
import { ElCard, ElButton, ElCarousel, ElCarouselItem } from "element-plus";
import "element-plus/es/components/card/style/css";
import "element-plus/es/components/button/style/css";
import "element-plus/es/components/carousel/style/css";
import "element-plus/es/components/carousel-item/style/css";
const props = defineProps({
visible: Boolean,
data: { type: Object, default: () => ({}) },
position: { type: Object, default: () => ({ x: 0, y: 0 }) },
});
const mediaItems = computed(() => {
const imgs = Array.isArray(props.data.images) ? props.data.images : [];
const vids = Array.isArray(props.data.videos) ? props.data.videos : [];
return [
...imgs.map((src) => ({ type: "image", src })),
...vids.map((src) => ({ type: "video", src })),
];
});
</script>
<style scoped>
.plot-popup {
position: absolute;
z-index: 999;
transform: translate(-50%, -100%);
}
.popup-card {
width: 280px;
font-size: 13px;
}
.media {
width: 100%;
height: 220px;
object-fit: cover;
border-radius: 8px;
}
.popup-actions {
display: flex;
justify-content: space-between;
margin-top: 8px;
}
</style>

View File

@@ -0,0 +1,257 @@
<template>
<div
v-if="visible"
class="sample-popup"
:style="{ left: position.x + 'px', top: position.y + 'px' }"
>
<el-card shadow="always" class="popup-card">
<!-- 🟢 样地信息 -->
<template v-if="!selectedTree">
<h3 class="plot-title">{{ data.name }}</h3>
<p>面积{{ data.area }} ha</p>
<p>采集人员{{ data.collector }}</p>
<p>样木数量{{ trees.length }}</p>
<!-- 图片与视频 -->
<el-carousel
height="220px"
indicator-position="outside"
:interval="4000"
arrow="always"
v-if="mediaItems.length"
>
<el-carousel-item
v-for="(item, index) in mediaItems"
:key="index"
class="carousel-item"
>
<template v-if="item.type === 'image'">
<img :src="item.src" class="media" />
</template>
<template v-else-if="item.type === 'video'">
<video controls class="media">
<source :src="item.src" type="video/mp4" />
</video>
</template>
</el-carousel-item>
</el-carousel>
<!-- 🌳 样木列表 -->
<h4 class="section-title">样木列表</h4>
<ul class="tree-list">
<li
v-for="(tree, i) in trees"
:key="i"
class="tree-item"
@click="selectTree(tree)"
>
<div class="tree-info">
<span class="tree-id">#{{ tree.id }}</span>
<span class="tree-species">{{ tree.species }}</span>
</div>
<el-icon class="tree-arrow">
<i class="el-icon-arrow-right" />
</el-icon>
</li>
</ul>
</template>
<!-- 🟣 样木详情 -->
<template v-else>
<div class="tree-header">
<el-button
type="primary"
link
size="small"
icon="el-icon-arrow-left"
@click="selectedTree = null"
>
返回样地
</el-button>
<h3>样木 {{ selectedTree.id }}</h3>
</div>
<p>树种{{ selectedTree.species }}</p>
<p>胸径{{ selectedTree.dbh }} cm</p>
<p>树高{{ selectedTree.height }} m</p>
<el-carousel
height="220px"
indicator-position="outside"
:interval="4000"
arrow="always"
v-if="treeMedia.length"
>
<el-carousel-item
v-for="(item, index) in treeMedia"
:key="index"
class="carousel-item"
>
<template v-if="item.type === 'image'">
<img :src="item.src" class="media" />
</template>
<template v-else-if="item.type === 'video'">
<video controls class="media">
<source :src="item.src" type="video/mp4" />
</video>
</template>
</el-carousel-item>
</el-carousel>
</template>
</el-card>
</div>
</template>
<script setup>
import { ref, computed } from "vue";
import {
ElCard,
ElButton,
ElCarousel,
ElCarouselItem,
ElIcon,
} from "element-plus";
import "element-plus/es/components/card/style/css";
import "element-plus/es/components/button/style/css";
import "element-plus/es/components/carousel/style/css";
import "element-plus/es/components/carousel-item/style/css";
import "element-plus/es/components/icon/style/css";
const props = defineProps({
visible: Boolean,
data: { type: Object, default: () => ({}) },
position: { type: Object, default: () => ({ x: 0, y: 0 }) },
});
const selectedTree = ref(null);
// 样地内样木列表
const trees = computed(() => props.data.trees || []);
// 样地媒体
const mediaItems = computed(() => {
const imgs = Array.isArray(props.data.images) ? props.data.images : [];
const vids = Array.isArray(props.data.videos) ? props.data.videos : [];
return [
...imgs.map((src) => ({ type: "image", src })),
...vids.map((src) => ({ type: "video", src })),
];
});
// 当前选中样木媒体
const treeMedia = computed(() => {
if (!selectedTree.value) return [];
const imgs = selectedTree.value.images || [];
const vids = selectedTree.value.videos || [];
return [
...imgs.map((src) => ({ type: "image", src })),
...vids.map((src) => ({ type: "video", src })),
];
});
function selectTree(tree) {
selectedTree.value = tree;
}
</script>
<style scoped>
.sample-popup {
position: absolute;
z-index: 999;
transform: translate(-50%, -100%);
}
.popup-card {
width: 300px;
font-size: 13px;
border-radius: 10px;
overflow: hidden;
}
.plot-title {
font-size: 16px;
font-weight: bold;
color: #2e7d32;
}
.section-title {
margin-top: 10px;
font-size: 14px;
font-weight: 600;
color: #1976d2;
}
/* === 样木列表 === */
.tree-list {
list-style: none;
padding: 0;
margin: 5px 0;
max-height: 130px;
overflow-y: auto;
}
.tree-item {
display: flex;
align-items: center;
justify-content: space-between;
background: #e3f2fd;
padding: 8px 10px;
margin-bottom: 6px;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s ease;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
}
.tree-item:hover {
background: #bbdefb;
transform: translateY(-1px);
}
.tree-info {
display: flex;
flex-direction: column;
}
.tree-id {
font-weight: bold;
color: #1565c0;
}
.tree-species {
font-size: 12px;
color: #444;
}
.tree-arrow {
color: #1565c0;
}
/* 滚动条优化 */
.tree-list::-webkit-scrollbar {
width: 6px;
}
.tree-list::-webkit-scrollbar-thumb {
background-color: #90caf9;
border-radius: 3px;
}
.tree-list::-webkit-scrollbar-thumb:hover {
background-color: #64b5f6;
}
/* 图片与视频 */
.media {
width: 100%;
height: 220px;
object-fit: cover;
border-radius: 8px;
}
/* 样木详情页头部 */
.tree-header {
display: flex;
align-items: center;
justify-content: space-between;
}
</style>