leaflet_基础篇

1. 数据

点 lng lat
116.134782 39.91316

线
116.341782 39.91316 ,116.431732 39.944753

面
116.273804 39.931591,
116.344528 39.939225,
116.328049 39.898148,
116.258354 39.906049

2. 单词 插件

2.1 单词

polymerize 聚合
polygon 多边形
polyline 折线

2.2 测距

测距css
测距js
测面积
init_css
init_js
ant-path

3. init地图

this.mymap = L.map('mapid', {
    center: [this.location.lat, this.location.lng],
    zoom: 10,
    maxZoom: 21,
    crs: L.CRS.EPSG4326,
    zoomControl: false, //左上角放大 缩小
    attributionControl: false, //右下角 加载底图 产生的 leafletjs 链接 隐藏掉
});

左下角-右上角
 map.fitBounds([
    [24.93896484375, 101.546630859375],
    [33.37646484375, 116.488037109375]
 ]); 
 拖动弹回效果
 map.setMaxBounds([
    [24.93896484375, 101.546630859375],
    [33.37646484375, 116.488037109375]
 ]);
 
    this.myMap.setMaxBounds(
              [29.71645532894234, 107.38936454057696],
              [29.71714950845788, 107.39126622676851],
            );
            
this.myMap.setView([this.initMap.lat, this.initMap.lng], 12);

this.myMap.flyTo([this.initMap.lat, this.initMap.lng], 12);

map.on("click", function(ev) {
    console.log("纬度:", ev.latlng.lat, "经度:", ev.latlng.lng);
});

map.on("zoom", function(ev) {
    console.log("放大等级:", ev.target._zoom);
});

------------------------------
// disable drag and zoom handlers
 
//禁止移动和放大缩小
 
map.dragging.disable();
 
map.touchZoom.disable();
 
map.doubleClickZoom.disable();
 
map.scrollWheelZoom.disable();
 
// disable tap handler, if present.
 
//禁止单击
 
if (map.tap) map.tap.disable();

4. 地图 点击事件

底图
L.tileLayer(‘https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png’, {
attribution: ‘© OpenStreetMap contributors’
}).addTo(this.mymap);

this.mymap.on('click', this.get_lat_lng);

methods: {
    get_lat_lng(e) { //获取经纬度
        L.popup()
            .setLatLng(e.latlng)
            .setContent(e.latlng.toString())
            .openOn(this.mymap);
    },
}

5. 聚合

https://github.com/Leaflet/Leaflet.markercluster/tree/93bf5408ad84b74ea42f55ccb6ca0450daa41427#usage

npm install leaflet.markercluster
import 'leaflet.markercluster/dist/leaflet.markercluster.js'
import 'leaflet.markercluster/dist/MarkerCluster.Default.css'

  var markerClusterGroup = L.markerClusterGroup();
    this.palace.marker_ary.map((item, index) => { // 标志 加载到 图层组
        let layer = L.marker([item.lng, item.lat], {
                icon: Icon,
                data: item,
                type: "market"
            })
            .bindTooltip(item.tool_tip)
            .bindPopup(item.pop_up)
            .addTo(this.palace.layer_group);

        layer.on('click', e => {
            this.palace.layer_group.eachLayer(item => {
                if (item.options.type == "market") {
                    item.setIcon(Icon);
                }
            })
            layer.setIcon(IconHover);
        });
        layer.on('mouseover', (e) => {
            layer.setIcon(IconHover);
        });
        layer.on('mouseout', () => {
            layer.setIcon(Icon);
        });

         markers.addLayer(layer);
    })
 this.palace.layer_group.addTo(this.mymap); //图层组加载到 地图上

this.mymap.addLayer(markers);

 <!-- 聚合弹出层 -->
  <div id="select-popup" class="scrollbar">
    <ul v-for='(value,key) in polymerize_data' v-if="value.data.length" :key='key'>
      <h3>{{value.name}}</h3>
      <li v-for='(item,index) in value.data' :key='index' @click='fly_to_place(item)'>{{index+1}}.{{item.options.data.pop_up}}</li>
    </ul>
  </div>
  
  
 let popup = document.getElementById('select-popup');
    this.polymerize_popup_click = L.popup({ //点击 聚合 弹出框
      closeButton: false,
      offset: [0, -5],
      minWidth: 300,
      className: 'select-popup'
    }).setContent(popup).setLatLng([0, 0]);

6. 标记

6.1 L.Icon.extend

