Leafletjs-- drawing points, lines, polygons

Leafletjs learning

A large part of a recent project requirements and are associated with indoor maps, learn about.

gif Pianman image loading, and then Tucao about Jane book, to be a build directory is it so difficult?

0. Other

1. On the Map Control

  • Baidu map, high moral maps are not very friendly in terms of indoor maps, which is a problem most of the Map control, focus on the problem is there is no way to make use of the system users to add their own map, there may be other technologies, but I do not know ah ~;

  • About indoor maps, 3Dmap the effect is relatively good, but I have not come into contact with, but it seems there is no better way to learn, find to do all indoor 3Dmaps are charging, the focus here refers to all. Want to make their own, they may use canvas+ D3js+ Treejsand the like, more trouble ah ~

  • Leafletjs Is completely free, the focus is completely free, there may be some function above but less than free people, ah, and more plug-ins, as well as the disadvantage is almost all in English, check documents more difficult.

2. The combined effect of the project point, line, area

  • Here's the point, line and area are drawn in advance, the corresponding coordinate points stored in the database, and finally get unified display on this page;

  • Demand here is the point == supplies and personnel , line == safe route , area == monitoring range , all point, line and area map to be binding and binding alarm events, once an event is triggered, then display the corresponding point, line, area.

.Gif effect

Renderings .png

3. Route Map

All operations are based on map

// 最主要的是这一步,下面请求操作是根据业务需求添加
var maplet = L.map('map', {
            crs: L.CRS.Simple,
            minZoom: -2,
            zoomControl: false
        });

 var bounds = [
            [0, 0],
            [1021.5, 1023]
        ];
        var imageObj = new Image();
        var image = L.imageOverlay("", bounds).addTo(maplet);

// 请求数据,拿到地图的 URL,这里的地图数据在地图管理模块添加完成
mymap(mapid)
function mymap(mapid) {
            $.ajax({
                url: localStorage.baseUrl + `/Map/GetMapByMapId?TOKEN=${localStorage.token}&MAP_ID=${mapid}`,
                async: true,
                type: 'GET',
                dataType: "json",
                success: function (data) {
                    console.log(data)
                    var url = localStorage.temp + data.rows[0].URL;
                    imageObj.src = url;
                    init(url)
                }
            })

        }

// 布置地图
        function init(url) {
            imageObj.onload = function () {
                x = imageObj.width;
                y = imageObj.height;
                image.setUrl(imageObj.src).setBounds([[0, 0], [y, x]])
                console.log(x, y)
                maplet.setView([y / 2, x / 2], 0);
            }
        }

4. point operation (custom Marker)

Strictly speaking, the entire control of the operating point is not drawn, you can draw a circle, but here is not round, with the draw Marker point display

  • First, the definition of an icon ( icon) Object
// 最后是根据坐标点来用图标显示,图标的属性可以自定义
var CustomerIcon = L.Icon.extend({
            options: {
             // 图标图片的地址
                iconUrl: '../../images/new/xiaofangdiliweizhi.svg',
              // 图标阴影的地址
                shadowUrl: '../../images/new/xiaofangdiliweizhi.svg',
              // 图标大小
                iconSize: [38, 95],
              // 图标偏离的位置
                shadowSize: [50, 64],
              // 图标阴影的大小
                iconAnchor: [20, 65]
            }
        });
  • By clicking on the event creation Marker, access point coordinates
// 创建地图时的 maplet ,添加点击事件
maplet.on('click', (ev) => {
            console.log(ev)
            // 创建 marker
            let marker = new L.Marker(ev.latlng, {
                // 图标
                icon: new CustomerIcon()
            }).addTo(maplet)

            // 打印点的横纵坐标
            console.log(ev.latlng.lat,ev.latlng.lng)
            // 根据需求,横纵坐标点 push 进数组
            var mark = []
            mark.push(ev.latlng.lat)
            mark.push(ev.latlng.lng)
            // 保存到数据库的函数
            layop(mark)
        })
  • effect
    Coordinates .gif

5. Draw Line

