# 基本介绍

Leaflet可用于桌面端和移动端。JS库的大小为38k左右,拥有大部分开发者需要的全部地图功能。
官网地址 (opens new window) 中文API文档 (opens new window)

# 在html中使用

<!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">
  <title>Document</title>
  <!--引入leaflet的js、css-->
  <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>
</head>
<style>
  * {
    box-sizing: border-box;
    margin: 0px;
    padding: 0px;
  }
 
  #mapid {
    height: 100vh;
  }
</style>
 
<body>
  <div id="mapid"></div>
</body>
<script>
  var mymap = L.map('mapid').setView([31.82658, 117.23344], 13);
  L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18
  }).addTo(mymap);
</script>
</html>

# 在Vue中使用

  • 安装leaflet
npm install leaflet
  • 全局引用(main.js)
import L from "leaflet";
import "leaflet/dist/leaflet.css";
  • vue页面初始化使用
<template>
  <div id="container"></div>
</template>

<script>
export default {
  data() {
    return {
      map: null,
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      this.map = L.map("container", {
        attributionControl: false,
	    zoomControl: true, // 显示缩放控件
	    center: [33.70, 113.57], // 初始地图中心
	    zoom: 5,
	    crs: L.CRS.EPSG3857,// 不能设置为4326
	    minZoom: 5,
	    maxZoom: 18,
	    scrollWheelZoom: true, // 默认开启鼠标滚轮缩放
	    maxBounds: L.latLngBounds(L.latLng(-90, -180), L.latLng(90, 180)) // 限制显示地理范围
      });
      window.map = map;
      L.tileLayer(
	    // http://192.168.0.250/WeServer/wmts/1.0.0/layer/default/wgs84/{z}/{y}/{x}.png
		// 高德影像地图
        // "http://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}"
		// 高德的WMS服务
		// "http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}"
		// 天地图矢量墨卡托投影
		// "http://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=c1890b6556739cabf20aeba3b62bd06d"
		// 天地图注记
		"http://t0.tianditu.gov.cn/DataServer?layer=cva&tk=c1890b6556739cabf20aeba3b62bd06d"
      ).addTo(map);
    },
  },
};
</script>
<style scoped>
#container {
  width: 100%;
  height: 100%;
}
</style>

# 常用方法

Leaflet学习笔记 (opens new window)

# 加载多个地图类型

var baseLayers = {
    'Sputnik': L.tileLayer('http://{s}.thunderforest.com/spinal-map/{z}/{x}/{y}{r}.png', {
      maxZoom: 18   
    }),
 
    "CartoDB": L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
      maxZoom: 18
    }),
 
    "OSM": L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 18
    }).addTo(map),
 
    "OpenTopoMap": L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
      maxZoom: 18
    }),
}
// 切换图层工具
var layerControl = L.control.layers(baseLayers, {}, {
    position: 'topleft',
    collapsed: true
}).addTo(map);

# 加载Geojson数据

let bbox = [34.22, 114.19, 38.23, 122.43]
let cellSide = 1
let options = { units: "kilometers" }
let result = turf.squareGrid(bbox, cellSide, options)
// 需要将经纬度位置换一下
turf.coordEach(result, function (coord) {
    coord.reverse()
})
L.geoJSON(result, {
   style: function(feature) {
	    const count = feature.properties.count
	    let color = `68, 149, 247`
	    if(count > 20) {
	       color = '165,0,179'
	    } else if(count <= 20 && count > 15) {
	       color = '255,10,10'
	    } else if(count <= 15 &&count > 10) {
	       color = '255,138,5'
	    } else if(count <= 10 &&count > 5) {
	       color = '247,176,76'
	    }
	    color = `rgb(${color})`
		return {
			 color: '#4264fb',
			 fillColor:feature.properties.fill,
			 weight:1,
			 fillOpacity:feature.properties.fillOpacity
		}
   }
}).addTo(this.map).bindPopup("I am a polygon layer.")

# 加载WMS服务

const url='/wfs/geoserver/gather/ows'
const params={
    service:'WFS',
    version:'1.1.0',
    request:'GetFeature',
    typeName:'gather:map_grid',
    maxFeatures:50,
    outputFormat:'application/json',
    //srsName:'EPSG:4326'
}
const url_str=url+L.Util.getParamString(params,url)
console.log(url_str)
$ajax({
    url:url_str,
    method: 'get',
    //dataType:'json'
}).then(res=>{
  console.log(res)
}).catch(err=>{
  console.log(err)
})