392 lines
12 KiB
Vue
392 lines
12 KiB
Vue
<template>
|
||
<div class="sb-map" :style="{ height: height }">
|
||
<slot name="tip"></slot>
|
||
<div ref="mapRef" class="sb-map__container"></div>
|
||
</div>
|
||
</template>
|
||
|
||
<script setup lang="ts">
|
||
import { ref, watch, onMounted, onBeforeUnmount, nextTick } from 'vue';
|
||
import L from 'leaflet';
|
||
import 'leaflet/dist/leaflet.css';
|
||
import { isPointInGeoJson } from '@/utils/geo';
|
||
|
||
export interface MapPoint {
|
||
id?: string | number;
|
||
lng: number;
|
||
lat: number;
|
||
name?: string;
|
||
icon?: string;
|
||
status?: string;
|
||
/** 点击图标时在地图上直接弹出的信息卡内容(HTML) */
|
||
popupHtml?: string;
|
||
}
|
||
|
||
const props = defineProps<{
|
||
/** 地图高度 */
|
||
height?: string;
|
||
/** 选点模式:点击地图拾取坐标 */
|
||
pickMode?: boolean;
|
||
/** 展示点位列表 */
|
||
points?: MapPoint[];
|
||
/** 当前选中点 */
|
||
selected?: MapPoint | null;
|
||
/** 初始中心 [lng, lat] */
|
||
center?: [number, number];
|
||
/** 初始缩放 */
|
||
zoom?: number;
|
||
/** 底图类型:road 路网图 / sat 卫星影像 */
|
||
base?: 'road' | 'sat';
|
||
/** 行政区划 GeoJSON(FeatureCollection) */
|
||
geoJson?: any;
|
||
/** 各区划统计值:区划名称 -> 数量 */
|
||
districtCounts?: Record<string, number>;
|
||
/** 高亮区划名称 */
|
||
highlightDistrict?: string;
|
||
/** 首次渲染区划时自动缩放到区划范围 */
|
||
fitGeo?: boolean;
|
||
/** 只显示区划边界,不显示名称/统计(用于选点限制范围) */
|
||
boundaryOnly?: boolean;
|
||
/** 隐藏区划名称标签(默认显示) */
|
||
hideDistrictLabels?: boolean;
|
||
/** 选点限制:只允许落在 geoJson 范围内 */
|
||
restrictGeo?: boolean;
|
||
}>();
|
||
|
||
const emit = defineEmits<{
|
||
(e: 'pick', point: MapPoint): void;
|
||
(e: 'pick-reject', point: MapPoint): void;
|
||
(e: 'point-click', point: MapPoint): void;
|
||
(e: 'district-click', name: string): void;
|
||
}>();
|
||
|
||
const mapRef = ref<HTMLDivElement>();
|
||
let map: L.Map | null = null;
|
||
let markerLayer: L.LayerGroup | null = null;
|
||
let pickMarker: L.Marker | null = null;
|
||
let lastValidPick: MapPoint | null = null;
|
||
let districtLayer: L.GeoJSON | null = null;
|
||
let districtLabelLayer: L.LayerGroup | null = null;
|
||
let resizeObserver: ResizeObserver | null = null;
|
||
|
||
/** 高德瓦片(GCJ-02,与 ZHJTQY 一致,免 key) */
|
||
const TILE_URLS: Record<string, string> = {
|
||
road: 'https://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
|
||
sat: 'https://webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}'
|
||
};
|
||
const TILE_OPTS: L.TileLayerOptions = {
|
||
subdomains: ['1', '2', '3', '4'],
|
||
maxZoom: 18,
|
||
minZoom: 3,
|
||
attribution: '© 高德地图'
|
||
};
|
||
|
||
function initMap() {
|
||
if (!mapRef.value) return;
|
||
const center = props.center ?? [118.97, 29.03]; // 默认衢州
|
||
map = L.map(mapRef.value, {
|
||
center: [center[1], center[0]], // Leaflet 是 [lat, lng]
|
||
zoom: props.zoom ?? 12,
|
||
zoomSnap: 0.5,
|
||
zoomDelta: 0.5,
|
||
zoomControl: false,
|
||
attributionControl: false
|
||
});
|
||
// 缩放控件放右下角:左上角常被图层面板/标题栏遮挡
|
||
L.control.zoom({ position: 'bottomright' }).addTo(map);
|
||
L.tileLayer(TILE_URLS[props.base ?? 'road'], TILE_OPTS).addTo(map);
|
||
// 区划名称层:位于区划面之上、设备点位之下
|
||
const labelPane = map.createPane('districtLabels');
|
||
labelPane.style.zIndex = '450';
|
||
districtLabelLayer = L.layerGroup().addTo(map);
|
||
markerLayer = L.layerGroup().addTo(map);
|
||
map.on('click', (e: L.LeafletMouseEvent) => {
|
||
if (!props.pickMode) return;
|
||
const point: MapPoint = { lng: +e.latlng.lng.toFixed(6), lat: +e.latlng.lat.toFixed(6) };
|
||
if (props.restrictGeo && props.geoJson && !isPointInGeoJson(props.geoJson, point.lng, point.lat)) {
|
||
emit('pick-reject', point);
|
||
return;
|
||
}
|
||
setPickMarker(point);
|
||
emit('pick', point);
|
||
});
|
||
renderPoints();
|
||
// 组件挂载时已有选中点(如设备已有坐标),补画标记
|
||
if (props.pickMode && props.selected?.lng && props.selected?.lat) {
|
||
setPickMarker(props.selected);
|
||
}
|
||
|
||
// 容器尺寸变化(如侧栏收起、页面切换)后重算地图,避免点击偏移/瓦片错位
|
||
resizeObserver = new ResizeObserver(() => {
|
||
map?.invalidateSize();
|
||
});
|
||
resizeObserver.observe(mapRef.value);
|
||
}
|
||
|
||
function setPickMarker(point: MapPoint) {
|
||
if (!map) return;
|
||
lastValidPick = point;
|
||
if (pickMarker) {
|
||
map.removeLayer(pickMarker);
|
||
}
|
||
pickMarker = L.marker([point.lat, point.lng], { draggable: true }).addTo(map);
|
||
pickMarker.on('dragend', () => {
|
||
const pos = pickMarker!.getLatLng();
|
||
const next = { lng: +pos.lng.toFixed(6), lat: +pos.lat.toFixed(6) };
|
||
if (props.restrictGeo && props.geoJson && !isPointInGeoJson(props.geoJson, next.lng, next.lat)) {
|
||
// 拖出衢州范围:回到上一个有效位置
|
||
if (lastValidPick) {
|
||
pickMarker!.setLatLng([lastValidPick.lat, lastValidPick.lng]);
|
||
}
|
||
emit('pick-reject', next);
|
||
return;
|
||
}
|
||
lastValidPick = next;
|
||
emit('pick', next);
|
||
});
|
||
map.panTo([point.lat, point.lng]);
|
||
}
|
||
|
||
function renderPoints() {
|
||
if (!map || !markerLayer) return;
|
||
markerLayer.clearLayers();
|
||
(props.points ?? []).forEach((p) => {
|
||
if (!p.lng || !p.lat) return;
|
||
const icon = p.icon
|
||
? L.icon({ iconUrl: p.icon, iconSize: [32, 32], iconAnchor: [16, 16], popupAnchor: [0, -18] })
|
||
: L.divIcon({
|
||
html: `<div style="width:14px;height:14px;border-radius:50%;background:#409EFF;border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.4);"></div>`,
|
||
className: 'sb-map__icon-wrap',
|
||
iconSize: [18, 18],
|
||
iconAnchor: [9, 9]
|
||
});
|
||
const marker = L.marker([p.lat, p.lng], { icon, title: p.name ?? '' });
|
||
if (p.popupHtml) {
|
||
marker.bindPopup(p.popupHtml, { className: 'sb-popup', maxWidth: 280, autoPan: true });
|
||
}
|
||
marker.on('click', () => emit('point-click', p));
|
||
marker.addTo(markerLayer!);
|
||
});
|
||
const list = (props.points ?? []).filter((p) => p.lng && p.lat);
|
||
if (list.length === 1 && !props.geoJson) {
|
||
map.setView([list[0].lat, list[0].lng], 15);
|
||
}
|
||
}
|
||
|
||
/** 行政区划底色 + 区划名称/统计标签 */
|
||
function renderDistricts(fitGeo = false) {
|
||
if (!map) return;
|
||
if (districtLayer) {
|
||
map.removeLayer(districtLayer);
|
||
districtLayer = null;
|
||
}
|
||
districtLabelLayer?.clearLayers();
|
||
if (!props.geoJson) return;
|
||
|
||
const active = props.highlightDistrict;
|
||
const styleOf = (name: string, hover = false) => {
|
||
if (props.boundaryOnly) {
|
||
return {
|
||
color: hover ? '#409EFF' : '#79a7e8',
|
||
weight: hover ? 2 : 1.2,
|
||
opacity: 0.9,
|
||
fillColor: '#409EFF',
|
||
fillOpacity: hover ? 0.08 : 0.03
|
||
};
|
||
}
|
||
const isActive = !!active && name === active;
|
||
return {
|
||
color: isActive ? '#64dcff' : hover ? '#9fd2ff' : '#8fa8ef',
|
||
weight: isActive ? 2.4 : hover ? 2 : 1.1,
|
||
opacity: 0.95,
|
||
fillColor: isActive ? '#16357f' : '#7486c8',
|
||
fillOpacity: isActive ? 0.55 : hover ? 0.38 : 0.2
|
||
};
|
||
};
|
||
|
||
districtLayer = L.geoJSON(props.geoJson, {
|
||
style: (feature: any) => styleOf(feature?.properties?.name ?? ''),
|
||
onEachFeature: (feature: any, layer: L.Layer) => {
|
||
const name = feature?.properties?.name ?? '';
|
||
// 悬停高亮
|
||
layer.on('mouseover', () => (layer as any).setStyle?.(styleOf(name, true)));
|
||
layer.on('mouseout', () => (layer as any).setStyle?.(styleOf(name)));
|
||
layer.on('click', () => emit('district-click', name));
|
||
// 区域选点模式只画边界,不显示名称/数量
|
||
if (props.boundaryOnly || props.hideDistrictLabels) return;
|
||
// 区划中心放名称 + 设备数,仿参考系统
|
||
const center = (layer as any).getBounds?.().getCenter?.();
|
||
if (!center || !districtLabelLayer) return;
|
||
const count = props.districtCounts?.[name] ?? 0;
|
||
const isActive = !!active && name === active;
|
||
// 区划中心点较近时做固定像素偏移,避免标签互相遮挡
|
||
const offset: Record<string, [number, number]> = {
|
||
柯城区: [0, -34],
|
||
衢江区: [0, 34],
|
||
常山县: [-38, 10],
|
||
龙游县: [38, -16]
|
||
};
|
||
const [dx, dy] = offset[name] ?? [0, 0];
|
||
const icon = L.divIcon({
|
||
className: 'sb-district-label',
|
||
html: `<div class="sb-district-card${isActive ? ' is-active' : ''}">
|
||
<span class="sb-district-card__name">${escapeHtml(name)}</span>
|
||
<span class="sb-district-card__count">${count} 台</span>
|
||
</div>`,
|
||
iconSize: [116, 32],
|
||
iconAnchor: [58 - dx, 16 - dy]
|
||
});
|
||
L.marker(center, { icon, interactive: false, pane: 'districtLabels', keyboard: false })
|
||
.addTo(districtLabelLayer);
|
||
}
|
||
}).addTo(map);
|
||
districtLayer.bringToBack();
|
||
|
||
if (fitGeo && props.fitGeo !== false) {
|
||
map.fitBounds(districtLayer.getBounds(), { padding: [36, 36], maxZoom: 10 });
|
||
}
|
||
}
|
||
|
||
function escapeHtml(value: string) {
|
||
return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||
}
|
||
|
||
watch(
|
||
() => props.points,
|
||
() => renderPoints(),
|
||
{ deep: true }
|
||
);
|
||
|
||
watch(
|
||
() => props.geoJson,
|
||
() => renderDistricts(true)
|
||
);
|
||
|
||
watch(
|
||
[() => props.districtCounts, () => props.highlightDistrict],
|
||
() => renderDistricts(false),
|
||
{ deep: true }
|
||
);
|
||
|
||
watch(
|
||
() => props.selected,
|
||
(val) => {
|
||
if (val && val.lng) {
|
||
setPickMarker(val);
|
||
} else if (pickMarker && map) {
|
||
map.removeLayer(pickMarker);
|
||
pickMarker = null;
|
||
lastValidPick = null;
|
||
}
|
||
},
|
||
{ deep: true }
|
||
);
|
||
|
||
onMounted(async () => {
|
||
await nextTick();
|
||
initMap();
|
||
renderDistricts(true);
|
||
});
|
||
|
||
onBeforeUnmount(() => {
|
||
resizeObserver?.disconnect();
|
||
resizeObserver = null;
|
||
if (map) {
|
||
map.remove();
|
||
map = null;
|
||
}
|
||
});
|
||
|
||
/** 定位到指定点(参数为 lng, lat) */
|
||
function flyTo(lng: number, lat: number, zoom = 16) {
|
||
if (!map) return;
|
||
map.setView([lat, lng], zoom);
|
||
}
|
||
|
||
/** 缩放并居中到指定行政区划 */
|
||
function fitDistrict(name: string) {
|
||
if (!map || !props.geoJson) return;
|
||
const feature = (props.geoJson.features ?? []).find(
|
||
(f: any) => f?.properties?.name === name
|
||
);
|
||
if (!feature) return;
|
||
const bounds = L.geoJSON(feature).getBounds();
|
||
if (!bounds.isValid()) return;
|
||
map.fitBounds(bounds, { padding: [48, 48], maxZoom: 12 });
|
||
}
|
||
|
||
defineExpose({ flyTo, fitDistrict });
|
||
</script>
|
||
|
||
<style>
|
||
/* 点位图标容器去默认样式(非 scoped,作用于 divIcon) */
|
||
.sb-map__icon-wrap {
|
||
background: transparent;
|
||
border: none;
|
||
}
|
||
/* 点位信息卡 */
|
||
.leaflet-popup-content-wrapper.sb-popup,
|
||
.sb-popup .leaflet-popup-content-wrapper {
|
||
border-radius: 6px;
|
||
}
|
||
.sb-popup .leaflet-popup-content {
|
||
margin: 10px 14px;
|
||
font-size: 13px;
|
||
line-height: 1.7;
|
||
}
|
||
|
||
/* 行政区划名称/统计卡(divIcon,非 scoped) */
|
||
.sb-district-label {
|
||
background: transparent;
|
||
border: none;
|
||
pointer-events: none;
|
||
}
|
||
.sb-district-card {
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
gap: 7px;
|
||
width: 108px;
|
||
height: 28px;
|
||
padding: 0 8px;
|
||
box-sizing: border-box;
|
||
color: #dce9ff;
|
||
background: linear-gradient(180deg, rgba(20, 55, 120, 0.9), rgba(9, 27, 62, 0.9));
|
||
border: 1px solid rgba(98, 170, 255, 0.55);
|
||
border-radius: 14px;
|
||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.35);
|
||
white-space: nowrap;
|
||
}
|
||
.sb-district-card.is-active {
|
||
color: #fff;
|
||
border-color: #64dcff;
|
||
background: linear-gradient(180deg, rgba(29, 74, 166, 0.96), rgba(11, 34, 86, 0.96));
|
||
box-shadow: 0 0 14px rgba(70, 180, 255, 0.35);
|
||
}
|
||
.sb-district-card__name {
|
||
font-size: 13px;
|
||
font-weight: 600;
|
||
letter-spacing: 0.5px;
|
||
}
|
||
.sb-district-card__count {
|
||
font-size: 12px;
|
||
color: #5ed8ff;
|
||
}
|
||
.sb-district-card.is-active .sb-district-card__count {
|
||
color: #8ff0ff;
|
||
}
|
||
</style>
|
||
|
||
<style scoped>
|
||
.sb-map {
|
||
width: 100%;
|
||
position: relative;
|
||
}
|
||
.sb-map__container {
|
||
width: 100%;
|
||
height: 100%;
|
||
min-height: 300px;
|
||
background: #0b1c33;
|
||
}
|
||
</style>
|