• leaflet的使用


    layui.define(['jquery'], function (exports) {
        let $ = layui.jquery;
    
        function leafLetHelper() {
    
        }
    
        leafLetHelper.prototype.render = function (option) {
            this.config = $.extend({}, this.defaultConfig, option);
    
            this.initLeafLetMap();
    
            if ((this.config.imgUrl || "") !== "") {
                this.setLeatletImage(this.config.imgUrl);
            }
    
            var _that = this;
    
            return {
                changImage: function (imgUrl, successCallback) {
                    // 更换图片
                    _that.config.imgUrl = imgUrl;
                    _that.setLeatletImage(_that.config.imgUrl, successCallback);
                },
                addMarker: function (option) {
                    // 添加标记
                    return _that.addMarker(option);
                },
                isDisabledMapClick: function (isClick) {
                    // 是否允许地图点击,设置地图事件时,有效
                    _that.config.disabledMapClick = isClick;
                },
                clearAllMarker: function () {
                    // 清楚所有标记
                    _that.clearAllMarker();
                },
                removeSingleMarker: function (id) {
                    _that.removeSingleMarker(id);
                },
                addPopup: function (option) {
                    // 标记点添加弹框
                    _that.addPopup(option);
                },
                getImgSize: function () {
                    // 图片原始大小
                    return _that.imgSize;
                },
                setMapBounds: function () {
                    _that.map.fitBounds(_that.bounds);
                    _that.map.setZoom(-1);
                },
                closePopup: function () {
                    // 关闭弹框
                    _that.closePopup();
                },
                openMarkerPopup: function (id) {
                    _that.openMarkerPopup(id);
                },
                addTextMarker: function (option) {
                    return _that.addTextMarker(option);
                },
                assignBeginIDRemoveMarker: function (beginId) {
                    _that.assignBeginIDRemoveMarker(beginId);
                },
                assignBeginIDSetMarkerIcon: function (option) {
                    _that.assignBeginIDSetMarkerIcon(option);
                },
                bindDrawPolyline: function (option) {
                    _that.bindDrawPolyline(option);
                },
                clearAllPolyline: function () {
                    _that.clearAllPolyline();
                },
                bindMapClick: function (callback) {
                    _that.bindMapClick(callback);
                },
                addPolyline: function (option) {
                    _that.addPolyline(option);
                }
            };
        }
    
        // leaflet map对象
        leafLetHelper.prototype.map = undefined;
        // leaflet 图片范围
        leafLetHelper.prototype.bounds = undefined;
        // leaflet 图片对象
        leafLetHelper.prototype.image = undefined;
        // leaflet 弹框对象
        leafLetHelper.prototype.popup = undefined;
        // 点标记
        leafLetHelper.prototype.markers = {};
        // 图片原始大小
        leafLetHelper.prototype.imgSize = [];
        // 默认配置
        leafLetHelper.prototype.defaultConfig = {
            mapContainer: "map", // map容器(标签ID)
            imgUrl: "", // 图层路径
        };
        // 当前配置
        leafLetHelper.prototype.config = {};
    
        /**
         * @description: 获取图片真实宽高
         * @param {String} data.imgUrl 图片路径
         * @param {CallableFunction} data.callback 回掉函数
         * @return {VoidFunction}
         */
        leafLetHelper.prototype.getImgSize = function (data) {
            if ((data.imgUrl || "") === "") {
                console.error("图片地址错误");
                return;
            }
    
            var img = new Image();
            img.src = data.imgUrl;
            // 如果图片被缓存,则直接返回缓存数据
            if (img.complete) {
                data.callback(img.width, img.height);
            } else {
                img.onload = function () {
                    data.callback(img.width, img.height);
                };
            }
        };
    
        /**
         * @description: 获取guid
         * @return {String}
         */
        leafLetHelper.prototype.newGuid = function () {
            return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
                var r = (Math.random() * 16) | 0,
                    v = c == "x" ? r : (r & 0x3) | 0x8;
                return v.toString(16);
            });
        };
    
        /**
         * @description: 初始化地图对象
         * @return {VoidFunction}
         */
        leafLetHelper.prototype.initLeafLetMap = function () {
            this.map = L.map(this.config.mapContainer, {
                crs: L.CRS.Simple,
                minZoom: -5,
                maxZoom: 5,
            });
    
            if (typeof this.config.mapClick === "function") {
                var _that = this;
    
                this.map.on("click", function (e) {
                    if (_that.config.disabledMapClick) {
                        return;
                    }
    
                    _that.config.mapClick(e);
                });
            }
        };
    
        /**
         * 绑定地图点击
         * @param {any} callback
         */
        leafLetHelper.prototype.bindMapClick = function (callback) {
            this.map.off("click");
            this.map.off('contextmenu');
            this.map.on("click", function (e) {
                callback && callback(e);
            });
        }
    
        // 线路缓存
        leafLetHelper.prototype.polylines = {};
        // 画线辅助变量
        leafLetHelper.prototype.polyline;
        leafLetHelper.prototype.drawing = false;
    
        /**
         * 画线
         */
        leafLetHelper.prototype.bindDrawPolyline = function (option) {
            let latlngs = [];
            let realPoint = [];
            let realline = undefined;
            let _this = this;
            option = option || {};
    
            let lineStyle = option.lineStyle || {
                weight: '10',
                color: 'red'
            };
    
            this.map.off('click')
            this.map.on('click', function (e) {
                // 开始画之前
                if (!_this.drawing) {
                    option.beforeDraw && option.beforeDraw();
                }
    
                if (!_this.drawing) {
                    // 开始画
                    _this.drawing = true;
                    $('.leaflet-grab').addClass('leaflet-draw')
    
                    _this.map.on('mousemove', function (e) {
                        realPoint[1] = [e.latlng.lat, e.latlng.lng]
                        if (realline) {
                            //realline.remove();
                            realline.setLatLngs(realPoint);
                        }
                        else {
                            realline = L.polyline(realPoint, lineStyle).addTo(_this.map);
                        }
                    })
    
                }
    
                // 记录画的每个点
                latlngs.push([e.latlng.lat, e.latlng.lng])
    
                // 显示画的线
                if (latlngs.length > 1) {
                    if (_this.polyline) {
                        //_this.polyline.remove();
                        _this.polyline.addLatLng([e.latlng.lat, e.latlng.lng]);
                    }
                    else {
                        _this.polyline = L.polyline(latlngs, lineStyle).addTo(_this.map);
                    }
                }
    
                realPoint[0] = latlngs[latlngs.length - 1];
            })
    
            this.map.off('contextmenu')
            this.map.on('contextmenu', function (e) {
                if (!_this.drawing) {
                    return;
                }
                // 结束画线
                _this.drawing = false;
    
                // 最后一次显示线
                let line = L.polyline(latlngs, lineStyle).addTo(_this.map);
    
                // 保存线路坐标
                option.id = option.id || _this.newGuid();
                _this.polylines[option.id] = line;
    
                // 点击事件
                if (option.click) {
                    line.on('click', function (e) {
                        option.click({
                            id: option.id,
                            latlngs: line.getLatLngs(),
                            polyline: line
                        });
    
                        L.DomEvent.stopPropagation(e);
                    })
                }
    
                // 返回坐标
                option.completeDraw && option.completeDraw({
                    id: option.id,
                    latlngs: line.getLatLngs(),
                    polyline: line
                })
    
                _this.map.off('mousemove')
    
                // 清空当前正在画的记录
                if (_this.polyline) {
                    _this.polyline.remove();
                    _this.polyline = undefined;
                    latlngs = [];
                }
    
                if (realline) {
                    realline.remove();
                    realline = undefined;
                    realPoint = [];
                }
    
                $('.leaflet-grab').removeClass('leaflet-draw')
            })
        }
    
        /**
         * 添加线
         * @param {object} option
         */
        leafLetHelper.prototype.addPolyline = function (option) {
            let _this = this;
    
            // 样式
            let lineStyle = option.lineStyle || {
                weight: '10',
                color: 'red'
            };
    
            let line = L.polyline(option.latlngs, lineStyle).addTo(_this.map);
    
            // 保存线路坐标
            option.id = option.id || _this.newGuid();
    
            _this.polylines[option.id] = line;
    
            if (option.click) {
                line.on('click', function (e) {
                    option.click({
                        id: option.id,
                        latlngs: line.getLatLngs(),
                        polyline: line
                    });
    
                    L.DomEvent.stopPropagation(e);
                })
            }
    
            // 返回坐标
            option.complete && option.complete({
                id: option.id,
                latlngs: line.getLatLngs(),
                polyline: line
            })
        }
    
        /**
         * 按ID删除线
         * @param {any} key
         */
        leafLetHelper.prototype.removeSinglePlyline = function (id) {
            if (this.polylines[id]) {
                this.polylines[id].remove();
                delete this.polylines[id];
            }
        }
    
        /**
         * 删除全部线条
         */
        leafLetHelper.prototype.clearAllPolyline = function () {
            let _this = this;
            $.each(_this.polylines, function (i, item) {
                item.remove();
            })
    
            _this.polylines = {};
        }
    
        /**
         * @description: 设置图层
         * @param {String} 图片路径
         * @return {VoidFunction}
         */
        leafLetHelper.prototype.setLeatletImage = function (imgUrl, callback) {
            var _that = this;
            this.getImgSize({
                imgUrl: imgUrl,
                callback: function (w, h) {
                    _that.bounds = [
                        [0, 0],
                        [h, w],
                    ];
    
                    if (_that.image) {
                        _that.image.setUrl(imgUrl);
                        _that.image.setBounds(_that.bounds);
                    } else {
                        _that.image = L.imageOverlay(imgUrl, _that.bounds).addTo(_that.map);
                        _that.map.fitBounds(_that.bounds);
                    }
    
                    _that.map.setZoom(-1);
    
                    _that.imgSize = [w, h];
    
                    // 限定拖动范围
                    //_that.map.setMaxBounds(_that.bounds)
    
                    // 切换成功后的执行函数
                    if (typeof callback === 'function') {
                        callback(w, h)
                    }
                },
            });
        };
    
        /**
         * @description: 添加标记
         * @param {object} option.icon leaflet icon对象
         * @param {Array} option.position 图标位置
         * @param {String} option.id 标记唯一标识
         * @return {marker} marker对象
         */
        leafLetHelper.prototype.addMarker = function (option) {
            icon = option.icon || {};
    
            var myIcon = L.icon({
                iconUrl: icon.iconUrl || "/images/d_marker.png",
                iconSize: icon.iconSize || [32, 32],
                iconAnchor: icon.iconAnchor || [16, 32],
                popupAnchor: icon.popupAnchor || [0, -32], // 弹框打开得坐标
            });
    
            option.id = option.id || this.newGuid();
    
            var marker = L.marker(option.position, { icon: myIcon }).addTo(this.map);
    
            this.markers[option.id] = marker;
    
            if (typeof option.iconClick === "function") {
                marker.on("click", function (e) {
                    option.iconClick(e, option.data);
                    L.DomEvent.stopPropagation(e);
                });
            }
    
            return marker;
        };
    
        /**
         * @description: 清除所有标记
         * @return {VoidFunction}
         */
        leafLetHelper.prototype.clearAllMarker = function () {
            $.each(this.markers, function (i, item) {
                item.remove();
            });
    
            this.markers = {};
        };
    
        /**
         * @description: 删除指定的marker
         * @param {String} id 唯一标记
         * @return {VoidFunction}
         */
        leafLetHelper.prototype.removeSingleMarker = function (id) {
            var marker = this.markers[id];
    
            if (marker) {
                marker.remove();
            }
    
            delete marker;
        }
    
        /**
         * @description: 按ID起始匹配,删除指定的marker
         * @param {String} beginID ID开头部分
         * @return {VoidFunction}
         */
        leafLetHelper.prototype.assignBeginIDRemoveMarker = function (beginID) {
            var tempMarkerIds = [];
            var _that = this;
    
            $.each(this.markers, function (key, marker) {
                if (key.indexOf(beginID) == 0) {
                    tempMarkerIds.push(key);
    
                    marker.remove();
                }
            })
    
            $.each(tempMarkerIds, function (i, item) {
                delete _that.markers[item];
            })
        }
    
        leafLetHelper.prototype.assignBeginIDSetMarkerIcon = function (option) {
            var tempMarkers = [];
    
            $.each(this.markers, function (key, marker) {
                if (key.indexOf(option.beginId) == 0) {
                    tempMarkers.push(marker);
                }
            })
    
            icon = option.iconSize || {};
    
            icon.iconSize = option.iconSize || [45, 45];
    
            $.each(tempMarkers, function (i, item) {
                var myIcon = item.getIcon()
    
                myIcon.options = {
                    iconUrl: myIcon.options.iconUrl,
                    iconSize: icon.iconSize,
                    iconAnchor: icon.iconAnchor || [icon.iconSize[0] / 2, icon.iconSize[1]],
                    popupAnchor: icon.popupAnchor || [0, -icon.iconSize[1]], // 弹框打开得坐标
                }
    
                item.setIcon(myIcon);
            })
        }
    
        /**
         * @description: 添加弹框(可封装可不封装)
         * @param {layer} layer layer对象
         * @param {String} html 弹框中的内容
         * @param {String} className 自定义样式
         * @param {Boolean} isOpen 是否默认打开
         * @return {VoidFunction}
         */
        leafLetHelper.prototype.addPopup = function (option) {
            //marker, html, className, isOpen, isShowCloseBtn
            var layer = option.layer;
    
            var html;
    
            if (option.html && option.html.jquery) {  // is jQuery对象
                html = option.html[0]
            }
            else {
                html = option.html
            }
    
            this.popup = layer.bindPopup(html, {
                className: option.className || "",
                closeButton: option.isShowCloseBtn === undefined ? true : option.isShowCloseBtn
            });
    
            if (option.isOpen) {
                this.popup.openPopup();
            }
        };
    
        /**
         * @description: 关闭弹框
         * @return {VoidFunction}
         */
        leafLetHelper.prototype.closePopup = function () {
            if (this.popup) {
                this.popup.closePopup();
            }
        }
    
        /**
         * @description: 打开指定marker的弹框
         * @param {String} id marker的唯一标识
         * @return {VoidFunction}
         */
        leafLetHelper.prototype.openMarkerPopup = function (id) {
            var marker = this.markers[id]
    
            if (marker) {
                marker.openPopup();
            }
        }
    
        /**
         * @description: 添加文字marker
         * @param {String} option.className 自定义类名
         * @param {Object} option.html 自定义html内容
         * @param {Number} option.lat 纬度
         * @param {Number} option.lng 经度
         * @param {Function} option.iconClick marker点击事件
         * @return {VoidFunction}
         */
        leafLetHelper.prototype.addTextMarker = function (option) {
            var html = '';
    
            if (option.html && option.html.jquery) {  // is jQuery对象
                html = option.html[0]
            }
            else {
                html = option.html
            }
    
            var myIcon = L.divIcon({
                className: option.className || '',
                html: html || ''
            });
    
            var marker = L.marker([option.lat, option.lng], { icon: myIcon }).addTo(this.map);
    
            if (typeof option.iconClick === "function") {
                marker.on("click", function (e) {
                    option.iconClick(e, option.data);
                });
            }
    
            return marker;
        }
    
        exports('leaflet', new leafLetHelper());
    })
    

      

    岁月无情催人老,请珍爱生命,远离代码!!!
  • 相关阅读:
    [JSOI2008]Blue Mary开公司[李超线段树]
    线段树分治
    满汉全席[2-SAT]
    「一本通 3.5 练习 5」和平委员会
    2-SAT问题
    2019/04/06 BJ省选模拟DAY1
    构造题【随时更
    文本编辑器vim/vi——命令模式
    指令——cat
    指令——history
  • 原文地址:https://www.cnblogs.com/zhoushangwu/p/15006361.html
Copyright © 2020-2023  润新知