一、Leaflet是什么?
Leaflet 是一个开源并且对移动端友好的交互式地图 JavaScript 库。 它大小仅仅只有 42 KB of JS, 并且拥有绝大部分开发者所需要的所有地图特性 。
Leaflet 简单、高效并且易用。 它可以高效的运行在桌面和移动平台, 拥有着大量的 扩展插件、 优秀的文档、简单易用的 API 和完善的案例, 以及可读性较好的 源码 。
二、简单上手
1.引入库
在文档的 head 部分引入 Leaflet CSS 文件:
<link
rel="stylesheet"
href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"
integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI="
crossorigin=""
/>
在引入 Leaflet CSS 文件之后引入 Leaflet JavaScript 文件:
<script
src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"
integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM="
crossorigin=""
></script>
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
/>
<link
rel="stylesheet"
href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"
integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI="
crossorigin=""
/>
<title>基本使用</title>
<style>
body {
padding: 0;
margin: 0;
background-color: bisque;
}
#map {
height: 90vh;
width: 100vw;
}
.leaflet-div-icon {
border: none;
background: none;
}
</style>
</head>
<script
src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"
integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM="
crossorigin=""
></script>
<script type="module">
// setView(LatLng(当前位置),zoom(默认开始显示的聚焦值))
var map = L.map("map").setView([31.82658, 117.23344], 13);
// attribution:添加地图右下角标识
L.tileLayer(
//将图层加载到地图上
"http://wprd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}",
{
maxZoom: 16,//最大聚焦值
//右下角描述
attribution:
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}
).addTo(map);
// GeoJSON数据(.GeoJSON 一种对地理数据结构进行编码的格式)
var coorsField = {
type: "FeatureCollection",
features: [
{
type: "Feature",
properties: {
popupContent: "标注点marker1", // 点击提示文字
},
geometry: {
type: "Point", // 配合 pointToLayer 一起使用
coordinates: [31.82658, 117.23344],
},
},
{
type: "Feature",
properties: {
popupContent: "标注点marker2", // 点击提示文字
},
geometry: {
type: "Point", // 配合 pointToLayer 一起使用
coordinates: [31.813, 117.245],
},
},
],
};
L.geoJSON(coorsField, {
pointToLayer: function (feature, latlng) {
// L.marker:设置marker标记
return L.marker(feature.geometry.coordinates, {
// L.divIcon:设置icon图标
icon: L.divIcon({
// 图标元素
html: `<div style="display:flex;align-items: center;"><img src="../../../assets/img/icon/icon4_s.png" alt=""><span style="white-space: nowrap">坐标:${latlng}</span></div>`,
}),
})// 该方法标定弹出框的内容
.bindPopup(feature.properties.popupContent)
.on("click", function () {
// 重新设置坐标,和聚焦倍数达到点击放大效果
map.setView(feature.geometry.coordinates, 16);
});
},
}).addTo(map);
</script>
<body>
// 绘制地图的盒子
<div id="map"></div>
</body>
</html>
2.效果