Leaflet-学习

一、官网

英文官网:Leaflet

中文官网:Leaflet

二、介绍

Leaflet 是一个开源并且对移动端友好的交互式地图 JavaScript 库。 它大小仅仅只有39 KB, 并且拥有绝大部分开发者所需要的所有地图特性。

Leaflet 简单、高效并且易用。 它可以高效的运行在桌面和移动平台, 拥有着大量的扩展插件、 优秀的文档、简单易用的API 和完善的案例, 以及可读性较好的 源码 。

三、下载Leaflet

【1】CDN

// html头部引入
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>

// 为避免潜在的安全问题,建议在使用CDN中的Leaflet时启用subresource integrity
 <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
 <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"  integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>

【2】下载到本地

版本说明
Leaflet 1.7.1稳定版,于2020年9月3日发布。
Leaflet 1.8-dev开发版,在master分支上开发。
Leaflet 0.7.7旧版,于2013年11月18日发布,最新更新于2015年10月26日。

在从上述链接下载文件到本地,将下载的文件解压到项目目录中,并将其添加到HTML代码的开头

<link rel="stylesheet" href="/leftlet/leaflet.css" />
<script src="/leftlet/leaflet.js"></script>

【3】npm

npm install leaflet

四、简单入门教程(开始使用leafLet)

【1】案例

在 id 为map的 div 中创建一个地图, 选择瓦片数据源, 添加一个标记点并且在弹出层上显示文本

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title></title>

  <!--leaflet样式文件-->
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
  <!--leaflet核心JS文件-->
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>

  <style>
    /*必须指定宽高度*/
    #map {
      width: 800px;
      height: 500px;
    }
  </style>
</head>

<body>
  <div id="map">
  </div>

  <script>
    // 创建一个地图
    var map = L.map("map", {
      center: [23.127013, 113.366266],
      zoom: 8
    });

    // 选择瓦片数据源
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

    // 添加一个标记点并且在弹出层上显示文本
    L.marker([23.127013, 113.366266]).addTo(map).bindPopup('我在这里').openPopup();
  </script>

</body>
</html>

【2】效果

五、瓦片地图介绍

其实瓦片地图并不是什么特殊的文件,就是最普通的png图片。之所以为地图,就是带有了地理坐标。打开network,查看其请求的的url就能明白其请求的原理了。我们上面看到的地图是由一张张带有地理坐标的图片拼接起来的

 首先我们要明白瓦片地图的请求原理。上面其中一个图片的URL为:https://a.tile.openstreetmap.org/8/209/112.png

主要在于最后三位,含义依次是8级的209行、112列(或者209列、112行)。8就是下图中的level(地图放大缩小层级),而行列号对应每一级level里面的唯一一个瓦片(图片),那么地图框架为我们完成的就是,在对应地图层级,请求对应范围内的瓦片,而这个协议规则一般是通用的谷歌标准(也有其他标准,看框架是否支持),比如第9级中的第一个不会叫9-0-0,而可能是9-1-1(真实可能不是)

 六、 Leaflet加载各种地图  

 Leaflet调用各种地图的功能十分复杂,幸好有leaflet.ChineseTmsProviders 这个插件,此插件源代码如下,你可以直接复制下面代码创建为js文件(可命名为leaflet.ChineseTmsProviders.js),然后引入你的HTML页面便可使用

// this L.CRS.Baidu from https://github.com/muyao1987/leaflet-tileLayer-baidugaode/blob/master/src/tileLayer.baidu.js

if (L.Proj) {
    L.CRS.Baidu = new L.Proj.CRS('EPSG:900913', '+proj=merc +a=6378206 +b=6356584.314245179 +lat_ts=0.0 +lon_0=0.0 +x_0=0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs', {
        resolutions: function () {
            var level = 19
            var res = [];
            res[0] = Math.pow(2, 18);
            for (var i = 1; i < level; i++) {
                res[i] = Math.pow(2, (18 - i))
            }
            return res;
        }(),
        origin: [0, 0],
        bounds: L.bounds([20037508.342789244, 0], [0, 20037508.342789244])
    });
}