let LeafIcon = L.Icon.extend({
    options: {
        shadowUrl: '',
        iconSize: [38, 95],
        shadowSize: [50, 64],
        iconAnchor: [22, 94],
        shadowAnchor: [4, 62],
        popupAnchor: [-3, -76] // 弹出框弹出位置,相对于图标锚点
    }
});

let greenIcon = new LeafIcon({
    iconUrl: './static/css/images/leaf-green.png'
})

L.marker([51.5, -0.09], {
    icon: greenIcon
}).addTo(this.mymap).bindPopup("I am a green leaf.");

6.2 L.icon

let greenIcon = L.icon({
    iconUrl: 'static/image/icon/marker-icon-red.png',
    shadowUrl: 'leaf-shadow.png',
    iconAnchor: [10, 14],  //图标的“指示地理位置的锚点”的坐标(相对于其左上角)
    。 以便图标显示准确位于标记的地理位置。
    如果指定大小,则iconAnchor默认为图标中心点,
    也可以在带有负边距的CSS中设置。
    iconSize: [20, 28],
    // shadowSize: [50, 64], // size of the shadow
    // shadowAnchor: [4, 62], // the same for the shadow
    // popupAnchor: [-3, -76] // point from which the popup should open relative to the iconAnchor
  });

7. marker circle polygon 扇形

iconAnchor 默认以 经纬度为圆心,右下-;
offset 左上-

7.1 L.marker

L.marker([51.5, -0.09]).addTo(this.mymap) // 标志 <LatLng>
.bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup();

let layer = L.marker([item.lng, item.lat], {
  icon: Icon,
  data: item,
  type: "marker"
})
.bindTooltip(item.tool_tip)
.bindPopup(item.pop_up)
.addTo(this.layer_control_obj.layer_group);

7.2 marker用html显示

js调用vue methods方法 window.markerPopup_close = this.markerPopup_close;

let myIcon = L.divIcon({
    html: `<div class="show_detail_item">
          <span style="margin-right:10px;"></span>
          <span style="position:absolute;top:10px;right:10px;cursor:pointer;" onclick="markerPopup_close()">x</div>
      </div>
      <div class="show_detail_item">
          <span style="margin-right:10px;">发震时刻 :</span>
          <span class="">${item.QUAKETIME}</div>
      </div>`,
    iconAnchor: [10, 10],
    className: ''
})


let markerS = L.marker([this.initMap.lat, this.initMap.lng], {
    icon: myIcon
}).addTo(this.myMap);

markerS.on('click', () => {
      typhoon_monitor_show_detail(this.routeCoords[0].length - 1);
    });
markerS.on('mouseover', () => {
  // typhoon_monitor_show_detail(this.routeCoords[0].length - 1);
});

markerS.on("click", () => {
  console.log("click");
});

7.3 L.circle


L.circle([51.508, -0.11], { // 圆形 LatLng
    color: 'green',
    fillColor: '#ccc',
    fillOpacity: 0.5,
    radius: 600 //半径
}).bindPopup("这是一个圆形").addTo(this.mymap);

7.4 L.polygon

dashOffset: “2”,
dashArray: “2,2” 虚线

L.polygon([ // 多边形  LatLng
    [51.509, -0.08],
    [51.503, -0.06],
    [51.51, -0.047],
    [51.52, -0.049]
]).bindPopup("这是一个多边形").addTo(this.mymap);

// zoom the map to the polyline
map.fitBounds(polyline.getBounds())

7.5 画圆 另一种方法

计算圆的边缘所有点

var radius = 2;
var parts = [];
for (var i = 0; i < 180; i++) {
  var radians = (i + 1) * Math.PI / 180;
  parts[i] = [
  Math.cos(radians) * radius + parseInt(this.initMap.lat),
  Math.sin(radians) * radius + parseInt(this.initMap.lng)];
}

L.polygon(parts, {
  color: 'green'
}).addTo(this.myMap);

7.6 已知一个经纬度,半径,仰角,求另一个经纬度

扇形 弧度和角度的换算关系如下:
1弧度=180/π度
1度=π/180弧度
也就是说,180度=π 弧度

 /**
     *
     * @param center 中心点 数组
     * @param radius 半径 km
     * @param startAngle 起始角度
     * @param endAngle 终止角度
     * @param pointNum 圆弧上点的个数
     */
    getPoints(center, radius, startAngle, endAngle, pointNum) {
      var sin;
      var cos;
      var x;
      var y;
      var angle;
      var points = new Array();
      points.push(center);
      for (var i = 0; i <= pointNum; i++) {
        angle = startAngle + (endAngle - startAngle) * i / pointNum;
        sin = Math.sin(angle * Math.PI / 180);
        cos = Math.cos(angle * Math.PI / 180);
        y = parseFloat(center[0]) + parseFloat(radius * cos);
        x = parseFloat(center[1]) + parseFloat(radius * sin);
        points[i] = [y, x];
      }
      var point = points;
      point.push(center);
      return point;
    },

