【技术】Leaflet 地图,惭愧惭愧

2 篇文章 0 订阅

Leaflet

一、简介

(一)介绍

Leaflet 是一个为建设移动设备友好的互动地图,而开发的现代的、开源的 JavaScript 库。它是由 Vladimir Agafonkin 带领一个专业贡献者团队开发,虽然代码仅有 42KB,但它具有开发人员开发在线地图的大部分功能。

Leaflet 设计坚持简便、高性能和可用性好的思想,在所有主要桌面和移动平台能高效运作,在现代浏览器上会利用 HTML5 和 CSS3 的优势,同时也支持旧的浏览器访问。支持插件扩展,有一个友好、易于使用的API文档和一个简单的、可读的源代码

官网:https://leafletjs.com/

(二)安装配置

  • 下载

  • 解压,解压后的目录如下:

leaflet.js -这是缩小的Leaflet JavaScript代码。

leaflet-src.js-这是可读的,最小的Leaflet JavaScript,有时对调试很有帮助。

leaflet.css -这是Leaflet的样式表。

images-这是一个包含由引用的图像的文件夹leaflet.css。

  • 配置,引入样式文件和 JS 脚本即可。
<link href="leaflet/leaflet.css" rel="stylesheet" />
<script src="leaflet/leaflet.js"></script>

(三)术语介绍

  • **经纬度:**经纬度是经度与纬度组成的坐标系统,是一种利用三度空间的球面来定义地球上的空间的球面坐标系统,能够标示地球上的任何一个位置。
  • **瓦片:**瓦片是将地图图片,并按照固定的尺寸分割后的图片碎片。也就是说 Leaflet 在页面上展示的地图是通过图片碎片拼接起来的。
    • 为了提高地图的响应速度,很多项目会通过Maperitive软件下载瓦片形成离线图片。

二、常用案例

(一)基础案例

  • 创建项目,导入 Leaflet 资源
  • 创建 html 页面,导入 Leaflet 样式和 脚本
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link href="leaflet/leaflet.css" rel="stylesheet" />
        <script src="leaflet/leaflet.js"></script>
	</head>
	<body>
	</body>
</html>
  • 定义容器,存放地图,容器可以配置大小。
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link href="leaflet/leaflet.css" rel="stylesheet" />
        <script src="leaflet/leaflet.js"></script>
		<style>
			body {
				margin: 0;
				padding: 0;
			}

			#map {
				position: absolute;
				top: 0;
				bottom: 0;
				width: 100%;
			}
		</style>
	</head>
	<body>
        <!-- 定义容器,存放地图 -->
        <div id="map"></div>
	</body>
</html>
  • 编写脚本配置地图

瓦片的数据地址可以是公网提供的,也可以内网私服。

Leaflet 官网地址:https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png

高德地址:http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}

内网地址:http://10.87.221.254:8091/tiles/{z}/{x}/{y}.png

<!DOCTYPE html>
<html>
	<head>
		<meta charset=utf-8 />
		<title>Leaflet</title>
		<link href="leaflet/leaflet.css" rel="stylesheet" />
        <script src="leaflet/leaflet.js"></script>
		<style>
			body {
				margin: 0;
				padding: 0;
			}

			#map {
				position: absolute;
				top: 0;
				bottom: 0;
				width: 100%;
			}
		</style>
	</head>
	<body>
        <!-- 定义容器,存放地图 -->
        <div id="map"></div>
        
        <script>
			/* 
				L为 Leaflset 对象,创建 Map 对象,配置初始化视图信息;
				参数一:经纬度,[维度,经度]
				参数二:zoom等级,可以简单理解为缩放比例
			*/
			var map = L.map('map').setView([34.819093, 113.561224], 7);
			
			/*
				配置布局;
				参数一:瓦片数据地址
				参数二:地图参数
					attribution: 版权信息
			*/
			L.tileLayer(
				'http://10.87.221.254:8091/tiles/{z}/{x}/{y}.png', 
				{
                    attribution: '&copy; <a href="https://863rc.com">中原英才</a>',
					maxZoom: 18,
				},
			).addTo(map);
		</script>
	</body>
</html>
  • 结果展示

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fEix0XOK-1666862019301)(八六三软件-Leaflet学习文档.assets/image-20220805190310098.png)]

(二)点击事件

<!DOCTYPE html>
<html>
	<head>
		<meta charset=utf-8 />
		<title>Leaflet</title>
		<link href="leaflet/leaflet.css" rel="stylesheet" />
        <script src="leaflet/leaflet.js"></script>
		<style>
			body {
				margin: 0;
				padding: 0;
			}

			#map {
				position: absolute;
				top: 0;
				bottom: 0;
				width: 100%;
			}
		</style>
	</head>
	<body>
        <!-- 定义容器,存放地图 -->
        <div id="map"></div>
        
        <script>
			/* 
				L为 Leaflset 对象,创建 Map 对象,配置初始化视图信息;
				参数一:经纬度,[维度,经度]
				参数二:zoom等级,可以简单理解为缩放比例
			*/
			var map = L.map('map').setView([34.819093, 113.561224], 7);
			
			/*
				为地图容器添加底图。
				参数一:瓦片数据地址
				参数二:地图参数
					attribution: 版权信息
			*/
			L.tileLayer(
				'http://10.87.221.254:8091/tiles/{z}/{x}/{y}.png', 
				{
                    attribution: '&copy; <a href="https://863rc.com">中原英才</a>',
					maxZoom: 18,
				},
			).addTo(map);
            
			// 地图点击事件
			map.on('click', function(e) {
                // map 设置视图,传递经纬度坐标, zoom 等级。
				map.setView(e.latlng, 10);
			});
		</script>
	</body>