L.TileLayer.ChinaProvider = L.TileLayer.extend({

    initialize: function(type, options) { // (type, Object)
        var providers = L.TileLayer.ChinaProvider.providers;

        options = options || {}

        var parts = type.split('.');

        var providerName = parts[0];
        var mapName = parts[1];
        var mapType = parts[2];

        var url = providers[providerName][mapName][mapType];
        options.subdomains = providers[providerName].Subdomains;
        options.key = options.key || providers[providerName].key;

        if ('tms' in providers[providerName]) {
            options.tms = providers[providerName]['tms']
        }

        L.TileLayer.prototype.initialize.call(this, url, options);
    }
});

L.TileLayer.ChinaProvider.providers = {
    TianDiTu: {
        Normal: {
            Map: "http://t{s}.tianditu.gov.cn/DataServer?T=vec_w&X={x}&Y={y}&L={z}&tk={key}",
            Annotion: "http://t{s}.tianditu.gov.cn/DataServer?T=cva_w&X={x}&Y={y}&L={z}&tk={key}"
        },
        Satellite: {
            Map: "http://t{s}.tianditu.gov.cn/DataServer?T=img_w&X={x}&Y={y}&L={z}&tk={key}",
            Annotion: "http://t{s}.tianditu.gov.cn/DataServer?T=cia_w&X={x}&Y={y}&L={z}&tk={key}"
        },
        Terrain: {
            Map: "http://t{s}.tianditu.gov.cn/DataServer?T=ter_w&X={x}&Y={y}&L={z}&tk={key}",
            Annotion: "http://t{s}.tianditu.gov.cn/DataServer?T=cta_w&X={x}&Y={y}&L={z}&tk={key}"
        },
        Subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
        key: "174705aebfe31b79b3587279e211cb9a"
    },

    GaoDe: {
        Normal: {
            Map: 'http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}'
        },
        Satellite: {
            Map: 'http://webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
            Annotion: 'http://webst0{s}.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}'
        },
        Subdomains: ["1", "2", "3", "4"]
    },

    Google: {
        Normal: {
            Map: "http://www.google.cn/maps/vt?lyrs=m@189&gl=cn&x={x}&y={y}&z={z}"
        },
        Satellite: {
            Map: "http://www.google.cn/maps/vt?lyrs=s@189&gl=cn&x={x}&y={y}&z={z}",
            Annotion: "http://www.google.cn/maps/vt?lyrs=y@189&gl=cn&x={x}&y={y}&z={z}"
        },
        Subdomains: []
    },

    Geoq: {
        Normal: {
            Map: "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer/tile/{z}/{y}/{x}",
            PurplishBlue: "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}",
            Gray: "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetGray/MapServer/tile/{z}/{y}/{x}",
            Warm: "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetWarm/MapServer/tile/{z}/{y}/{x}",
        },
        Theme: {
            Hydro: "http://thematic.geoq.cn/arcgis/rest/services/ThematicMaps/WorldHydroMap/MapServer/tile/{z}/{y}/{x}"
        },
        Subdomains: []
    },

    OSM: {
        Normal: {
            Map: "http://{s}.tile.osm.org/{z}/{x}/{y}.png",
        },
        Subdomains: ['a', 'b', 'c']
    },

    Baidu: {
        Normal: {
            Map: 'http://online{s}.map.bdimg.com/onlinelabel/?qt=tile&x={x}&y={y}&z={z}&styles=pl&scaler=1&p=1'
        },
        Satellite: {
            Map: 'http://shangetu{s}.map.bdimg.com/it/u=x={x};y={y};z={z};v=009;type=sate&fm=46',
            Annotion: 'http://online{s}.map.bdimg.com/tile/?qt=tile&x={x}&y={y}&z={z}&styles=sl&v=020'
        },
        Subdomains: '0123456789',
        tms: true
    }

};

L.tileLayer.chinaProvider = function(type, options) {
    return new L.TileLayer.ChinaProvider(type, options);
};

