<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width
    <title>自定义</title>
    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css"/>
    <link rel="stylesheet" href="../../layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="../../layuiadmin/style/admin.css" media="all">
    <link rel="stylesheet" type="text/css" href="../../layuiadmin/style/roadBook.css" />
    <style>
	     html,body,.map{
			    height: 99%;
			    width: 100%;
			}
		.dev{
		    width: 98%;
		    left: 1%;
		    position: absolute;
		    z-index: 10086;
		    top: 85px;
		    background: #fff;
		    /*height: 42px;*/
		    line-height: 40px;
		    padding: 0 15px;
		    font-size: 12px;
		    box-shadow: 0 1px 3px #606060;
		}
</style>
</head>
<body>
<div class="layui-map">
    <div class="map">
        <div id="container"></div>
        <div id="panel"></div>
        <div class="loading" style="display: none"><img src="../../layuiadmin/views/images/loading-1.gif" alt=""></div>
    </div>
</div


<script src="../../layuiadmin/common/jquery.js"></script>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=高德KEY&plugin=AMap.MouseTool,AMap.Riding"></script>
<script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
<script type="text/javascript" src="https://cache.amap.com/lbs/static/addToolbar.js"></script>
<script src="http://webapi.amap.com/ui/1.1/main.js?v=1.1.1"></script>
<script>
 /**
 *************************************************************************地图***************************************************************************************
 *************************************************************************操作***************************************************************************************
 *************************************************************************开始***************************************************************************************
 **/
/****
 * 1、初始化地图
 * 2、添加点
 * 3、给添加的点一个编号
 * 4、构建骑行规划路径
 * 5、推拽点并进行路线重新规划
 * 6、插入点并进行路线重新规划
 * 8、删除点并进行路线重新规划
 * ****/