</html>

(三)标记案例

<!DOCTYPE html>
<html>
	<head>
		<meta charset=utf-8 />
		<title>Leaflet with mapbox</title>
		<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
		<link href="leaflet/leaflet.css" rel="stylesheet" />
        <script src="leaflet/leaflet.js"></script>
        <script src="leaflet/leaflet.polylineDecorator.js"></script>
		<style>
			body {
				margin: 0;
				padding: 0;
			}

			#map {
				position: absolute;
				top: 0;
				bottom: 0;
				width: 100%;
			}

			.pop-style .leaflet-popup-content-wrapper {
				background: #4ab4ff;
			}

			.pop-style .leaflet-popup-tip {
				border-top-color: #4ab4ff;
			}
		</style>
	</head>
	<body>
		<div id='map'></div>

		<script>
			/* 
				L为 Leaflset 对象,创建 Map 对象,配置初始化视图信息;
				参数一:经纬度,[维度,经度]
				参数二:zoom等级,可以简单理解为缩放比例
			*/
			var map = L.map('map').setView([34.819093, 113.561224], 7);
			
			/*
				为地图容器添加底图。
				参数一:瓦片数据地址
				参数二:地图参数
					attribution: 版权信息
			*/
			L.tileLayer(
				'http://10.87.221.254:8091/tiles/{z}/{x}/{y}.png', 
				{
                    attribution: '&copy; <a href="https://863rc.com">中原英才</a>',
					maxZoom: 18,
				},
			).addTo(map);

            // 跟换标记的图片
            var markerIocn = L.icon({
				iconUrl: 'leaflet/images/plan.png',
				// 标记图片大小
				iconSize: [30, 50]
			});

			// 添加标记(marker)
			L.marker([34.819093, 113.561224], {icon:markerIocn}).addTo(map);
		</script>
	</body>
</html>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cfbJiXPp-1666862019302)(八六三软件-Leaflet学习文档.assets/image-20220807102519465.png)]

(四)线段、多边形、矩形

<!DOCTYPE html>
<html>
	<head>
		<meta charset=utf-8 />
		<title>Leaflet with mapbox</title>
		<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
		<link href="leaflet/leaflet.css" rel="stylesheet" />
        <script src="leaflet/leaflet.js"></script>
		<style>
			body {
				margin: 0;
				padding: 0;
			}

			#map {
				position: absolute;
				top: 0;
				bottom: 0;
				width: 100%;
			}
		</style>
	</head>
	<body>
		<div id='map'></div>

		<script>
			/* 
				L为 Leaflset 对象,创建 Map 对象,配置初始化视图信息;
				参数一:经纬度,[维度,精度]
				参数二:zoom等级,可以简单理解为缩放比例
			*/
			var map = L.map('map').setView([34.819093, 113.561224], 7);
			
			/*
				为地图容器添加底图。
				参数一:瓦片数据地址
				参数二:地图参数
					attribution: 版权信息
			*/
			L.tileLayer(
				'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 
				{
                    attribution: '&copy; <a href="https://863rc.com">中原英才</a>',
					maxZoom: 18,
				},
			).addTo(map);

			/* 线段 */
			var arrow1 = L.polyline([[34.819093, 113.561224], [34.819093, 118.561224]], {opacity: 1,color: 'firebrick'}).bindPopup('I am red:').addTo(map);
			var arrow2 = L.polyline([[34.819093, 113.561224], [30.819093, 114.561224]], {opacity: 1,color: 'lightgreen'}).bindPopup('I am green:').addTo(map);
			var arrow3 = L.polyline([[30.819093, 114.561224], [34.819093, 118.561224]], {opacity: 1,color: 'orange'}).bindPopup('I am orange:').addTo(map);
            
            /* 多边形 */
		    // 多边形点位坐标
			var latlngs = [
				[38.584931, 106.055274],
				[39.945795, 116.294531],
				[31.093209, 121.348242],
				[30.56491, 104.077735],
			];
			// 创建带颜色的多边形
			var polygon = L.polygon(latlngs, {color: 'green'}).addTo(map);
			// 地图缩放到多边形区域
			// map.fitBounds(polygon.getBounds());
            
            /* 矩形 */
			// 矩形点位坐标
			var bounds = [[38.584931, 106.055274], [31.093209, 121.348242]];
			// 创建带颜色的矩形
			L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
			// 地图缩放到多边形区域
			// map.fitBounds(bounds);
		</script>
	</body>
</html>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9IwhCIVu-1666862019303)(八六三软件-Leaflet学习文档.assets/image-20220807104641647.png)]

(五)圆