在HTML页面中引入leaflet.ChineseTmsProviders.js,加载多种瓦片地图

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title></title>

  <!--leaflet样式文件-->
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
  <!--leaflet核心JS文件-->
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
  <!-- 引入 ChineseTmsProviders.js文件-->
  <script src="./leaflet/leaflet.ChineseTmsProviders.js"></script>

  <style>
    /*必须指定宽高度*/
    #map {
      width: 800px;
      height: 500px;
    }
  </style>
</head>

<body>
  <div id="map"></div>
  <script>
    // 天地图内容
    var TianDinormalm = L.tileLayer.chinaProvider('TianDiTu.Normal.Map', {
      maxZoom: 18,
      minZoom: 5
    });
    var TianDinormala = L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion', {
      maxZoom: 18,
      minZoom: 5
    });
    var TianDiimgm = L.tileLayer.chinaProvider('TianDiTu.Satellite.Map', {
      maxZoom: 18,
      minZoom: 5
    });
    var TianDiimga = L.tileLayer.chinaProvider('TianDiTu.Satellite.Annotion', {
      maxZoom: 18,
      minZoom: 5
    });

    var TianDi = L.layerGroup([TianDinormalm, TianDinormala]);
    var TianDiImage = L.layerGroup([TianDiimgm, TianDiimga]);


    // 高德地图
    var Gaode = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
      maxZoom: 18,
      minZoom: 5
    });
    var Gaodeimgem = L.tileLayer.chinaProvider('GaoDe.Satellite.Map', {
      maxZoom: 18,
      minZoom: 5
    });
    var Gaodeimga = L.tileLayer.chinaProvider('GaoDe.Satellite.Annotion', {
      maxZoom: 18,
      minZoom: 5
    });
    var GaodeImage = L.layerGroup([Gaodeimgem, Gaodeimga]);


    // 谷歌地图
    var Google = L.tileLayer.chinaProvider('Google.Normal.Map', {
      maxZoom: 18,
      minZoom: 5
    })
    var Googleimgem = L.tileLayer.chinaProvider('Google.Satellite.Map', {
      maxZoom: 18,
      minZoom: 5
    });
    var Googleimga = L.tileLayer.chinaProvider('Google.Satellite.Annotion', {
      maxZoom: 18,
      minZoom: 5
    });
    var GoogleImage = L.layerGroup([Googleimgem, Googleimga]);


    // OSM地图
    var OSM = L.tileLayer.chinaProvider('OSM.Normal.Map', {
      maxZoom: 18,
      minZoom: 5
    });


    // 百度地图
    var Baidu = L.tileLayer.chinaProvider('Baidu.Normal.Map', {
      maxZoom: 18,
      minZoom: 5
    });
    var Baiduimgem = L.tileLayer.chinaProvider('Baidu.Satellite.Map', {
      maxZoom: 18,
      minZoom: 5
    });
    var Baiduimga = L.tileLayer.chinaProvider('Baidu.Satellite.Annotion', {
      maxZoom: 18,
      minZoom: 5
    });
    var BaiduImage = L.layerGroup([Baiduimgem, Baiduimga]);


    // 智图地图
    var normalm1 = L.tileLayer.chinaProvider('Geoq.Normal.Map', {
      maxZoom: 18,
      minZoom: 5
    });
    var normalm2 = L.tileLayer.chinaProvider('Geoq.Normal.Color', {
      maxZoom: 18,
      minZoom: 5
    });
    var normalm3 = L.tileLayer.chinaProvider('Geoq.Normal.PurplishBlue', {
      maxZoom: 18,
      minZoom: 5
    });
    var normalm4 = L.tileLayer.chinaProvider('Geoq.Normal.Gray', {
      maxZoom: 18,
      minZoom: 5
    });
    var normalm5 = L.tileLayer.chinaProvider('Geoq.Normal.Warm', {
      maxZoom: 18,
      minZoom: 5
    });
    var normalm6 = L.tileLayer.chinaProvider('Geoq.Normal.Cold', {
      maxZoom: 18,
      minZoom: 5
    });


    var baseLayers = {
      "天地图": TianDi,
      "天地图影像": TianDiImage,

      "高德地图": Gaode,
      "高德影像": GaodeImage,

      "谷歌地图": Google,
      "谷歌影像": GoogleImage,

      "OSM地图": OSM,

      "百度地图": Baidu,
      "百度影像": BaiduImage,


      "智图地图": normalm1,
      "智图多彩": normalm2,
      "智图午夜蓝": normalm3,
      "智图灰色": normalm4,
      "智图暖色": normalm5,
      "智图冷色": normalm6,

    }

    var map = L.map("map", {
      center: [23.127013, 113.366266],
      zoom: 8,
      layers: [Gaode], // 选择baseLayers的地图
      zoomControl: false,
      key: 'Your key', // 如果你使用天地图,请添加密钥key
    });

    L.control.layers(baseLayers, null).addTo(map);
    L.control.zoom({
      zoomInTitle: '放大',
      zoomOutTitle: '缩小'
    }).addTo(map);
  </script>

