利用Leaflet.js创建交互式地图:添加Popup

        在现代Web开发中,交互式地图已成为展示地理位置数据的强大工具。Leaflet.js是一个开源的JavaScript库,它提供了一个简单易用的界面来创建这样的地图。在本文中,我们将探讨如何使用Leaflet.js创建一个交互式地图,并添加Popup来显示额外的信息。

概述

        Leaflet.js允许开发者通过简单的API来添加各种地图层和控件。Popup是Leaflet.js中一个非常实用的功能,它可以在地图上的特定位置显示额外的信息。这在需要向用户展示地点详细信息时非常有用,比如地点的描述、图片或其他数据。

实现步骤

1. 初始化地图

首先,我们需要创建一个基础地图实例。这通常涉及到设置地图的初始视图和缩放级别。

var map = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,
    attribution: '© OpenStreetMap contributors'
}).addTo(map);

2. 定义多边形数据

        在本例中,我们假设已经有了一个包含多边形数据的数组。

data() {
  return {
    drawnItems: null,
    map: null,
    polygonsData:[],
    detailForm: {},
  };
},

3. 渲染多边形和Popup

        接下来,我们将遍历数据数组,为每个多边形创建一个Leaflet多边形对象,并为其添加Popup。

methods: {
  renderPolygons() {
    console.log("加载多边形", this.polygonsData);
    this.drawnItems.clearLayers(); // 清空之前的图层
    this.polygonsData.forEach((item, index) => {
      // 确保coord不是null
      const polygonCoords = item.polygonsDataItem.map((coord, coordIndex) => {
        if (!coord || typeof coord.lat === "undefined" || typeof coord.lng === "undefined") {
          console.error(`无效的坐标点在索引 ${index}, 坐标点索引 ${coordIndex}:`, coord);
          return null;
        }
        return L.latLng(coord.lat, coord.lng);
      });
      // 过滤掉null的坐标点
      const validCoords = polygonCoords.filter((coord) => coord !== null);
      // 根据onStatus获取对应的样式
      const polygonStyle = this.getPolygonStyleByStatus(item.onStatus);
      const polygon = L.polygon(validCoords, polygonStyle);
      // 计算多边形的中心点
      const center = polygon.getBounds().getCenter();
      // 创建Popup内容
      const popupContent = `
        <div class="content">
          <div class="item">泊位编号:${item.berthNo}</div>
          <div class="item">泊位类型:${item.berthType}</div>
          <div class="item">泊位长度:${item.berthLength ? item.berthLength : '-'}米</div>
          <div class="item">泊位宽度:${item.berthWidth ? item.berthWidth : '-'}米</div>
          <div class="item">泊位水深:${item.berthDepth ? item.berthDepth : '-'}米</div>
          <div class="item">泊位状态:${item.onStatus}</div>
          <div class="btn" id="berthUsageBtn">泊位使用情况</div>
        </div>
      `;
      // 创建Popup
      const popup = L.popup({
        closeButton: false,
        autoClose: true,
        closeOnClick: true,
        className: 'my-custom-popup'
      }).setContent(popupContent);
      // 绑定Popup事件
      this.bindPopupEvents(polygon, item);
      // 绑定Popup到多边形
      polygon.bindPopup(popup);
      this.drawnItems.addLayer(polygon);
    });
  },
  // 触发点击事件
  bindPopupEvents(layer, item) {
    layer.on("popupopen", function (e) {
      const popup = e.popup;
      const container = popup._container;
      const berthUsageBtn = container.querySelector('#berthUsageBtn');
      if (berthUsageBtn) {
        berthUsageBtn.onclick = function () {
          console.log('点击了', item);
          this.detailForm = item;
        }.bind(this);
      }
    }.bind(this));
    layer.on("popupclose", function (e) {
      const popup = e.popup;
      const container = popup._container;
      const berthUsageBtn = container.querySelector('#berthUsageBtn');
      if (berthUsageBtn) {
        berthUsageBtn.onclick = null;
      }
    });
  }
}

4. 自定义Popup样式

为了使Popup更加美观,我们可以通过CSS来自定义其样式。

::v-deep .leaflet-popup-content {
  width: 200px;
  padding: 24px 10px;
  box-sizing: border-box;
  margin: 0;
}
::v-deep .leaflet-popup-tip {
  background: #2F4C79;
}
::v-deep .leaflet-popup-content-wrapper {
  background: #2F4C79;
  box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.12);
  .content {
    display: flex;
    flex-direction: column;
    font-weight: 500;
    font-size: 16px;
    .item {
      color: #FFFFFF;
      margin-bottom: 10px;
    }
    .btn {
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      width: 100%;
      color: #EBF2FF;
      line-height: 16px;
      text-align: left;
      font-style: normal;
      text-decoration-line: underline;
    }
  }
}

结论

        通过上述步骤,我们成功地在Leaflet.js地图上添加了交互式的多边形和Popup。这种方法不仅提高了地图的交互性,还增强了用户体验。Leaflet.js的强大功能和灵活性使其成为创建交互式地图的理想选择。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值