<!DOCTYPE html>
<html>
	<head>
		<meta charset=utf-8 />
		<title>Leaflet with mapbox</title>
		<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
		<link href="leaflet/leaflet.css" rel="stylesheet" />
        <script src="leaflet/leaflet.js"></script>
        <script src="leaflet/leaflet.polylineDecorator.js"></script>
        <script src="leaflet/leaflet.ChineseTmsProviders.js"></script>
        <script src="echarts/echarts.js"></script>
		<style>
			body {
				margin: 0;
				padding: 0;
			}

			#map {
				position: absolute;
				top: 0;
				bottom: 0;
				width: 100%;
			}
		</style>
	</head>
	<body>
		<div id='map'></div>

		<script>
			 /* 
				L为 Leaflset 对象,创建 Map 对象,配置初始化视图信息;
				参数一:经纬度,[维度,精度]
				参数二:zoom等级,可以简单理解为缩放比例
			*/
			var map = L.map('map').setView([34.819093, 113.561224], 7);
			
			/*
				为地图容器添加底图。
				参数一:瓦片数据地址
				参数二:地图参数
					attribution: 版权信息
			*/
			L.tileLayer(
				'http://10.87.221.254:8091/tiles/{z}/{x}/{y}.png', 
				{
                    attribution: '&copy; <a href="https://863rc.com">中原英才</a>',
					maxZoom: 18,
				},
			).addTo(map);
            
			/* 
				圆圈
				通过传入相应options控制circle样式
			*/
			var circle = L.circle([34.819093, 113.561224], {
				color: 'red',         // 圈轨迹颜色,即外边框的颜色
				fillColor: '#f03',    // 填充色,默认值与color值一致
				fillOpacity: 0.5,     // 填充透明度
				radius: 500 * 1000    // circle半径,单位为米
			}).addTo(map);

		</script>
	</body>
</html>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0ViUFZ50-1666862019303)(八六三软件-Leaflet学习文档.assets/image-20220807232458335.png)]

(六)弹框 popup

<!DOCTYPE html>
<html>
	<head>
		<meta charset=utf-8 />
		<title>Leaflet with mapbox</title>
		<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
		<link href="leaflet/leaflet.css" rel="stylesheet" />
        <script src="leaflet/leaflet.js"></script>
		<style>
			body {
				margin: 0;
				padding: 0;
			}

			#map {
				position: absolute;
				top: 0;
				bottom: 0;
				width: 100%;
			}

			.pop-style .leaflet-popup-content-wrapper {
				background: #4ab4ff;
			}

			.pop-style .leaflet-popup-tip {
				border-top-color: #4ab4ff;
			}
		</style>
	</head>
	<body>
		<div id='map'></div>

		<script>
			/* 
				L为 Leaflset 对象,创建 Map 对象,配置初始化视图信息;
				参数一:经纬度,[维度,精度]
				参数二:zoom等级,可以简单理解为缩放比例
			*/
			var map = L.map('map').setView([34.819093, 113.561224], 7);
			
			/*
				为地图容器添加底图。
				参数一:瓦片数据地址
				参数二:地图参数
					attribution: 版权信息
			*/
			L.tileLayer(
				'http://10.87.221.254:8091/tiles/{z}/{x}/{y}.png', 
				{
                    attribution: '&copy; <a href="https://863rc.com">中原英才</a>',
					maxZoom: 18,
				},
			).addTo(map);


			// 添加标记(marker)
			L.marker([34.819093, 113.561224]).addTo(map);
			
			// 静态 popup 弹框
			var popup = L.popup({
					closeButton: false,
					closeOnClick: false,
					className: "pop-style"
				}).setLatLng([34.819093, 113.561224])
				.setContent('<p>Hello world!<br />This is a nice popup.</p>')
				.openOn(map);

			// marker-自定义图标-绑定 popup 开始
			var myIcon = L.icon({
                // 标记图片地址
				iconUrl: 'leaflet/images/111.png',
                // 标记图片大小
				iconSize: [30, 50]
			});

            // 添加标记(marker)
			L.marker([34.27083595165,108.92944335937501], {
				icon: myIcon // 引入图标
			}).addTo(map)
				.bindPopup('<p style="color:#db1b00;">标记绑定popup 弹框。</p>') // 绑定 popup 弹框
				// .openPopup(); // 打开 popup 弹框
            // marker-自定义图标-绑定 popup 结束
		</script>
	</body>
</html>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7RF7ujym-1666862019304)(八六三软件-Leaflet学习文档.assets/image-20220807103627841.png)]

(七)图层类型切换

<!DOCTYPE html>
<html>
	<head>
		<meta charset=utf-8 />
		<title>Leaflet with mapbox</title>
		<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
		<link href="leaflet/leaflet.css" rel="stylesheet" />
        <script src="leaflet/leaflet.js"></script>
        <script src="leaflet/leaflet.polylineDecorator.js"></script>
        <script src="leaflet/leaflet.ChineseTmsProviders.js"></script>
        <script src="echarts/echarts.js"></script>
		<style>
			body {
				margin: 0;
				padding: 0;
			}

			#map {
				position: absolute;
				top: 0;
				bottom: 0;
				width: 100%;
			}
		</style>
	</head>
	<body>
		<div id='map'></div>

		<script>
			 /* 
				L为 Leaflset 对象,创建 Map 对象,配置初始化视图信息;
				参数一:经纬度,[维度,精度]
				参数二:zoom等级,可以简单理解为缩放比例
			*/
			var map = L.map('map').setView([34.819093, 113.561224], 13);
			L.tileLayer(
				'', 
				{
					attribution: '&copy; <a href="https://863rc.com">中原英才</a>',
					maxZoom: 18,
				},
			).addTo(map);
			
			// 定义基础布局
			var baseLayers = {
				"高德地图": L.tileLayer('http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', {
					subdomains: "1234"
				}).addTo(map),
				'高德影像': L.layerGroup([L.tileLayer('http://webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}', {
					subdomains: "1234"
				}), L.tileLayer('http://t{s}.tianditu.cn/DataServer?T=cta_w&X={x}&Y={y}&L={z}', {
					subdomains: "1234"
				})]),
				'GeoQ灰色底图': L.tileLayer('http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}'),
		
				'自定义底图': L.tileLayer('http://10.87.221.254:8091/tiles/{z}/{x}/{y}.png')
			};
			
			// 定义图层控制,添加布局
			var layercontrol = L.control.layers(baseLayers, {}, {
				position: "topright"
			}).addTo(map);
		</script>
	</body>