8. 缩放级别

0-17级别,禁止地图缩放 minZoom:3,maxZoom:3

this.mymap = L.map('mapid', {
    // minZoom: 0,
    // maxZoom: 1,
    zoomDelta: 0.25,
    zoomSnap: 0
})
this.mymap.setView([0, 0], 0);

L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
    // attribution: cartodbAttribution
}).addTo(this.mymap);

// 通过向L.Control.Scale地图添加a 并平移到赤道和北纬60°,
//我们可以看到比例因子如何加倍。
// L.Control.Scale显示适用于地图中心点的比例。
//在高缩放级别,比例变化非常小,并且不明显。
L.control.scale().addTo(this.mymap);

// setInterval(() => {
//     this.mymap.setView([0, 0]);
//     setTimeout(() => {
//         this.mymap.setView([60, 0]);
//     }, 2000);
// }, 4000);

// 使用超时缩放水平之间交替0和1自动:
// setInterval(() => {
//     this.mymap.setZoom(0);
//     setTimeout(() => {
//         this.mymap.setZoom(1);
//     }, 2000);
// }, 4000);

var ZoomViewer = L.Control.extend({
    onAdd: () => {
        var gauge = L.DomUtil.create('div');
        gauge.style.width = '200px';
        gauge.style.background = 'rgba(255,255,255,0.5)';
        gauge.style.textAlign = 'left';
        this.mymap.on('zoomstart zoom zoomend', (ev) => {
            gauge.innerHTML = '缩放级别: ' + this.mymap.getZoom();
        })
        return gauge;
    }
});
(new ZoomViewer).addTo(this.mymap);

// 其他设置缩放的方法是:
// setView(center, zoom),这也设置了地图中心
// flyTo(center, zoom),就像setView一个流畅的动画
// zoomIn()/zoomIn(delta),默认情况下delta放大缩放级别1
// zoomOut()/zoomOut(delta),默认情况下缩小delta缩放级别1
// setZoomAround(fixedPoint, zoom),在保持点固定的同时设置缩放级别(滚轮缩放的功能)
// fitBounds(bounds),自动计算缩放以适合地图上的矩形区域
// 变焦缩放
// var map = L.map('map', {
//     zoomSnap: 0.25
// });

9. 图层

9.1 声明图层组

this.typhoon_range_group = L.layerGroup();
this.myMap.addLayer(this.typhoon_range_group);

L.control.layers(baseLayers, overlays, ).addTo(map);

9.2 加载到图层组

 L.polygon(points, {
  color: type == 1 ? "#fdf200" : "rgb(247, 122, 6)",
  fillColor: type == 1 ? "rgb(210, 205, 45)" : "rgb(192, 121, 55)",
  fillOpacity: 0.2,
}).addTo(this.typhoon_range_group)
var layers=[];  
for(var i = 0;i< result.length;i++){  
    var layer = new L.marker([ result[i].lat, result[i].lng ]);  
    layers.push(layer);  
}

var myGroup=L.layerGroup(layers);  
maps.addLayer(myGroup);  

myGroup.clearLayers();  

this.dotList.map((item, index) => {
    let layer = null;
     layer = L.marker([item.WD, item.JD], {
        icon: myIconHover,
        data: item
      });
    this.market_group.addLayer(layer);
  });
},

9.3 清空图层组

contain_group(group) { //是否含有图层组
  if(!group){
      return false;
  }
  let num = 0;
  group.eachLayer(() => {
    num++
  });
  return num;
},

if (this.common.containGroup(this.yjglGroup)) {
    this.yjglGroup.clearLayers()
}


this.typhoon_range_group.eachLayer(item => {
      this.typhoon_range_group.removeLayer(item)
    })
显隐
this.myMap.removeLayer(this.ycysLayer);
this.myMap.addLayer(this.ycysLayer);

marker
this.ycysLayer.eachLayer(item => {
     item.setOpacity(0);
})

this.myMap.eachLayer(layer => {
// 清空所有的图层
layer.remove();
});

 this.marketGroup.clearLayers();
----------------
geoJson 中的marker 不能用 setOpacity

9.4 遍历图层组

this.ycysLayer.eachLayer(item => {
    if (obj.options.data.id == item.options.data.id) {
      item.setIcon(IconHover);
    }
})

10. pop框

10.1 pop框关闭

markerPopup_move: null, //移动到 marker 弹出框
关闭popup

