Leaflet 地图开发基础

Leaflet 是一个轻量级的开源地图库,非常适合构建移动友好的交互式地图。

快速开始

引入 Leaflet CSS 和 JavaScript:

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

创建地图容器:

<div id="map" style="height: 600px;"></div>

初始化地图

const map = L.map('map').setView([39.9, 116.4], 13);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '© OpenStreetMap contributors',
  maxZoom: 19
}).addTo(map);

添加标记和弹窗

const marker = L.marker([39.9, 116.4]).addTo(map);
marker.bindPopup('<b>北京</b><br>中国首都').openPopup();

const circle = L.circle([39.92, 116.38], {
  color: 'red',
  fillColor: '#f03',
  fillOpacity: 0.5,
  radius: 500
}).addTo(map);

处理地图事件

map.on('click', function(e) {
  console.log('点击位置:', e.latlng);
  L.popup()
    .setLatLng(e.latlng)
    .setContent(`坐标: ${e.latlng.toString()}`)
    .openOn(map);
});

结语

Leaflet 简单易用,文档完善,是 WebGIS 开发的首选库之一。


相关文章

前端渲染大型表格方法总结

前端渲染大型表格方法总结

Vue 3 组合式 API 完全指南

深入理解 Vue 3 Composition API 的核心概念和最佳实践