</html>

(八)Leaflet + Echarts

<!DOCTYPE html>
<html>
	<head>
		<meta charset=utf-8 />
		<title>Leaflet with mapbox</title>
		<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
		<link href="leaflet/leaflet.css" rel="stylesheet" />
        <script src="leaflet/leaflet.js"></script>
        <script src="leaflet/leaflet.polylineDecorator.js"></script>
        <script src="leaflet/leaflet.ChineseTmsProviders.js"></script>
        <script src="echarts/echarts.js"></script>
		<style>
			body {
				margin: 0;
				padding: 0;
			}

			#map {
				position: absolute;
				top: 0;
				bottom: 0;
				width: 100%;
			}
			#charts{
				width: 300px;
				height: 300px;
			}
		</style>
	</head>
	<body>
		<div id='map'></div>

		<script>
			 /* 
				L为 Leaflset 对象,创建 Map 对象,配置初始化视图信息;
				参数一:经纬度,[维度,精度]
				参数二:zoom等级,可以简单理解为缩放比例
			*/
			var map = L.map('map').setView([34.819093, 113.561224], 7);
			
			/*
				配置布局;
				参数一:瓦片数据地址
				参数二:地图参数
					attribution: 版权信息
			*/
			L.tileLayer(
				'http://10.87.221.254:8091/tiles/{z}/{x}/{y}.png', 
				{
                    attribution: '&copy; <a href="https://863rc.com">中原英才</a>',
					maxZoom: 18,
				},
			).addTo(map);
			
			// 添加标记(marker)
			var marker = L.marker([34.819093, 113.561224]).addTo(map);
			// 标记绑定弹框
			marker.bindPopup('<div id="charts"></div>',{});
			// 标记绑定事件
			marker.on('popupopen', function(e){
				var myCharts = echarts.init(document.querySelector("#charts"));
				var option = {
					title: {
						text: 'ECharts'
					},
					tooltip: {},
					legend: {
						data:['销量']
					},
					xAxis: {
						data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
					},
					yAxis: {},
					series: [{
						name: '销量',
						type: 'bar',
						data: [5, 20, 36, 10, 10, 20]
					}]
				};
				myCharts.setOption(option);
			});
			
		</script>
	</body>
</html>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fjc87fBz-1666862019309)(八六三软件-Leaflet学习文档.assets/image-20220807221553048.png)]

三、Leaflet 插件

(一)中国地图插件

1、案例

Leaflet 提供了一个插件Leaflet.ChineseTmsProviders,https://github.com/htoooth/Leaflet.ChineseTmsProviders

  • 下载插件,引入脚本
<script src="leaflet/leaflet.ChineseTmsProviders.js"></script>
  • 编写脚本
<!DOCTYPE html>
<html>
	<head>
		<meta charset=utf-8 />
		<title>Leaflet with mapbox</title>
		<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
		<link href="leaflet/leaflet.css" rel="stylesheet" />
        <script src="leaflet/leaflet.js"></script>
        <script src="leaflet/leaflet.polylineDecorator.js"></script>
        <script src="leaflet/leaflet.ChineseTmsProviders.js"></script>
		<style>
			body {
				margin: 0;
				padding: 0;
			}

			#map {
				position: absolute;
				top: 0;
				bottom: 0;
				width: 100%;
			}
		</style>
	</head>
	<body>
		<div id='map'></div>

		<script>
			 /* 
				L为 Leaflset 对象,创建 Map 对象,配置初始化视图信息;
				参数一:经纬度,[维度,精度]
				参数二:zoom等级,可以简单理解为缩放比例
			*/
			var map = L.map('map').setView([34.819093, 113.561224], 7);
			
			// 使用中国地图插件,引入天地图
			L.tileLayer.chinaProvider('TianDiTu.Normal.Map',{maxZoom:18,minZoom:5}).addTo(map);
			L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion',{maxZoom:18,minZoom:5}).addTo(map);
		</script>
	</body>
</html>
2、地图的提供者

如果您想使用百度提供商,请安装Proj4Leaflet在您的项目中。

  • TianDiTu
    • TianDiTu.Normal.Map
    • TianDiTu.Normal.Annotion
    • TianDiTu.Satellite.Map
    • TianDiTu.Satellite.Annotion
    • TianDiTu.Terrain.Map
    • TianDiTu.Terrain.Annotion
  • GaoDe
    • GaoDe.Normal.Map (include Annotion)
    • GaoDe.Satellite.Map
    • GaoDe.Satellite.Annotion
  • Google
    • Google.Normal.Map (include Annotion)
    • Google.Satellite.Map (exclude Annotion)
    • Google.Satellite.Map (include Annotion)
  • Geoq
    • Geoq.Normal.Map
    • Geoq.Normal.PurplishBlue
    • Geoq.Normal.Gray
    • Geoq.Normal.Warm
    • Geoq.Normal.Hydro
  • OSM
    • OSM.Normal.Map
  • Baidu
    • Baidu.Normal.Map
    • Baidu.Satellite.Map (exclude Annotion)
    • Baidu.Satellite.Annotion

