leaflet和leaflet.pm的使用

本文详细介绍如何使用Leaflet创建具备缩放与图层切换功能的地图,并通过leaflet.pm增强交互体验,包括绘制图形、编辑功能及事件监听。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.安装

npm install leaflet

2.引入

import L from 'leaflet';
import 'leaflet/dist/leaflet.css';

3.初始化地图

 map = L.map("mapDiv", {
            crs: L.CRS.EPSG4326,  // 要使用的坐标参考系
            center: [29.84, 121.61],  // 地图的初始地理中心
            zoom: 12,  // 初始地图缩放级别
            layers: [imgMap],  // 最初将添加到地图的图层数组
            zoomControl: false,  // 缩放控件是否显示 
            attributionControl: false,  // 右下角的leaflet标志是否显示
 });

4.设置缩放按钮和切换图层按钮

 L.control.layers(baseLayers, overlayLayers).addTo(map);
 L.control.zoom({
     zoomInTitle: '放大',
     zoomOutTitle: '缩小'
  }).addTo(map);


const normalMapm = L.tileLayer('http://t3.tianditu.com/vec_c/wmts?layer=vec&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=e2b00ec180ba4f7ff1fdb526cd082b4e', {
        maxZoom: 16,
        minZoom: 5,
        zoomOffset: 1
    })
    const normalMapa = L.tileLayer('http://t0.tianditu.gov.cn/cva_c/wmts?layer=cva&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=e2b00ec180ba4f7ff1fdb526cd082b4e', {
        maxZoom: 16,
        minZoom: 5,
        zoomOffset: 1
    })
    const imgMapm = L.tileLayer('http://t0.tianditu.gov.cn/img_c/wmts?layer=img&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=e2b00ec180ba4f7ff1fdb526cd082b4e', {
        maxZoom: 16,
        minZoom: 5,
        zoomOffset: 1
    })
    const imgMapa = L.tileLayer('http://t0.tianditu.gov.cn/cia_c/wmts?layer=cia&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=e2b00ec180ba4f7ff1fdb526cd082b4e', {
        maxZoom: 16,
        minZoom: 5,
        zoomOffset: 1
    })

    const normalMap = L.layerGroup([normalMapm, normalMapa]), imgMap = L.layerGroup([imgMapm, imgMapa]);
    const baseLayers = { "行政": normalMap, "卫星": imgMap };
    const overlayLayers = {}

5.设置定位的图片

delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
       iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
       iconUrl: require('leaflet/dist/images/marker-icon.png'),
       shadowUrl: require('leaflet/dist/images/marker-shadow.png'),
       iconSize: [70, 70],
       shadowSize: [50, 64],
       iconAnchor: [40, 54],
       shadowAnchor: [4, 62],
       popupAnchor: [-3, -76]
});

6.绘制图层 

 L.marker(res).addTo(map)

 L.polygon(res, { color: 'rgb(51, 136, 255)', fillColor: 'rgb(51, 136, 255)',fillOpacity:0.2, weight: 3 }).addTo(map);

 L.polyline(res, { color: 'rgb(51, 136, 255)', fillColor: 'rgb(51, 136, 255)', fill: true }).addTo(map);

L.circle([res.lat, res.lng], { color: 'rgb(51, 136, 255)', fillColor: 'rgba(51, 136, 255,.2)', radius: res.raduis, fillOpacity: 1 }).addTo(map)

  // color:线段颜色
  // weight:线段宽度
  // opacity:线段透明度
  // dashArray:虚线间隔
  // fill:是否填充内部(true/false)
  // fillColor:内部填充颜色,如不设置,默认为color颜色
  // fillOpacity:内部填充透明度

至此一个具有缩放按钮和切换地图图层的页面出来了,下面将使用leaflet.pm来为地图添加工具条控件。

1.安装 

npm install leaflet.pm

2.引入

import "leaflet.pm";
import "leaflet.pm/dist/leaflet.pm.css";

3.设置中文和控件

  map.pm.setLang('zh');
  map.pm.addControls({
         position: "topleft",
         drawPolygon: true, // 绘制多边形
         drawMarker: true, //绘制标记点
         drawCircleMarker: false, //绘制圆形标记
         drawPolyline: false, //绘制线条
         drawRectangle: true,	//绘制矩形
         drawCircle: true, //绘制圆圈
         editMode: false, //编辑多边形
         dragMode: false, //拖动多边形
         cutPolygon: false, // 添加一个按钮以删除多边形里面的部分内容
         removalMode: true  // 清除多边形
  });

 // 设置绘制后的线条颜色等
 map.pm.setPathOptions({
     color: "orange",
     illColor: "green",
     fillOpacity: 0.4
  });

4.事件

 map.on("pm:drawstart", e => {
         console.log(e, "点击控件绘制时调用");
 });
 map.on("pm:drawend", e => {
         console.log(e, "禁止绘制");
 });
 map.on("pm:create", e => {
         console.log(e, "绘制完成时调用");
  });
 map.on('pm:globalremovalmodetoggled', e => {
            console.log(e, "清除图层时调用");
 })

### 解决 Leaflet.pm 报错问题 当遇到与 Leaflet.pm 插件有关的错误时,可以采取多种方法来排查并解决问题。以下是几种常见的解决方案: #### 1. 检查依赖项加载顺序 确保所有的 JavaScript 文件按照正确的顺序加载。通常情况下,应该先加载 Leaflet 库,再加载 Leaflet.pm 插件文件[^2]。 ```html <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script> <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css"/> <!-- 加载其他必要的 CSS JS --> <script src="path/to/leaflet.pm.min.js"></script> ``` #### 2. 初始化配置选项 确认初始化过程中传递给 `L.Map` 的参数是否正确设置了支持编辑的功能。如果启用了绘图功能,则需要指定相应的工具栏按钮其他交互控件。 ```javascript var map = L.map('map', { center: [50.5, 30.5], zoom: 13, editableLayers: new L.FeatureGroup(), // 创建可编辑图层组 }); ``` #### 3. 处理特定类型的 GeoJSON 数据 对于某些复杂的几何对象,在将其转换为 Leaflet 图层之前可能需要额外处理。例如,缓冲区(Buffer)操作可能会导致不兼容的数据结构被传入到 `L.GeoJSON()` 构造函数中[^1]。 ```javascript // 对原始数据进行预处理后再创建GeoJson Layer function preprocessData(data){ let processedFeatures = data.features.map(feature => ({ ...feature, geometry: simplifyGeometry(feature.geometry), // 假设有一个简化几何体的方法 })); return {...data, features:processedFeatures}; } const preprocessedBuffered = preprocessData(buffered); var bufferLayer = L.geoJSON(preprocessedBuffered ,{ pmIgnore: true, }).addTo(map); ``` #### 4. 更新至最新版本 有时旧版插件可能存在已知缺陷或与其他库存在冲突的情况。建议定期查看官方文档 GitHub 上是否有新的发布版本可用,并及时升级以获得更好的稳定性性能表现。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我是来写bug的吧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值