</body>

</html>

 七、Leaflet地图小案例

【1】地图事件

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title></title>

  <!--leaflet样式文件-->
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
  <!--leaflet核心JS文件-->
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
  <!-- 引入 ChineseTmsProviders.js文件-->
  <script src="./leaflet/leaflet.ChineseTmsProviders.js"></script>

  <style>
    /*必须指定宽高度*/
    #map {
      width: 800px;
      height: 500px;
    }
  </style>
</head>

<body>
  <div id="map"></div>
  <script>
    // 高德地图
    var Gaode = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
      maxZoom: 18,
      minZoom: 5
    });

    var map = L.map("map", {
      center: [23.127013, 113.366266],
      zoom: 8,
      layers: [Gaode],
      zoomControl: false,
    });

    //地图加载完成
    map.once("loadEnd", function () {
      console.log("地图加载完成");
    });

    //地图点击
    map.on("click", function (e) {
      console.log("你在地图" + e.latlng + "点击了");
    });

    //地图双击
    map.on("dblclick", function (e) {
      console.log("你在地图上双击了!");
    });

    //地图移动
    map.on("move", function (e) {
      console.log("地图移动了");
    });

    //地图层级改变
    map.on("zoom", function (e) {
      console.log("地图层级改变了");
    });
  </script>

</body>

</html>

【2】 中心点和层级显示

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title></title>

  <!--leaflet样式文件-->
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
  <!--leaflet核心JS文件-->
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
  <!-- 引入 ChineseTmsProviders.js文件-->
  <script src="./leaflet/leaflet.ChineseTmsProviders.js"></script>

  <style>
    /*必须指定宽高度*/
    #map {
      width: 800px;
      height: 500px;
    }

    .info {
      padding: 10px;
      background-color: #fff;
      border-radius: 4px;

    }
  </style>
</head>

<body>
  <div id="map"></div>
  <script>
    // 高德地图
    var Gaode = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
      maxZoom: 18,
      minZoom: 5
    });

    var map = L.map("map", {
      center: [23.127013, 113.366266],
      zoom: 8,
      layers: [Gaode],
      zoomControl: true,
    });

    // 设置地图中心点与缩放级别
    map.setView([23.165103, 113.405802], 15);

    // 自定义info控件
    var info = L.control();
    info.onAdd = function (map) {
      this.infoDiv = L.DomUtil.create("div", "info"); // 创建一个class为info的div
      this.update(map.getZoom(), map.getCenter()); // map.getZoom()获取地图当前层级  map.getCenter()获取地图当前中心点
      return this.infoDiv;
    };

    //根据当前地图状态更新显示信息
    info.update = function (zoom, center) {
      this.infoDiv.innerHTML =
        "<b>当前地图状态</b><br/>" +
        "<b>zoom: </b>" + zoom + "<br/>" +
        "<b>center: </b>" + center + "";
    };
    info.addTo(map);

    //监听地图状态变化
    map.on("move", moveMap);
    function moveMap(e) {
      info.update(map.getZoom(), map.getCenter());
    }
  </script>

</body>