var routeMarker = [], //路线点
    markerSum = [], marker_sum = 0,//marker点及对应值
    marker_sums,
    markers = [], marker,
    markerContent,
    clickListener,
    currentMarker,
    markerType,
    routeLineIds,
    dragendType,//是否为修改路书
    routeLine,//当前规划的路线
    routeLines = [],//规划路线
    insertMarkerType = false,
    colorArray=['#259CED','#6B37FC','#ED6581','#FF9641','#878787','#00b8a7','#4CAF50','#cc5d35','#b14aff','#2c8993',],
    color=[],
    currentColor
    $("body").on("mouseenter", ".custom-content-marker", function () {
        $(this).find('.sum').show();
        $(this).find('.close-btn').show();
    });
    $("body").on("mouseleave", ".custom-content-marker", function () {
        $(this).find('.sum').hide();
        $(this).find('.close-btn').hide();
    });
    var lnglat = new AMap.LngLat(104.065565, 30.658546);

    var map = new AMap.Map("container", {
        center: lnglat,
        zoom: 14,
        resizeEnable: true
    });
    /***************
     ******画********
     ******点********
     ***************/
        //创建右键菜单

    var menu = new ContextMenu(map);

    //自定义菜单类
    function ContextMenu(map) {
        var me = this;
        //地图中添加鼠标工具MouseTool插件
        this.mouseTool = new AMap.MouseTool(map);
        this.contextMenuPositon = null;
        var content = [];
        content.push("<div class='info context_menu'>");
        content.push("  <p class='split_line' onclick='menu.distanceMeasureMenu()'>距离量测</p>");
        content.push("  <p onclick='menu.addMarkerMenu()'>添加标记</p>");
        content.push("</div>");
        //通过content自定义右键菜单内容
        this.contextMenu = new AMap.ContextMenu({isCustom: true, content: content.join('')});
        //地图绑定鼠标右击事件——弹出右键菜单
        map.on('rightclick', function (e) {
            me.contextMenu.open(map, e.lnglat);
            me.contextMenuPositon = e.lnglat; //右键菜单位置
        });
    }

    //自定义标记内容
    function markerContentHtml() {
        if (routeMarker.length == 0) {
            markerContent = '<div class="custom-content-marker">' +
                '   <div>' +
                '       <img src="../../layuiadmin/views/images/match/start.png" alt="">' +
                '       <span class="sum sum' + marker_sum + '" style="display: none">' + marker_sum + '</span>' +
                '   </div>' +
                '</div>';
        } else {
            markerContent = '<div class="custom-content-marker">' +
                '   <div><img src="http://a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png" alt=""><span class="sum sum' + marker_sum + '">' + marker_sum + '</span></div>' +
                '   <div class="close-btn" onclick="clearMarker(this)">X</div>' +
                '</div>';
        }
    }

    ContextMenu.prototype.distanceMeasureMenu = function () {  //右键菜单距离量测
        this.mouseTool.rule();
        this.contextMenu.close();
    };
    ContextMenu.prototype.addMarkerMenu = function () {  //右键菜单添加Marker标记
        dragendType = ''
        markerType = 'addMarker'
        markerContentHtml();
        markerSum.push(marker_sum)
        marker_sum += 1
        this.mouseTool.close();
        routeMarker.push(this.contextMenuPositon)
        addMarker(this.contextMenuPositon)
        console.log(this.contextMenuPositon)
        markers.push(marker)
        if (routeMarker.length > 1) {
            $('.loading').show();
            for (let i = routeMarker.length - 1; i < routeMarker.length; i++) {
                var startingPoint = [routeMarker[i - 1].lng, routeMarker[i - 1].lat];
                var endPoint = [routeMarker[i].lng, routeMarker[i].lat];
            }
            ridingPlan(startingPoint, endPoint)
            setTimeout(function () {
                $('.loading').hide();
            }, 300)
        }
        this.contextMenu.close();
    };

    /***************
     *** marker ***
     ******添加*******
     ***************/
    function addMarker(markers) {
        if (markerType == 'insertMarker') {//插入点
            markerContent = '<div class="custom-content-marker">' +
                '   <div>' +
                '       <img src="http://a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png" alt="">' +
                '       <span class="sum sum' + marker_sums + '" style="display: none">' + marker_sums + '</span>' +
                '   </div>' +
                '   <div class="close-btn" onclick="clearMarker(this)">X</div>' +
                '</div>';
        }
        marker = new AMap.Marker({
            map: map,
            content: markerContent,
            position: markers, //基点位置
            draggable: true,
            offset: new AMap.Pixel(-13, -30)
        });
        dragend()
    }

    /***************
     ******拖拽*******
     ******事件*******
     ***************/
    function dragend() {
        let startingPoint;
        let endPoint;
        let endPoint2;
        $("body").on("mouseenter", ".custom-content-marker", function () {//获取当前拖拽点
            currentMarker = $(this).find('.sum').text();
        });
        clickListener = AMap.event.addListener(marker, "dragend", function (e) {//推拽后修改当前marker点的值

            console.log(e.lnglat)
            $('.loading').show();
            dragendType = 'dragend'
            markerType = 'markerDragend'
            $.each(routeMarker, function (key, item) {
                if (currentMarker == key) {
                    routeMarker[currentMarker] = e.lnglat
                }
                return false
            })
            if (routeMarker.length == 1) {
                $('.loading').hide();
                return false
            }
            if (routeMarker.length - 1 == currentMarker) {//终点
                map.remove(routeLines[routeLines.length - 1]);//删除之前的路线
                startingPoint = [routeMarker[routeMarker.length - 2].lng, routeMarker[routeMarker.length - 2].lat];//重新赋值当前起点
                endPoint = [routeMarker[routeMarker.length - 1].lng, routeMarker[routeMarker.length - 1].lat];//重新赋值当前终点
                routeLineIds = routeMarker.length - 2
                let template = routeLine;
                ridingPlan(startingPoint, endPoint)//重新加载当前路径
                let interval = setInterval(function () {
                    if (template !== routeLine) {
                        routeLines.splice(routeLines.length - 1, 1, routeLine);//重新加载后替换数组中的路线
                        clearInterval(interval);
                        $('.loading').hide();
                    }
                }, 200);
            } else if (0 == currentMarker) { //起点
                map.remove(routeLines[0]);//删除之前的路线
                routeLines[0].routeLineId = 0
                startingPoint = [routeMarker[0].lng, routeMarker[0].lat];//重新赋值当前起点
                endPoint = [routeMarker[1].lng, routeMarker[1].lat];//重新赋值当前终点
                routeLineIds = 0
                let template = routeLine;
                ridingPlan(startingPoint, endPoint)//重新加载当前路径
                let interval = setInterval(function () {
                    if (template !== routeLine) {
                        routeLines.splice(0, 1, routeLine);//重新加载后替换数组中的路线
                        clearInterval(interval);
                        $('.loading').hide();
                    }
                }, 200);
            } else {//中间点
                let flag = true;
                map.remove(routeLines[currentMarker - 1]);//删除之前的路线
                map.remove(routeLines[currentMarker]);//删除之前的路线
                startingPoint = [routeMarker[currentMarker - 1].lng, routeMarker[currentMarker - 1].lat]//重新赋值当前起点
                endPoint = [routeMarker[currentMarker].lng, routeMarker[currentMarker].lat]//重新赋值当前终点
                endPoint2 = [routeMarker[currentMarker - (-1)].lng, routeMarker[currentMarker - (-1)].lat]//重新赋值当前终点
                routeLineIds = currentMarker - 1
                let template = routeLine;
                ridingPlan(startingPoint, endPoint);//重新加载当前路径
                let interval1 = setInterval(function () {
                    if (template !== routeLine) {
                        routeLines.splice(currentMarker - 1, 1, routeLine);//重新加载后替换数组中的路线
                        clearInterval(interval1);
                        template = routeLine;
                        if (flag) {
                            routeLineIds = currentMarker
                            ridingPlan(endPoint, endPoint2);//重新加载当前路径
                            flag = false;
                        }
                        let interval2 = setInterval(function () {
                            if (template !== routeLine) {
                                routeLines.splice(currentMarker, 1, routeLine);//重新加载后替换数组中的路线
                                clearInterval(interval2);
                                $('.loading').hide();
                            }
                        }, 200);
                    }
                }, 200);
            }
        });
    }

    /***************
     ******画********
     ******线********
     ***************/
    //骑行导航
    function ridingPlan(startingPoint, endPoint) {
        let riding = new AMap.Riding({
            hideMarkers: true
        });
        riding.search(startingPoint, endPoint, function (status, result) {
            if (status === 'complete') {
                if (result.routes && result.routes.length) {
                    var path = parseRouteToPath(result.routes[0]);
                    routeLine = new AMap.Polyline({
                        path: path,
                        isOutline: true,
                        outlineColor: currentColor,
                        borderWeight: 1,
                        strokeWeight: 5,
                        cursor: 'pointer',
                        showDir: true,//是否显示箭头
                        strokeColor: currentColor, // 线颜色
                        lineJoin: 'round' // 折线拐点的绘制样式
                    })
                    if (markerType == 'addMarker') {//创建点
                        routeLine.routeLineId = routeLines.length
                        routeLines.push(routeLine);
                    } else if (markerType == 'markerDragend') {//拖拽点
                        routeLine.routeLineId = routeLineIds
                    } else if (markerType == 'insertMarker') {//插入点
                        routeLine.routeLineId = routeLineIds
                    } else if (markerType == 'delMarker') {//删除点
                        routeLine.routeLineId = routeLineIds
                    }
                    insertMarker();
                    routeLine.setMap(map)
                }
            }
        });
    }

    // 解析RidingRoute对象,构造成AMap.Polyline的path参数需要的格式
    // RidingResult对象结构参考文档 https://lbs.amap.com/api/javascript-api/reference/route-search#m_RideRoute
    function parseRouteToPath(route) {
        var path = []
        for (var i = 0, l = route.rides.length; i < l; i++) {
            var step = route.rides[i]
            for (var j = 0, n = step.path.length; j < n; j++) {
                path.push(step.path[j])//路线上的所有点
            }
        }
        return path
    }


    /***************
     *****插入*******
     ******点********
     * 1、绑定线的点击事件
     * 2、添加点
     ***************/
    function insertMarker() {
        AMap.event.addListener(routeLine, "click", function (e) {
            markerType = 'insertMarker'
            dragendType = 'dragend'
            $('.loading').show();
            let startingPoint, endPoint, endPoint2;
            let flag = true;
            insertMarkerType = true;
            let routeLineId = e.target.routeLineId;//获取线的id(操作的是那一条线)
            routeLineIds = routeLineId;
            console.log(routeLineId)
            marker_sums = parseInt(routeLineId) + 1;
            markerSum.splice(parseInt(routeLineId) + 1, 0, parseInt(routeLineId) + 1);//重新加载后替换数组中的marker值
            routeMarker.splice(parseInt(routeLineId) + 1, 0, e.lnglat);//重新加载后替换数组中的marker值
            for (let i = markerSum.length - 1; i >= marker_sums; i--) {
                markerSum[i] = i;
                $('.sum' + i).text(i + 1)
                $('.sum' + i).attr("class", "sum sum" + (i + 1));
                if (i === marker_sums) {
                    break;
                }
            }
            marker_sum = markerSum.length
            setTimeout(function () {
                let pro = new Promise((resolve, reject) => {
                    let routeLineMarker = [e.lnglat.getLng(), e.lnglat.getLat()]//插入点的坐标位置
                    addMarker(routeLineMarker)
                    resolve(marker)
                })
                pro.then((data) => {
                    markers.splice(parseInt(routeLineId) + 1, 0, data);//重新加载后插入的路线
                })

                map.remove(e.target);//删除当前点击的线
                startingPoint = [routeMarker[routeLineId].lng, routeMarker[routeLineId].lat]//重新赋值当前起点
                endPoint = [routeMarker[parseInt(routeLineId) + 1].lng, routeMarker[parseInt(routeLineId) + 1].lat]//重新赋值当前终点
                endPoint2 = [routeMarker[parseInt(routeLineId) + 2].lng, routeMarker[parseInt(routeLineId) + 2].lat]//重新赋值当前终点
                let template = routeLine;
                ridingPlan(startingPoint, endPoint);//重新加载当前路径
                let interval1 = setInterval(function () {
                    if (template !== routeLine) {
                        routeLines.splice(routeLineId, 1, routeLine);//重新加载后替换数组中的路线
                        clearInterval(interval1);
                        template = routeLine;
                        if (flag) {
                            ridingPlan(endPoint, endPoint2);//重新加载当前路径
                            flag = false;
                        }
                        let interval2 = setInterval(function () {
                            if (template !== routeLine) {
                                routeLines.splice(parseInt(routeLineId) + 1, 0, routeLine);//重新加载后插入的路线
                                $.each(routeLines, function (key, item) {
                                    if (key >= parseInt(routeLineIds) + 1) {
                                        routeLines[key].routeLineId = key
                                    }
                                })
                                clearInterval(interval2);
                                $('.loading').hide();
                            }
                        }, 200);
                    }
                }, 200);
            }, 200)
        });
    }

    /***************
     *****清除*******
     ***marker点****
     ***************/
    function clearMarker(e) {
        markerType = 'delMarker'
        let clearMarker = $(e).siblings().find('.sum').text();
        $('.loading').show();
        $.each(markers, function (key, item) {
            if (key === parseInt(clearMarker)) {
                map.remove(item);
            }
        })
        if (parseInt(clearMarker) == markers.length - 1) {//终点
            map.remove(routeLines[routeLines.length - 1]);//删除当前点击的线
            markers.splice(markers.length - 1, 1);
            markerSum.splice(markerSum.length - 1, 1);
            routeMarker.splice(routeMarker.length - 1, 1)
            routeLines.splice(routeLines.length - 1, 1);
            marker_sum = markerSum.length
            setTimeout(function () {
                $('.loading').hide();
            }, 300)
        } else {//途经点
            let pro = new Promise((resolve, reject) => {
                map.remove(routeLines[parseInt(clearMarker)]);//删除当前点前的线
                map.remove(routeLines[parseInt(clearMarker) - 1]);//删除当前点后的线
                markers.splice(parseInt(clearMarker), 1);//删除数组中的marker点
                markerSum.splice(parseInt(clearMarker), 1);
                routeMarker.splice(parseInt(clearMarker), 1)
                routeLines.splice(parseInt(clearMarker) - 1, 1);
                $.each(markerSum, function (key, item) {
                    if (key >= parseInt(clearMarker)) {
                        markerSum[key] = key
                        $('.sum' + (key + 1)).text(key)
                        $('.sum' + (key + 1)).attr("class", "sum sum" + key);
                    }

                })
                $.each(routeLines, function (key, item) {
                    if (key >= parseInt(clearMarker) - 1) {
                        routeLines[key].routeLineId = key
                    }
                })
                resolve();
            })
            pro.then((data) => {
                let startingPoint = [routeMarker[parseInt(clearMarker) - 1].lng, routeMarker[parseInt(clearMarker) - 1].lat];//重新赋值当前起点
                let endPoint = [routeMarker[parseInt(clearMarker)].lng, routeMarker[parseInt(clearMarker)].lat];//重新赋值当前终点
                routeLineIds = routeLines[parseInt(clearMarker) - 1].routeLineId
                let template = routeLine;
                ridingPlan(startingPoint, endPoint)//重新加载当前路径
                let interval = setInterval(function () {
                    if (template !== routeLine) {
                        routeLines.splice(parseInt(clearMarker) - 1, 1, routeLine);//重新加载后替换数组中的路线
                        marker_sum = markerSum.length
                        $('.loading').hide();
                        clearInterval(interval);
                    }
                }, 200);
            })
        }
    }
</script>
</body>
</html>