(二)画线装饰插件

1、案例

polylineDecorator.js,https://github.com/bbecquet/Leaflet.PolylineDecorator

<!DOCTYPE html>
<html>
	<head>
		<meta charset=utf-8 />
		<title>Leaflet with mapbox</title>
		<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
		<link href="leaflet/leaflet.css" rel="stylesheet" />
        <script src="leaflet/leaflet.js"></script>
        <script src="leaflet/leaflet.polylineDecorator.js"></script>
		<style>
			body {
				margin: 0;
				padding: 0;
			}

			#map {
				position: absolute;
				top: 0;
				bottom: 0;
				width: 100%;
			}
		</style>
	</head>
	<body>
		<div id='map'></div>

		<script>
			/* 
				L为 Leaflset 对象,创建 Map 对象,配置初始化视图信息;
				参数一:经纬度,[维度,精度]
				参数二:zoom等级,可以简单理解为缩放比例
			*/
			var map = L.map('map').setView([34.819093, 113.561224], 7);
			
			/*
				为地图容器添加底图。
				参数一:瓦片数据地址
				参数二:地图参数
					attribution: 版权信息
			*/
			L.tileLayer(
				'http://10.87.221.254:8091/tiles/{z}/{x}/{y}.png', 
				{
                    attribution: '&copy; <a href="https://863rc.com">中原英才</a>',
					maxZoom: 18,
				},
			).addTo(map);


			// 添加区域线
			var arrow1 = L.polyline([[34.819093, 113.561224], [34.819093, 118.561224]], {opacity: 1,color: 'firebrick'}).bindPopup('I am red:').addTo(map);
			var arrow2 = L.polyline([[34.819093, 113.561224], [30.819093, 114.561224]], {opacity: 1,color: 'lightgreen'}).bindPopup('I am green:').addTo(map);
			var arrow3 = L.polyline([[30.819093, 114.561224], [34.819093, 118.561224]], {opacity: 1,color: 'orange'}).bindPopup('I am orange:').addTo(map);
			
			// 线条样式
			var arrowHead = L.polylineDecorator(arrow1, {
				patterns: [
					{
						offset: '10%', // 偏移量
						repeat: '20%', // 模式符号的重复间隔
						// 符号实例
						symbol: L.Symbol.arrowHead({
							pixelSize: 10, // 符号大小
							polygon: false, // 
							// 符号样式
							pathOptions: {
								stroke: true, // 是否显示边线
								weight: 5, // 线宽
								color: 'yellow', // 符号颜色
							},
						})
					},
					{
						// 模式符号的偏移位置
						offset: '10%',
						// 模式符号的重复间隔
						repeat: '20%',
						// 符号实例
						symbol: L.Symbol.marker({
							// 是否允许旋转,true 表示旋转,会根据线的位置自动旋转
							rotate: true,
							//标记显示样式
							markerOptions: {
								//图标
								icon: L.icon({
									//图标地址
									iconUrl: 'leaflet/images/plan.png',
									//图标位置
									iconAnchor: [16, 16],
									// 标记图片大小
									iconSize: [30, 30]
								})
							}
						})
					}
				]
			}).addTo(map);
		</script>
	</body>
</html>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GXcX08KO-1666862019310)(八六三软件-Leaflet学习文档.assets/image-20220807110506872.png)]

2、参数
  • Pattern定义
属性参数类型必须描述
offsetsee belowNo第一个图案符号相对于线条起点的偏移。默认值:0。
endOffsetsee belowNo最后一个图案符号距直线终点的最小偏移量。默认值:0。
repeatsee belowYes图案符号的重复间隔。定义每个连续符号锚点之间的距离。
symbolSymbol factoryYes符号工厂类的实例。

offset, endOffsetrepeat可以分别定义为数字、像素或线条长度的百分比、字符串(例如:'10%').

  • 方法
方法描述
setPaths(latlngs)更改装饰器应用的路径。latlngs可以是构造函数支持的所有类型。例如,如果从集合中删除多段线,或者坐标发生变化,这将非常有用。
setPatterns(<Pattern[]> patterns)更改装饰器的模式定义,并相应地更新符号。

四、Leaflet API

构造器

构造器使用描述
`L.Map( <HTMLElementString> id, options? )`new L.Map(…) L.map(…)

配置项