</html>

 【3】 获取和设置地图可视范围

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title></title>

  <!--leaflet样式文件-->
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
  <!--leaflet核心JS文件-->
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
  <!-- 引入 ChineseTmsProviders.js文件-->
  <script src="./leaflet/leaflet.ChineseTmsProviders.js"></script>

  <style>
    /*必须指定宽高度*/
    #map {
      width: 800px;
      height: 500px;
    }

    .info {
      padding: 10px;
      background-color: #fff;
      border-radius: 4px;

    }
  </style>
</head>

<body>
  <div id="map"></div>
  <script>
    // 高德地图
    var Gaode = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
      maxZoom: 18,
      minZoom: 5
    });

    var map = L.map("map", {
      center: [23.127013, 113.366266],
      zoom: 8,
      layers: [Gaode],
      zoomControl: true,
    });

    // 设置地图当前显示范围有两种方法:一是用fitBounds(bounds),二是flyToBounds(bounds),
    // 区别在于后者有飞行动画效果,前者没有;
    // 其中bounds参数可以上一个LatLngBounds对象,也可以是一个包含矩形对角点的数组。


    // LatLngBounds对象
    var corner1 = L.latLng(30, 106);
    var corner2 = L.latLng(28.9, 105.51);
    var bounds = L.latLngBounds(corner1, corner2);

    // 第一种 fitBounds(bounds) 没有飞行效果
    //map.fitBounds(bounds)

    // 第二种 flyToBounds(bounds)有飞行效果
    map.flyToBounds(bounds);

    // 包含矩形对角点的数组
    // map.fitBounds([
    //   [30, 106],
    //   [28.9, 105.51]
    // ]);


    // 自定义info控件
    var info = L.control();
    info.onAdd = function (map) {
      this.infoDiv = L.DomUtil.create("div", "info"); // 创建一个class为info的div
      this.update(map.getBounds()); // map.getBounds()获取地图可视范围
      return this.infoDiv;
    };

    //根据当前地图状态更新显示信息
    info.update = function (bounds) {
      this.infoDiv.innerHTML =
        "<b>当前地图显示范围</b><br/>" +
        "<b>右上角: </b>" + bounds.getNorthEast() + "<br/>" +
        "<b>左下角: </b>" + bounds.getSouthWest() + "";
    };
    info.addTo(map);

    //监听地图状态变化
    map.on("move", moveMap);
    function moveMap(e) {
      info.update(map.getBounds());
    }
  </script>

</body>

</html>

【4】 mark的使用

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title></title>

  <!--leaflet样式文件-->
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
  <!--leaflet核心JS文件-->
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
  <!-- 引入 ChineseTmsProviders.js文件-->
  <script src="./leaflet/leaflet.ChineseTmsProviders.js"></script>

  <style>
    /*必须指定宽高度*/
    #map {
      width: 800px;
      height: 500px;
    }
  </style>
</head>

<body>
  <div id="map"></div>
  <script>
    // 高德地图
    var Gaode = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
      maxZoom: 18,
      minZoom: 5
    });

    var map = L.map("map", {
      center: [23.127013, 113.366266],
      zoom: 8,
      layers: [Gaode],
      zoomControl: true,
    });

    // 添加marker
    marker = L.marker([23.127013, 113.366266], {
      draggable: true,
      autoPan: false
    });

    // marker添加到地图上
    marker.addTo(map);

    // marker绑定气泡
    marker.bindPopup("我是一个图标");

    // marker绑定事件,当拖动完成时触发
    marker.on('dragend', function () {
      console.log('图标移动完成');
    });
  </script>

</body>

</html>

【5】 mark自定义icon图片

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title></title>

  <!--leaflet样式文件-->
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
  <!--leaflet核心JS文件-->
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
  <!-- 引入 ChineseTmsProviders.js文件-->
  <script src="./leaflet/leaflet.ChineseTmsProviders.js"></script>

  <style>
    /*必须指定宽高度*/
    #map {
      width: 800px;
      height: 500px;
    }
  </style>
</head>

