riverwaterassay.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <template>
  2. <div class="map-container">
  3. <div id="water-system-map"></div>
  4. </div>
  5. </template>
  6. <script setup>
  7. //水系图的转换
  8. import 'leaflet/dist/leaflet.css';
  9. import { onMounted, onUnmounted } from 'vue';
  10. import L from 'leaflet';
  11. let map; // 声明为全局变量,避免被Vue垃圾回收
  12. onMounted(() => {
  13. // 初始化地图容器尺寸
  14. const mapContainer = document.getElementById('water-system-map');
  15. mapContainer.style.width = '100%';
  16. mapContainer.style.height = '600px';
  17. // 初始化地图(经纬度、缩放级别可根据GeoJSON数据调整)
  18. const map = L.map('water-system-map').setView([24.88, 113.62], 9);
  19. // 加载GeoJSON
  20. fetch('/data/韶关市河流水系图.geojson')
  21. .then(res => {
  22. if (!res.ok) {
  23. throw new Error('GeoJSON加载失败');
  24. }
  25. return res.json();
  26. })
  27. .then(geojson => {
  28. // 添加水系样式(可自定义颜色、宽度)
  29. L.geoJSON(geojson, {
  30. style: {
  31. color: '#0066cc', // 蓝色线条
  32. weight: 2, // 线条宽度
  33. opacity: 0.8, // 透明度
  34. lineJoin: 'round' // 拐角圆润
  35. },
  36. // 可选:添加鼠标悬停效果
  37. onEachFeature(feature, layer) {
  38. layer.on('mouseover', function() {
  39. this.setStyle({ color: '#ff3300', weight: 3 }); // 悬停变红加粗
  40. });
  41. layer.on('mouseout', function() {
  42. this.setStyle({ color: '#0066cc', weight: 2 }); // 离开恢复
  43. });
  44. }
  45. }).addTo(map);
  46. })
  47. .catch(err => {
  48. console.error('加载GeoJSON失败:', err);
  49. alert('水系图加载失败,请检查文件路径');
  50. });
  51. // 监听窗口Resize,适配地图尺寸
  52. window.addEventListener('resize', handleResize);
  53. });
  54. onUnmounted(() => {
  55. // 组件销毁时移除事件监听,避免内存泄漏
  56. window.removeEventListener('resize', handleResize);
  57. if (map) {
  58. map.remove();
  59. map = null;
  60. }
  61. });
  62. // 窗口Resize处理函数
  63. function handleResize() {
  64. if (map) {
  65. map.invalidateSize();
  66. }
  67. }
  68. </script>
  69. <style scoped>
  70. .map-container {
  71. width: 100%;
  72. height: 600px; /* 确保父容器有高度 */
  73. }
  74. .leaflet-default-icon-path {
  75. background-image: url('https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png');
  76. }
  77. </style>