this.myMap.closePopup(this.markerPopup);

this.markerPopup.removeFrom(this.map)
this.$nextTick(() => {
    $(".placeTipClose").click(() => {
        this.myMap.closePopup()
    })
})
  
  
let content = `<div class="" >
  <div class="placeTipTitle flex justify-content-space-between" style="font-weight: bold;">
      <span>${item.name}</span>
      <span class="placeTipClose">×</span>
  </div>
  <div class="placeTipContent ">
      <span style="margin-right:10px;">人口 :</span>
      <span class="">${item.people_num} 人</div>
  </div>
   <div class="placeTipContent ">
      <span style="margin-right:10px;">居住面积:</span> 
      <span class="">${item.live_area} km²</div>
  </div>
</div`;

this.$nextTick(() => {
$(".placeTipClose").click(() => {
  this.myMap.closePopup();
});
});
          

10.2 pop框弹出

this.markerPopup_move = L.popup({
  //移动到 marker 弹出框
  closeOnClick: false,
  closeButton: false,
  offset: [0, -7.5],
  className: "marker-popup"
});

this.markerPopup_move
.setLatLng([item.WD, item.JD])
.setContent(`<div class="tip">${item.JCDW}</div>`)
.openOn(this.myMap);

  

11. 进行地图位移

    MapMove() {
      let currentCenter = this.myMap.getCenter(),
        currentZoom = this.myMap.getZoom();
      let lat = currentCenter.lat,
        lng = currentCenter.lng;
      this.$nextTick(() => {
        this.myMap.flyTo([lat, lng], currentZoom, {
          duration: 0.01
        });
        console.log("进行地图位移", lat, lng, currentZoom);
      });
    },

12. 地图位移问题 3857 4326

mapboxGL 地图瓦片地图有 3857 开发
所以对应的地图 也用3857

 this.myMap.fitBounds(this.polyline.getBounds(), {
    //   paddingTopLeft: [100, 100],
    //   paddingBottomRight: [200, 100],
    // })
    

13. mapboxGL获取地图瓦片编号

this.$http
    .get(
      "地图瓦片地址",
      {
        params: {}
      }
    )
    .then(res => {
      console.log("res", res);
      this.myMap.flyTo([res.data.center[1], res.data.center[0]], 21.5);
      this.deviceUnderPainting = L.mapboxGL({
        accessToken: "no-token",
        style: res.data,
        interactive: true
      }).addTo(this.myMap);
      var mapboxMap = this.deviceUnderPainting.getMapboxMap();
      mapboxMap.on("load", () => {
        mapboxMap.on("click", e => {
          let TilesAty = mapboxMap.queryRenderedFeatures(e.point);
          //这里是个数组  注意
        });
      });
    });

14 图片

14.1 插入地图图片 画点


14.2 图片地图

var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg', 
imageBounds = [[30.712216, 104.22655], [30.773941, 104.12544]]; 
L.imageOverlay(imageUrl, imageBounds).addTo(map);

15. geoJSON

  this.palace_layer_border = L.geoJSON([geojson_data.palace], {
        //故宫边际线 加载到 图层组 L.geoJSON 没有 setOpacity这个方法
        style: geojson_data.palace.style
      });
      this.myMap.addLayer(this.palace_layer_border);

16. 切换地图 地图显示不全

 if (val.state) {
        window.L.Util.requestAnimFrame(
            this.mapDT.map.invalidateSize,
            this.mapDT.map,
            !1,
            this.mapDT.map._container
        );
    } else {
        window.L.Util.requestAnimFrame(
            this.mapDTCE.map.invalidateSize,
            this.mapDTCE.map,
            !1,
            this.mapDTCE.map._container
        );
    }

17. imageOverlay

 // calculate the edges of the image, in coordinate space
// let southWest = map.unproject([0, img.height], map.getMaxZoom() - 1);
// let northEast = map.unproject([img.width, 0], map.getMaxZoom() - 1);
// eslint-disable-next-line
// let bounds = new L.LatLngBounds(southWest, northEast);
-----------------------------------------
let map = this.myMap;
let imageUrl = this.imgUrl;
let img = new Image();
img.src = this.imgUrl;
img.onload = function(e) {
    let imageBounds = [[0, 0], [1, img.width / img.height]];
    // eslint-disable-next-line
    L.imageOverlay(imageUrl, imageBounds).addTo(map);
    map.fitBounds([imageBounds]);
    map.setMaxBounds(imageBounds);
};

18. internet 查看地图类型

wmts 天地图瓦片

b3dm  三维建筑模型

terrain dem
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值