<body>
  <div id="map"></div>
  <script>
    // 高德地图
    var Gaode = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
      maxZoom: 18,
      minZoom: 5
    });

    var map = L.map("map", {
      center: [23.127013, 113.366266],
      zoom: 8,
      layers: [Gaode],
      zoomControl: true,
    });

    // 自定义图标
    var customIcon = L.icon({
      iconUrl: './images/like.svg',
      iconSize: [55, 55]
    });

    // 添加marker,并设置图标
    marker = L.marker([23.167561, 113.400282], {
      draggable: true,
      autoPan: false,
      icon: customIcon
    }).addTo(map);

    // marker绑定气泡
    marker.bindPopup("我是一个图标");

    // marker绑定事件,当拖动完成时触发
    marker.on('dragend', function () {
      console.log('图标移动完成');
    });
  </script>

</body>

</html>

 【6】tooltip的使用

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title></title>

  <!--leaflet样式文件-->
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
  <!--leaflet核心JS文件-->
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
  <!-- 引入 ChineseTmsProviders.js文件-->
  <script src="./leaflet/leaflet.ChineseTmsProviders.js"></script>

  <style>
    /*必须指定宽高度*/
    #map {
      width: 800px;
      height: 500px;
    }
  </style>
</head>

<body>
  <div id="map"></div>
  <script>
    // 高德地图
    var Gaode = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
      maxZoom: 18,
      minZoom: 5
    });

    var map = L.map("map", {
      center: [23.127013, 113.366266],
      zoom: 8,
      layers: [Gaode],
      zoomControl: true,
    });

    // 添加marker
    marker = L.marker([23.127013, 113.366266], {
      draggable: true,
      autoPan: false,
    }).addTo(map);

    // tooltip与marker绑定
    var t = marker.bindTooltip("my tooltip text").openTooltip();

    // 实现动态修改内容
    t.setTooltipContent('<p>动态修改与mark绑定的ToolTip~ </p>')

    // 实现单独叠加
    L.tooltip().setLatLng([23.129013, 114.366266]).setContent('<p>单独叠加的ToolTip</p>').addTo(map);
  </script>

</body>

</html>

 【7】popup的使用

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title></title>

  <!--leaflet样式文件-->
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
  <!--leaflet核心JS文件-->
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
  <!-- 引入 ChineseTmsProviders.js文件-->
  <script src="./leaflet/leaflet.ChineseTmsProviders.js"></script>

  <style>
    /*必须指定宽高度*/
    #map {
      width: 800px;
      height: 500px;
    }
  </style>
</head>

<body>
  <div id="map"></div>
  <script>
    // 高德地图
    var Gaode = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
      maxZoom: 18,
      minZoom: 5
    });

    var map = L.map("map", {
      center: [23.127013, 113.366266],
      zoom: 8,
      layers: [Gaode],
      zoomControl: true,
    });

    // 添加marker
    marker = L.marker([23.127013, 113.366266], {
      draggable: true,
      autoPan: false,
    }).addTo(map);

    // popup与marker绑定
    var t = marker.bindPopup("my popup text")

    // 实现动态修改内容
    t.setPopupContent('<p>动态修改与mark绑定的popup~ </p>')

    // 实现单独叠加
    L.popup().setLatLng([23.129013, 114.366266]).setContent('<p>单独叠加的popup</p>').openOn(map);
  </script>

</body>

</html>

【8】 线的显示

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title></title>

  <!--leaflet样式文件-->
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
  <!--leaflet核心JS文件-->
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
  <!-- 引入 ChineseTmsProviders.js文件-->
  <script src="./leaflet/leaflet.ChineseTmsProviders.js"></script>

  <style>
    /*必须指定宽高度*/
    #map {
      width: 800px;
      height: 500px;
    }
  </style>
</head>

