参考仓库:
leaflet基本用法
1.引入leafletjs资源:
- 手动 下载地址:https://leafletjs.com/download.html 引入css和js
- npm npm install leaflet --save 在组件或者main.js中引入
2.创建容器存放地图
<div id="map"></div>
3.初始化地图
坐标,纬度在前,经度在后,初始化地图必有两个参数,一个坐标,一个初始缩放倍数
<script setup>
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import { onMounted} from 'vue'
const initMap = () => {
let map = L.map('map', {
center: [29.44916482692468, 106.47399902343751],//中心坐标
zoom: null,//初始缩放,因为在下文写了展示全地图,所以这里不设置,也可以设置
minZoom: 3,
maxZoom: 18,
zoomControl: true, //缩放组件
// attributionControl: false, //去掉右下角logol
})
// let map=L.map("map").setview([29.44916482692468, 106.47399902343751],9);
}
onMounted(() => {
initMap()
})
</script>
4.给容器设置宽高,显示地图
<style>
#map {
height: 800px;
width: 1000px;
margin: auto;
border: 10px solid pink;
}
</style>
leaflet布局,图层
L.tileLayer加载底图,第一个参数为底图资源,第二个参数中attribution为版权
L.tileLayer(
"https://webrd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}",
{
attribution:
'© <p>OpenStreetMap</p> contributors',
}
).addTo(map);
leaflet标记
使用L.marker()第一个参数为经纬度,第二个参数为自定义标记图标。
addTo()添加到图层;bindPopup()显示弹框内容,openPopup()自动打开弹框。
弹框也可使用bindTooltip()
let markerIcon = L.icon({
iconUrl: "https://unpkg.com/leaflet@1.9.3/dist/images/marker-icon.png",
iconSize: [20, 30],
});
let marker = L.marker([29.44916482692468, 106.47399902343751], { icon: markerIcon })
.addTo(map)
.bindPopup("标记")
.openPopup();
//--------------------------------
//marker.bindTooltip('我是标记', { //添加提示文字
// permanent: true, //是永久打开还是悬停打开
//direction: 'top' //方向
//}).openTooltip(); //在图层打开
leaflet线段,形状
线段:使用 L.polyline()第一个参数为线段两端的位置坐标,第二个参数为线段的样式。
同样也可使用弹框来做数据展示。
let line = L.polyline([[29.44, 106.473], [27.595, 106.9]],
{
opacity: 1,
color: 'red'
}).addTo(map)
圆形:使用 L.circle(),对于圆形只需要一个坐标和圆的半径;第一个参数为圆点,第二个参数为圆的样式。同样也可使用弹框