地图状态配置项
选项类型默认值描述
**center**LatLngnull初始化地图的地理中心.
**zoom**Numbernull初始化地图的缩放.
**layers**ILayer[]null初始化后加载到地图上的图层.
**minZoom**Numbernull地图的最小视图。可以重写地图图层的minZoom.
**maxZoom**Numbernull地图的最大视图。可以重写地图图层的maxZoom.
**maxBounds**LatLngBoundsnull当这个选项被设置后,地图被限制在给定的地理边界内,当用户平移将地图拖动到视图以外的范围时会出现弹回的效果, 并且也不允许缩小视图到给定范围以外的区域(这取决于地图的尺寸)。 使用setMaxBounds方法可以动态地设置这种约束.
**crs**CRSL.CRS.EPSG3857使用的坐标系,当你不确定坐标系是什么时请不要更改.
交互选项
选项类型默认值描述
**dragging**Booleantrue决定地图是否可被鼠标或触摸拖动.
**touchZoom**Booleantrue决定地图是否可被两只手指触摸拖拽缩放.
**scrollWheelZoom**Booleantrue决定地图是否被被鼠标滚轮滚动缩放.
**doubleClickZoom**Booleantrue决定地图是否可被双击缩放.
**boxZoom**Booleantrue决定地图是否可被缩放到鼠标拖拽出的矩形的视图,鼠标拖拽时需要同时按住shift键.
**tap**BooleantrueEnables mobile hacks for supporting instant taps (fixing 200ms click delay on iOS/Android) and touch holds (fired as contextmenu events).
**tapTolerance**Number15The max number of pixels a user can shift his finger during touch for it to be considered a valid tap.
**trackResize**Booleantrue确定地图在窗口尺寸改变时是否可以自动处理浏览器以更新视图.
**worldCopyJump**Booleanfalse当这个选项可用时,当你平移地图到其另一个领域时会被地图捕获到,并无缝地跳转到原始的领域以保证所有标注、矢量图层之类的覆盖物仍然可见.
**closePopupOnClick**Booleantrue当你不想用户点击地图关闭消息弹出框时,请将其设置为false .
键盘导航选项
选项类型默认值描述
**keyboard**Booleantrue聚焦到地图且允许用户通过键盘的方向键和+/-键来漫游地图.
**keyboardPanOffset**Number80确定按键盘方向键时地图平移的像素.
**keyboardZoomOffset**Number1确定键盘+ or -键对于的缩放级数.
平移惯性选项
选项类型默认值描述
**inertia**Booleantrue如果该选项可用,在拖动和在某一时间段内持续朝同一方向移动建有动力的地图时,会有惯性的效果.
**inertiaDeceleration**Number3000确定惯性移动减速的速率,单位是像素每秒的二次方2.
**inertiaMaxSpeed**Number1500惯性移动的最大速度,单位是像素每秒.
**inertiaThreshold**Numberdepends放开鼠标或是触摸来停止惯性移动与移动停止之间的毫秒数.
控制选项
选项类型默认值描述
**zoomControl**Booleantrue确定zoom control是否默认加载在地图上 .
**attributionControl**Booleantrue确定attribution control是否默认加载在地图上.
动画选项
选项类型默认值描述
**fadeAnimation**Booleandepends确定瓦片淡出动画是否可用。通常默认在所有浏览器中都支持CSS3转场,android例外.
**zoomAnimation**Booleandepends确定瓦片缩放动画是否可用。通常默认在所有浏览器中都支持CSS3转场,android例外.
**zoomAnimationThreshold**Number4Won’t animate zoom if the zoom difference exceeds this value.
**markerZoomAnimation**Booleandepends确定注记的缩放是否随地图缩放动画而播放,如果被禁用,注记在动画中拉长时会消失。通常默认在所有浏览器中都支持CSS3转场,android例外.

事件

You can subscribe to the following events using these methods.

EventData描述
**click**MouseEvent用户点击或触摸地图时触发.
**dblclick**MouseEvent用户双击或连续两次触摸地图时触发.
**mousedown**MouseEvent用户按下鼠标按键时触发.
**mouseup**MouseEvent用户按下鼠标按键时触发.
**mouseover**MouseEvent鼠标进入地图时触发.
**mouseout**MouseEvent鼠标离开地图时触发.
**mousemove**MouseEvent鼠标在地图上移动时触发.
**contextmenu**MouseEvent当用户在地图上按下鼠标右键时触发,如果有监听器在监听这个时间,则浏览器默认的情景菜单被禁用.
**focus**Event当用户在地图上进行标引、点击或移动时进行聚焦.
**blur**Event当地图失去焦点时触发.
**preclick**MouseEvent当鼠标在地图上点击之前触发。有时会在点击鼠标时,并在已存在的点击事件开始处理之前想要某件事情发生时用得到.
**load**Event当地图初始化时触发。(当地图的中心点和缩放初次设置时).
**unload**EventFired when the map is destroyed with remove method.
**viewreset**Event当地图需要重绘内容时触发。(通常在地图缩放和载入时发生)这对于创建用户自定义的叠置图层非常有用.
**movestart**Event地图视图开始改变时触发。(比如用户开始拖动地图).
**move**Event所有的地图视图移动时触发.
**moveend**Event当地图视图结束改变时触发。(比如用户停止拖动地图).
**dragstart**Event用户开始拖动地图时触发.
**drag**Event用户拖动地图时不断重复地触发.
**dragend**Event用户停止拖动时触发.
**zoomstart**Event当地图缩放即将发生时触发。(比如缩放动作开始前).
**zoomend**Event当地图缩放时触发.
**zoomlevelschange**EventFired when the number of zoomlevels on the map is changed due to adding or removing a layer.
**resize**ResizeEventFired when the map is resized.
**autopanstart**Event打开弹出窗口时地图开始自动平移时触发.
**layeradd**LayerEvent当一个新的图层添加到地图上时触发.
**layerremove**LayerEvent当一些图层从地图上移除时触发.
**baselayerchange**LayerEvent当通过layer control改变基础图层时触发.
**overlayadd**LayerEventFired when an overlay is selected through the layer control.
**overlayremove**LayerEventFired when an overlay is deselected through the layer control.
**locationfound**LocationEvent当地理寻址成功时触发(使用locate方法)
**locationerror**ErrorEvent当地理寻址错误时触发(使用locate方法)
**popupopen**PopupEvent当弹出框打开时触发(使用openPopup方法)
**popupclose**PopupEvent当弹出框关闭时触发(使用closePopup方法)