Draw lines drawn essentially the same point, ultimate goal is to obtain an array of point coordinates

  • Examples plot line
// 动态绘线主要涉及到三个事件:click,dbclick,mousemove。
// click确定线的折点,dbclick确定线的终点,mousemove绘制鼠标移动过程中图形的变化。

var points=[]
    var lines=new L.polyline(points)
    var tempLines=new L.polyline([])
    map.on('click', onClick);    //点击地图
    map.on('dblclick',onDoubleClick);


    //map.off(....) 关闭该事件

    function onClick(e)
    {

        points.push([e.latlng.lat,e.latlng.lng])
        lines.addLatLng(e.latlng)
        map.addLayer(lines)
        map.addLayer(L.circle(e.latlng,{color:'#ff0000',fillColor:'ff0000',fillOpacity:1}))
        map.on('mousemove',onMove)//双击地图

    }
    function onMove(e) {
        if(points.length>0) {
            ls=[points[points.length-1],[e.latlng.lat,e.latlng.lng]]
            tempLines.setLatLngs(ls)
            map.addLayer(tempLines)
        }
    }

    function onDoubleClick(e)
    {
        L.polyline(points).addTo(map)
        points=[]
        lines=new L.polyline(points)
        map.off('mousemove')
    }
  • Integrated Project Add an event
//绘制线路---start--
// 点击事件,点击后可以绘制
        $("#overlayCompany").on("click", function () {
            mapopen = true;
        })

var linesline = new L.polyline([])
var tempLines = new L.polyline([], {
            dashArray: 10
        })

maplet.on('click', onClick); //点击地图
maplet.on('dblclick', onDoubleClick);
maplet.on('mousemove', onMove);//双击地图

function onClick(e) {
            if (mapopen) {
                pointsline.push([e.latlng.lat, e.latlng.lng])
                linesline.addLatLng(e.latlng)
                maplet.addLayer(linesline)
                maplet.addLayer(L.circle(e.latlng, {
                    color: '#ff0000', fillColor: 'ff0000', fillOpacity: 1
                }))
                maplet.on('mousemove', onMove)
            }
        }

function onMove(e) {
            if (mapopen) {
                if (pointsline.length > 0) {
                    lsline = [pointsline[pointsline.length - 1], [e.latlng.lat, e.latlng.lng]]
                    tempLines.setLatLngs(lsline)
                    maplet.addLayer(tempLines)
                }
            }
        }

// 鼠标双击事件(双击绘制线结束)
function onDoubleClick(e) {
            if (mapopen) {
                var polygon = L.polyline(pointsline).addTo(maplet)
                ploverlays.push({polygon})
                overlays = pointsline.slice(0, pointsline.length - 1);
                // 坐标点数组,主要的就是获取这个坐标点数组,下面的操作根据需求进行
                pointsline = []

                linesline.remove()
                tempLines.setLatLngs([]);
                linesline = new L.polyline(pointsline)
                mapopen = false;

                // 根据需求处理坐标点形式
                var polygon2 = "";
                overlays.forEach(function (item, index) {
                    polygon2 += item[0] + "-" + item[1] + ",";
                })
                polygon2 = polygon2.split(",");
                var polygonnew = polygon2.slice(0, polygon2.length - 1).join(",")
                console.log(polygonnew)

                    // 添加函数等需求
                    optiontype = "add";
                    $("#subregion").text("提交");
                    initmodal()
                    $("#editregion").modal({
                        backdrop: 'static',
                        keyboard: false
                    });
                  $("#mapid").val(''+mapfloor+'');
                  $("#region").val(''+polygonnew+'');
            }
        }
  • effect
    Draw lines .gif
    Line coordinate .png

6. Draw faces (polygons)

