| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- <template>
- <div class="map-container">
- <div id="water-system-map"></div>
- </div>
- </template>
- <script setup>
- //水系图的转换
- import 'leaflet/dist/leaflet.css';
- import { onMounted, onUnmounted } from 'vue';
- import L from 'leaflet';
- let map; // 声明为全局变量,避免被Vue垃圾回收
- onMounted(() => {
- // 初始化地图容器尺寸
- const mapContainer = document.getElementById('water-system-map');
- mapContainer.style.width = '100%';
- mapContainer.style.height = '600px';
- // 初始化地图(经纬度、缩放级别可根据GeoJSON数据调整)
- const map = L.map('water-system-map').setView([24.88, 113.62], 9);
- // 加载GeoJSON
- fetch('/data/韶关市河流水系图.geojson')
- .then(res => {
- if (!res.ok) {
- throw new Error('GeoJSON加载失败');
- }
- return res.json();
- })
- .then(geojson => {
- // 添加水系样式(可自定义颜色、宽度)
- L.geoJSON(geojson, {
- style: {
- color: '#0066cc', // 蓝色线条
- weight: 2, // 线条宽度
- opacity: 0.8, // 透明度
- lineJoin: 'round' // 拐角圆润
- },
- // 可选:添加鼠标悬停效果
- onEachFeature(feature, layer) {
- layer.on('mouseover', function() {
- this.setStyle({ color: '#ff3300', weight: 3 }); // 悬停变红加粗
- });
- layer.on('mouseout', function() {
- this.setStyle({ color: '#0066cc', weight: 2 }); // 离开恢复
- });
- }
- }).addTo(map);
- })
- .catch(err => {
- console.error('加载GeoJSON失败:', err);
- alert('水系图加载失败,请检查文件路径');
- });
- // 监听窗口Resize,适配地图尺寸
- window.addEventListener('resize', handleResize);
- });
- onUnmounted(() => {
- // 组件销毁时移除事件监听,避免内存泄漏
- window.removeEventListener('resize', handleResize);
- if (map) {
- map.remove();
- map = null;
- }
- });
- // 窗口Resize处理函数
- function handleResize() {
- if (map) {
- map.invalidateSize();
- }
- }
- </script>
- <style scoped>
- .map-container {
- width: 100%;
- height: 600px; /* 确保父容器有高度 */
- }
- .leaflet-default-icon-path {
- background-image: url('https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png');
- }
- </style>
|