地图状态修改

方法返回值描述
**setView**( <LatLng> *center*, <Number> *zoom*, <zoom/pan options> *options?* )this设定地图(设定其地理中心和缩放).
**setZoom**( <Number> *zoom*, <zoom options> *options?* )this设定地图的缩放.
**zoomIn**( <Number> *delta?*, <zoom options> *options?* )this通过delta变量放大地图的级别,1是delta的默认值.
**zoomOut**( <Number> *delta?*, <zoom options> *options?* )this通过delta变量缩小地图的级别,1是delta的默认值.
**setZoomAround**( <LatLng> *latlng*, <Number> *zoom*, <zoom options> *options?* )thisZooms the map while keeping a specified point on the map stationary (e.g. used internally for scroll zoom and double-click zoom).
**fitBounds**( <LatLngBounds> *bounds*, <fitBounds options> *options?* )this将地图视图尽可能大地设定在给定的地理边界内.
**fitWorld**( <fitBounds options> *options?* )this将地图视图尽可能大地设定在包含全部地域的级别上.
**panTo**( <LatLng> *latlng*, <pan options> *options?* )this将地图平移到给定的中心。如果新的中心点在屏幕内与现有的中心点不同则产生平移动作.
**panInsideBounds**( <LatLngBounds> *bounds* )this平移地图到坐落于给定边界最接近的视图内.
**panBy**( <Point> *point*, <pan options> *options?* )this通过给定的像素值对地图进行平移.
**invalidateSize**( <Boolean> *options?*, <zoom/pan options> *options?* )this检查地图容器的大小是否改变并更新地图,如果是这样的话,在动态改变地图大小后调用,如果animate是true的话,对地图进行更新.
**setMaxBounds**( <LatLngBounds> *bounds*, <zoom/pan options> *options?* )this将地图限定在给定的边界内 (map maxBounds).
**locate**( <Locate options> *options?* )this用地理定位接口Geolocation API获取用户位置信息,在成功定位或定位出错产生locationerror后解除location-found事件与定位数据,且将地图视图设定到检测的确切的用户的位置(如果定位失败则回到地域视图)。在Locate options中有更多详细内容。
**stopLocate**()thisStops watching location previously initiated by **map.locate**({watch: true}) and aborts resetting the map view if map.locate was called with {setView: true}.
**remove**()thisDestroys the map and clears all related event listeners.

获取地图状态

方法返回值描述
**getCenter**()LatLng返回地图视图的地理中心.
**getZoom**()Number获取地图视图现在所处的缩放级别.
**getMinZoom**()Number返回地图最小的缩放级别.
**getMaxZoom**()Number返回地图最大的缩放级别.
**getBounds**()LatLngBounds返回地图视图的经纬度边界.
**getBoundsZoom**( <LatLngBounds> *bounds*, <Boolean> *inside?* )Number返回适应整个地图视图边界的最大缩放级别。如果inside的设置时true,这个方法返回适应整个地图视图边界的最小缩放级别.
**getSize**()Point返回现有地图容器的大小.
**getPixelBounds**()Bounds返回地图视图在像素投影坐标系下的边界。(很多时候对用户自定义图层和叠加很有用).
**getPixelOrigin**()Point返回地图图层像素投影坐标系下的左上角的点。(很多时候对用户自定义图层和叠加很有用).

图层控制

方法返回值描述
**addLayer**( <ILayer> *layer*, <Boolean> *insertAtTheBottom?* )this将图层添加到地图上。如果insertAtTheBottom的选项为true,图层添加时在所以图层之下。(在切换基底图时比较有用).
**removeLayer**( <ILayer> *layer* )this将图层在地图上移除.
**hasLayer**( <ILayer> *layer* )Boolean如果添加的图层是当前图层则返回true.
**openPopup**( <Popup> *popup* )this当关闭前一个弹出框时弹出指定的对话框。(确定在同一时间只有一个打开并可用).
`openPopup( html el, latlng, options? )`this
**closePopup**( <Popup> *popup?* )this关闭openPopup打开的弹出框.
**addControl**( <IControl> *control* )this在地图上添加控制选项.
**removeControl**( <IControl> *control* )this在地图上移除控制选项.

转换方法

