<style>
    .markers_labels {
        margin-left: -24px !important;
        margin-top: -43px !important;
    }

    .gm-svpc,
    .gm-style-mtc,
    .gm-style-cc {
        display: none;
    }

    .classA {
        background-size: 700px 1600px;
        background-position: 0px -1200px;
        width: 34px;
        height: 34px;
        position: absolute;
        left: -16px;
        top: -16px;
    }

    .labels {
        width: 30px;
        height: 30px;
        position: relative;
        bottom: -200px;
    }
</style>

<template>
    <div style="height:100%;">
        <div id="map_canvas" style="height: 100%; width: 100%"></div>
    </div>
</template>
<script>
    export default {
        props: ["locationArray", "type"],
        name: 'tripMap',
        data() {
            return {
                directions: new google.maps.DirectionsService(), //获取路线请求的服务
                renderer: new google.maps.DirectionsRenderer(), //
                polyline: {}, //线路
                map: {},
                icons: {
                    trafficImage: "http://imgfile.oytour.com/static/location_01.png",
                    hotelImage: "http://imgfile.oytour.com/static/location_hotel.png",
                    scenicImage: "http://imgfile.oytour.com/static/location_scenic.png",
                    planeImage: "http://imgfile.oytour.com/static/location_plane.png"
                },
                markerArray: [], //标记数组
            }
        },
        watch: {
            locationArray(newValue, old) {
                this.mapBuild()
            }
        },
        created() {

        },
        destroyed: function () {

        },
        mounted() {
            this.mapBuild() //初始化实例之后调用
        },
        methods: {
            // 地图实例
            mapBuild() {
                let _this = this;
                this.markerArray = [];
                if (this.locationArray && this.locationArray.length > 0) {
                    let lat = parseFloat(this.locationArray[0].lat)
                    let lng = parseFloat(this.locationArray[0].lng)
                    let center = {
                        lng: lng,
                        lat: lat
                    }
                    //创建地图实例,zoom是缩放比例
                    this.map = new google.maps.Map(document.getElementById('map_canvas'), {
                        zoom: 7,
                        center: center,
                        mapTypeId: google.maps.MapTypeId.ROADMAP,
                        gestureHandling: 'greedy'
                    });
                    this.renderer.setMap(this.map);
                    // 线条设置
                    var polyOptions = {
                        strokeColor: '#000000', // 颜色
                        strokeOpacity: 1.0, // 透明度
                        strokeWeight: 2 // 宽度
                    }
                    this.polyline = new google.maps.Polyline(polyOptions);
                    this.polyline.setMap(this.map); // 装载

                    let allPoints = [];
                    //去掉重复的数据
                    this.locationArray.forEach((x, index) => {
                        if (x.lat && x.lng) {
                            let obj = {
                                location: x.lat + ',' + x.lng,
                                type: x.type,
                                name: x.name,
                                isFly: x.isFly,
                                trafficType: x.trafficType
                            }
                            if (this.type == 1) {
                                if (!_this.checkItemIsExists(allPoints, obj)) {
                                    allPoints.push(obj);
                                }
                            } else {
                                if (!_this.checkItemIsExists(allPoints, obj, 2)) {
                                    allPoints.push(obj);
                                }
                            }
                        }
                    });
                    this.calcRoute(allPoints)
                }
            },
            checkItemIsExists(arr, checkItem, type) {
                var isExists = false;
                for (var i = 0; i < arr.length; i++) {
                    if (type) {
                        if (arr[i].location == checkItem.location && !isExists && arr[i].type == checkItem.type) {
                            isExists = true;
                        }
                    } else {
                        if (arr[i].location == checkItem.location && !isExists) {
                            isExists = true;
                        }
                    }

                }
                return isExists;
            },
            // 创建路径规划
            calcRoute: function (waypoints) {
                let _this = this;
                var startArray = waypoints[0].location.split(',');
                let lat = parseFloat(startArray[0]);
                let lng = parseFloat(startArray[1]);
                this.map.setCenter(new google.maps.LatLng(lat, lng));
                this.map.setZoom(10);
                //全部
                if (this.type == 1) {
                    this.drawDrivingRute(waypoints);
                    waypoints.forEach((item, index) => {
                        this.addMarker(item, index + 1);
                    });
                }
                //每天
                else {
                    for (var i = 0; i < waypoints.length - 1; i++) {
                        var currentItem = waypoints[i];
                        var nextItem = waypoints[i + 1];
                        if (currentItem && currentItem.trafficType == 4) {
                            this.drawWalkRoute(currentItem.location, nextItem.location);
                        } else {
                            var newArray = [];
                            newArray.push(currentItem);
                            newArray.push(nextItem);
                            this.drawDrivingRute(newArray);
                        }
                        if (i == 0) {
                            this.addMarker(currentItem, i + 1);
                        } else {
                            var preitem = waypoints[i - 1];
                            var startArray = preitem.location.split(',');
                            var currentArray = currentItem.location.split(',');
                            var currentdistance = this.CalcDistance(currentArray[0], currentArray[1], startArray[0],
                                startArray[1]);
                            this.addMarker(currentItem, i + 1, currentdistance);
                            if (i == waypoints.length - 2) {
                                var nextArray = nextItem.location.split(',');
                                var nextdistance = this.CalcDistance(nextArray[0], nextArray[1], currentArray[0],
                                    currentArray[1]);
                                this.addMarker(nextItem, i + 2, nextdistance);
                            }
                        }
                    }
                }
            },
            //画驾车路线图
            drawDrivingRute(array) {
                for (var i = 0; i < array.length; i++) {
                    var form_loc = array[i].location.split(',');
                    var path = this.polyline.getPath(); //获取线条的坐标
                    path.push(new google.maps.LatLng(form_loc[0], form_loc[1])); //为线条添加标记坐标
                }
            },
            addMarker(obj, title, distance) {
                var loc = obj.location.split(',');
                //生成标记图标
                var image = {}
                var type = obj.type;
                var isFly = obj.isFly;
                //交通
                if (type == 1) {
                    image = {
                        url: this.icons.trafficImage, // image is 512 x 512
                        scaledSize: new google.maps.Size(30, 40),
                    };
                }
                //住宿
                if (type == 3) {
                    image = {
                        url: this.icons.hotelImage,
                        scaledSize: new google.maps.Size(40, 40),
                    }
                }
                //景点
                if (type == 2) {
                    image = {
                        url: this.icons.scenicImage,
                        scaledSize: new google.maps.Size(35, 45),
                    }
                }
                //飞机
                if (isFly == 1) {
                    image = {
                        url: this.icons.planeImage,
                        scaledSize: new google.maps.Size(30, 30),
                    }
                }
                let marker = new MarkerWithLabel({
                    position: new google.maps.LatLng(loc[0], loc[1]),
                    icon: image, //标记自定义图标
                    draggable: false, //不可拖动
                    map: this.map, //地图实例 
                    labelContent: title, //label的内容
                    labelAnchor: new google.maps.Point(0, 0), //label的位置,可以调
                    labelClass: "labels", // the CSS class for the label
                    labelStyle: {
                        background: '#fff',
                        borderRadius: '50%',
                        marginLeft: '-10px',
                        marginTop: '-35px',
                        width: '19px',
                        height: '19px',
                        textAlign: 'center',
                        lineHeight: '20px'
                    }
                });
                //景点
                if (type == 2) {
                    var str = '<div>' + obj.name + '</div>';
                    if (distance) {
                        str += '<br/><div>' + distance + 'KM<div>'
                    }
                    let infowindow = new google.maps.InfoWindow({
                        content: str,
                        size: new google.maps.Size(50, 50)
                    });

                    infowindow.open(this.map, marker);
                    marker.addListener('click', function () {
                        infowindow.close();
                    })
                }
                if (type == 3 || type == 2 || isFly == 1) {
                    marker.labelContent = ''
                    marker.labelStyle = 'background:transparent'
                }
            },
            //步行路线请求内容
            drawWalkRoute(from_g, to_g) {
                var request = {
                    origin: from_g,
                    destination: to_g,
                    travelMode: google.maps.DirectionsTravelMode.WALKING,
                    provideRouteAlternatives: true,
                    transitOptions: {}
                };
                var _this = this;
                this.directions.route(request, function (response, status) { //绘制路线
                    if (status == google.maps.DirectionsStatus.OK) {
                        _this.renderer.setDirections(response);
                        _this.renderer.setMap(_this.map);
                        _this.renderer.setOptions({
                            suppressMarkers: true
                        });
                    } else {
                        renderer.setMap(null);
                    }
                });
            },
            getRad(d) {
                return d * Math.PI / 180.0;
            },
            //计算两点之间的距离
            CalcDistance(lat1, lng1, lat2, lng2) {
                var EARTH_RADIUS = 6378137.0; //单位M
                var radLat1 = this.getRad(lat1);
                var radLat2 = this.getRad(lat2);
                var a = radLat1 - radLat2;
                var b = this.getRad(lng1) - this.getRad(lng2);
                var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) *
                    Math.pow(Math.sin(b / 2), 2)));
                s = s * EARTH_RADIUS;
                s = Math.round(s * 10000) / 10000.0/1000.0;
                return Math.round(s);
            }
        },
    }
</script>