<body>
  <div id="map"></div>
  <script>
    // 高德地图
    var Gaode = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
      maxZoom: 18,
      minZoom: 5
    });

    var map = L.map("map", {
      center: [23.127013, 113.366266],
      zoom: 8,
      layers: [Gaode],
      zoomControl: true,
    });

    // 从一组坐标点创建红色的线
    var latlngs = [
      [45.51, -122.68],
      [37.77, -122.43],
      [34.04, -118.2]
    ];
    var polyline = L.polyline(latlngs, {
      color: 'red',
      weight: 8,
      dashArray: "5,10,20"
    }).addTo(map);

    // click操作
    polyline.on('click', function () {
      console.log('点了线一下')
    });

    // 地图显示区域为红线所在位置
    map.flyToBounds(polyline.getBounds());
  </script>

</body>

</html>

 【9】 缩放组件和自定义缩放组件

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title></title>

  <!--leaflet样式文件-->
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
  <!--leaflet核心JS文件-->
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
  <!-- 引入 ChineseTmsProviders.js文件-->
  <script src="./leaflet/leaflet.ChineseTmsProviders.js"></script>

  <style>
    /*必须指定宽高度*/
    #map {
      width: 800px;
      height: 500px;
    }
  </style>
</head>

<body>
  <div id="map"></div>
  <script>
    // 高德地图
    var Gaode = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
      maxZoom: 18,
      minZoom: 5
    });

    var map = L.map("map", {
      center: [23.127013, 113.366266],
      zoom: 8,
      layers: [Gaode],
      zoomControl: false,
    });

    //创建内置缩放组件,将其置于地图的右上角
    L.control.zoom({
      zoomInText: "🌼",
      zoomOutText: "🌍",
      position: "topright"
    }).addTo(map);



    //自定义缩放按钮
    var customZoom = L.control();
    customZoom.onAdd = function (map) {
      this._container = L.DomUtil.create("div"); // 创建一个放按钮的div

      // 缩小
      this._btn_zoom_out = L.DomUtil.create(
        "input",
        "example-button",
        this._container
      );
      this._btn_zoom_out.type = "button";
      this._btn_zoom_out.value = "缩小";
      // 使用DomEvent绑定事件
      L.DomEvent.on(this._btn_zoom_out, "click", function (e) {
        if (map._zoom < map.getMaxZoom()) {
          map.zoomOut(map.options.zoomDelta * (e.shiftKey ? 3 : 1));
        }
      });

      // 放大
      this._btn_zoom_in = L.DomUtil.create(
        "input",
        "example-button",
        this._container
      );
      this._btn_zoom_in.type = "button";
      this._btn_zoom_in.value = "放大";
      // 使用DomEvent绑定事件
      L.DomEvent.on(this._btn_zoom_in, "click", function (e) {
        if (map._zoom < map.getMaxZoom()) {
          map.zoomIn(map.options.zoomDelta * (e.shiftKey ? 3 : 1));
        }
      });
      return this._container;
    };
    customZoom.addTo(map);
  </script>

</body>

</html>

  • 5
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Leaflet中,可以使用zIndexOffset属性来设置图标的z-index值。默认情况下,图标的z-index值为0。通过设置zIndexOffset属性,可以调整图标的z-index值,以避免标签与图标相互遮挡。在给标签添加自定义样式时,可以使用CSS的z-index属性来控制标签的层级关系。\[1\] 另外,Leaflet还提供了API文档和在线例子,可以详细了解Leaflet的各个类的函数和属性,以及使用Leaflet插件的方法。\[2\] 在CSS中,可以使用position属性来设置元素的定位方式。其中,absolute表示绝对定位,完全脱离标准文档流。结合方位词(left、right、top、bottom)一起使用,可以定义元素相对于其包含块的位置。如果没有指定参考,元素将以窗口为参考进行定位;如果定义了参考,元素将以包含块为参考进行定位。\[3\] #### 引用[.reference_title] - *1* [leaflet添加自定义标注且不遮挡点位图标](https://blog.csdn.net/m0_74149462/article/details/130194895)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [leaflet结合Leaflet-Geoman插件实现绘制以及动态配置样式(附源码下载)](https://blog.csdn.net/liguoweioo/article/details/120376461)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [前端学习day07](https://blog.csdn.net/qq_44559185/article/details/123300569)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

@Demi

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

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

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

打赏作者

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

抵扣说明:

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

余额充值