方法返回值描述
**latLngToLayerPoint**( <LatLng> *latlng* )Point返回地图图层上与地理坐标相一致的点。(在地图上进行位置叠加时比较有用).
**layerPointToLatLng**( <Point> *point* )LatLng返回给定地图上点的地理坐标系.
**containerPointToLayerPoint**( <Point> *point* )Point将于地图容器相关的点转换为地图图层相关的点.
**layerPointToContainerPoint**( <Point> *point* )Point将地图图层相关的点转换为地图容器相关的点.
**latLngToContainerPoint**( <LatLng> *latlng* )Point返回与给定地理坐标系相符的地图容器的点.
**containerPointToLatLng**( <Point> *point* )LatLng返回给定地理容器点的地理坐标.
**project**( <LatLng> *latlng*, <Number> *zoom?* )Point将地理坐标投影到指定缩放级别的像素坐标系中.
**unproject**( <Point> *point*, <Number> *zoom?* )LatLng将像素坐标系投影到指定缩放级别的地理坐标系中。(默认为当前的缩放级别).
**mouseEventToContainerPoint**( <MouseEvent> *event* )Point返回鼠标点击事件对象的像素坐标(与地图左上角相关).
**mouseEventToLayerPoint**( <MouseEvent> *event* )Point返回鼠标点击事件对象的像素坐标(与地图图层相关).
**mouseEventToLatLng**( <MouseEvent> *event* )LatLng返回鼠标点击事件对象的地理坐标.

其他方法

方法返回值描述
**getContainer**()HTMLElement返回地图容器对象.
**getPanes**()MapPanes返回不同地图对象的边框(叠加渲染).
**whenReady**( <Function> *fn*, <Object> *context?* )this当地图的位置和缩放初始化好或是时间发生之后,运行给定的回调方法,通常传递一个函数内容.

位置选项

选项类型默认值描述
**watch**Booleanfalse如果该值为真,则开始利用W3C的watchPosition方法监听位置变化情况(而不是指监听一次)。你可以通过map.stoplocate()方法来停止监听.
**setView**Booleanfalse如果该值为真,则通过自动将地图视图定位到用户一定精度范围内的位置,如果地理定位失败则显示全部地图.
**maxZoom**NumberInfinity在使用setView选项时视图缩放的最大级别.
**timeout**Number10000在触发locationerror事件之前等待地理定位的毫秒为单位的时间.
**maximumAge**Number0位置监听的最大生命周期。如果比最后定位回复后毫秒用时短,则locate返回一个缓存位置.
**enableHighAccuracy**Booleanfalse开启高精度,参加 W3C SPEC的描述.

Zoom/pan options

选项类型默认值描述
**reset**BooleanfalseIf true, the map view will be completely reset (without any animations).
**pan**pan options-Sets the options for the panning (without the zoom change) if it occurs.
**zoom**zoom options-Sets the options for the zoom change if it occurs.
**animate**Boolean-An equivalent of passing animate to both zoom and pan options (see below).

Pan options

选项类型默认值描述
**animate**Boolean-If true, panning will always be animated if possible. If false, it will not animate panning, either resetting the map view if panning more than a screen away, or just setting a new offset for the map pane (except for panBy which always does the latter).
**duration**Number0.25Duration of animated panning.
**easeLinearity**Number0.25The curvature factor of panning animation easing (third parameter of the Cubic Bezier curve). 1.0 means linear animation, the less the more bowed the curve.
**noMoveStart**BooleanfalseIf true, panning won’t fire movestart event on start (used internally for panning inertia).

Zoom options

选项类型默认值描述
**animate**Boolean-If not specified, zoom animation will happen if the zoom origin is inside the current view. If true, the map will attempt animating zoom disregarding where zoom origin is. Setting false will make it always reset the view completely without animation.

fitBounds options

The same as zoom/pan options and additionally:

选项类型默认值描述
**paddingTopLeft**Point[0,0]Sets the amount of padding in the top left corner of a map container that shouldn’t be accounted for when setting the view to fit bounds. Useful if you have some control overlays on the map like a sidebar and you don’t want them to obscure objects you’re zooming to.
**paddingBottomRight**Point[0,0]The same for bottom right corner of the map.
**padding**Point[0,0]Equivalent of setting both top left and bottom right padding to the same value.

Properties

M地图属性包括互动操作,允许你在运行环境中互动地控制地图行为,比如通过拖拽和点击缩放级别显示和不显示某要素. Example:

map.doubleClickZoom.disable();

You can also access default map controls like attribution control through map properties:

map.attributionControl.addAttribution("Earthquake data &copy; GeoNames");
Property类型描述
**dragging**IHandler地图拖拽处理程序,可以通过鼠标和触摸的形式.
**touchZoom**IHandler触摸地图缩放处理程序.
**doubleClickZoom**IHandler双击缩放处理程序.
**scrollWheelZoom**IHandler滚动缩放处理程序.
**boxZoom**IHandler矩形框(利用鼠标拖动)缩放处理程序.
**keyboard**IHandler键盘导向处理程序.
**tap**IHandlerMobile touch hacks (quick tap and touch hold) handler.
**zoomControl**Control.Zoom缩放控制.
**attributionControl**Control.Attribution属性控制.

地图窗口

望文思义,这是一个包括可以用来放置自定义图层的不同的地图窗口的对象。最大的区别是图层的叠置.

Property类型描述
**mapPane**HTMLElement包含其他地图窗口的窗口.
**tilePane**HTMLElement切片图层的窗口.
**objectsPane**HTMLElement包含除切片窗口以外所有窗口的窗口.
**shadowPane**HTMLElement用来隐藏图层的窗口(如标注的隐藏).
**overlayPane**HTMLElement这线段和多边形一类图层的窗口.
**markerPane**HTMLElement标注图标的窗口.
**popupPane**HTMLElement弹出的窗口.
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值