Sketch line drawing surface are essentially the same, the main point is to obtain the coordinates

  • Example of drawing polygons
    var points=[]
    var lines=new L.polyline([])
    var tempLines=new L.polyline([],{dashArray:5})
    
    map.on('click', onClick);    //点击地图
    map.on('dblclick',onDoubleClick);
    map.on('mousemove',onMove)//双击地图

    //map.off(....) 关闭该事件

    function onClick(e)
    {
        points.push([e.latlng.lat,e.latlng.lng])
        lines.addLatLng(e.latlng)
        map.addLayer(tempLines)
        map.addLayer(lines)
        map.addLayer(L.circle(e.latlng,{color:'#ff0000',fillColor:'ff0000',fillOpacity:1}))

    }
    function onMove(e) {
        if(points.length>0) {
            ls=[points[points.length-1],[e.latlng.lat,e.latlng.lng],points[0]]
            tempLines.setLatLngs(ls)
            // map.addLayer(tempLines)
        }
    }

    function onDoubleClick(e)
    {
        L.polygon(points).addTo(map)
        points=[]
        //map.removeLayer(tempLines)
        //tempLines.remove()
        lines.remove()
        tempLines.remove()
        lines=new L.polyline([])
    }
  • effect
    Regional results show .gif

7. Summary

The above operation is drawing to get the coordinates of points stored in the database, but will eventually need to coordinate access point to show

  • Get points show
// 上面异步获取数据 pointdata ,里面包含坐标点信息
for (let i = 0; i < pointdata.length; i++) {
                        // 坐标点
                        let matpoint = pointdata[i].POSITION ? pointdata[i].POSITION.split(",") : [];
                        console.log(matpoint)

                        let maticon = pointdata[i].ICON

                        // 图标
                        var myicon = '' + maticon + ''
                        var iconmat = new L.Icon({
                            iconUrl: '../../images/new/' + myicon + '.svg',
                            shadowUrl: '../../images/new/' + myicon + '.svg',
                            iconSize: [25, 41],
                            iconAnchor: [12, 41],
                            popupAnchor: [1, -34],
                            shadowSize: [41, 41]
                        })

                        var markermat = null;
                        markermat = L.marker(matpoint, {
                            icon: iconmat
                        });
                        // 显示名字
                        markermat.bindTooltip(pointdata[i].ITEM_NAME ? pointdata[i].ITEM_NAME : pointdata[i].LABEL_ID).openTooltip();
                        // 显示弹窗
                        var popupmat = L.popup({
                            maxWidth: 700,
                            maxHeight: 600
                        }).setLatLng(matpoint)
                        
                        buildings.addLayer(markermat);
                    }
                    buildings.addTo(maplet)
  • Get line display

    Effect the flow line (line dynamic rendering), you need to add widget leaflet-ant-path.js

// 异步获取到相应数据后,执行函数 line()
function line(longLatList) {
            if (path) {
                maplet.removeLayer(path);
            }
           // 流动线效果(动态线渲染),需要添加插件 ‘leaflet-ant-path.js’
            var antPath = L.polyline.antPath;
            var path = antPath(longLatList, {
                "paused": false,     //暂停  初始化状态
                "reverse": false,  //方向反转
                "delay": 150,    //延迟,数值越大效果越缓慢
                "dashArray": [20, 35], //间隔样式
                "weight": 10,   //线宽
                "opacity": 0.5,  //透明度
                "color": "red", //颜色
                "pulseColor": "#FFFFFF"  //块颜色
            });
            path.addTo(maplet).bindPopup("green to red");
            // 缩放地图到折线所在区域
            maplet.fitBounds(path.getBounds());
        }
  • Get polygon display

    polArr array of points, which can be multi-dimensional arrays to [ [[a1 ], [ a2]], [[b1 ], [ b2]],...... ]form can

// polArr 为点的数组,可以是多维数组,以 [ [[a1 ], [ a2]], [[b1 ], [ b2]],...... ] 形式都可以
function getRegion(polArr) {
            // console.log(polArr)
            var polygon = L.polygon(polArr, {
                color: '#000eff',
                fillColor: '#0000ed',
                weight: 0.2
            }).addTo(maplet);
        }

The above is combined with personal items to organize the example of the official website is much clear!

Point a praise chant!

Guess you like

Origin www.cnblogs.com/jry199506/p/11370069.html