Administrator
2022-03-09 303d9b6c50e59bf190e0a3a4083c182dbf1314f8
去除关闭缓冲按钮
3 files modified
4 files added
1 files deleted
2610 ■■■■ changed files
package.json 116 ●●●● patch | view | raw | blame | history
src/components/map/Draw.js 1163 ●●●●● patch | view | raw | blame | history
src/components/map/main.vue 631 ●●●● patch | view | raw | blame | history
src/components/map/main1.vue 329 ●●●●● patch | view | raw | blame | history
src/components/map/main2.vue 270 ●●●●● patch | view | raw | blame | history
src/components/map/tip.vue 25 ●●●●● patch | view | raw | blame | history
src/page/index/tags.vue 8 ●●●● patch | view | raw | blame | history
test.html 68 ●●●●● patch | view | raw | blame | history
package.json
@@ -1,59 +1,59 @@
{
  "name": "saber-admin",
  "version": "2.8.1",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "analyz": "npm_config_report=true npm run build",
    "test:unit": "vue-cli-service test:unit",
    "test:e2e": "vue-cli-service test:e2e"
  },
  "dependencies": {
    "avue-plugin-ueditor": "^0.1.4",
    "axios": "^0.18.0",
    "babel-polyfill": "^6.26.0",
    "classlist-polyfill": "^1.2.0",
    "crypto-js": "^4.0.0",
    "element-ui": "^2.15.1",
    "jquery": "^3.6.0",
    "js-base64": "^2.5.1",
    "js-cookie": "^2.2.0",
    "js-md5": "^0.7.3",
    "mockjs": "^1.0.1-beta3",
    "moment": "^2.29.1",
    "node-gyp": "^5.0.6",
    "nprogress": "^0.2.0",
    "ol": "^6.5.0",
    "olcs": "^2.12.0",
    "pdfobject": "^2.2.7",
    "script-loader": "^0.7.2",
    "vue": "^2.6.10",
    "vue-axios": "^2.1.2",
    "vue-i18n": "^8.7.0",
    "vue-router": "^3.0.1",
    "vue2-countdown": "^1.0.8",
    "vuex": "^3.1.1"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^3.1.1",
    "@vue/cli-plugin-eslint": "^3.1.5",
    "@vue/cli-service": "^3.1.4",
    "chai": "^4.1.2",
    "node-sass": "^4.14.1",
    "sass-loader": "^7.0.1",
    "vue-template-compiler": "^2.5.17",
    "webpack-bundle-analyzer": "^3.0.3"
  },
  "lint-staged": {
    "*.js": [
      "vue-cli-service lint",
      "git add"
    ],
    "*.vue": [
      "vue-cli-service lint",
      "git add"
    ]
  }
}
    "name": "saber-admin",
    "version": "2.8.1",
    "private": true,
    "scripts": {
        "serve": "vue-cli-service serve",
        "build": "vue-cli-service build",
        "lint": "vue-cli-service lint",
        "analyz": "npm_config_report=true npm run build",
        "test:unit": "vue-cli-service test:unit",
        "test:e2e": "vue-cli-service test:e2e"
    },
    "dependencies": {
        "avue-plugin-ueditor": "^0.1.4",
        "axios": "^0.18.0",
        "babel-polyfill": "^6.26.0",
        "classlist-polyfill": "^1.2.0",
        "crypto-js": "^4.0.0",
        "element-ui": "^2.15.1",
        "jquery": "^3.6.0",
        "js-base64": "^2.5.1",
        "js-cookie": "^2.2.0",
        "js-md5": "^0.7.3",
        "mockjs": "^1.0.1-beta3",
        "moment": "^2.29.1",
        "node-gyp": "^5.0.6",
        "nprogress": "^0.2.0",
        "ol": "^6.5.0",
        "olcs": "^2.12.0",
        "pdfobject": "^2.2.7",
        "script-loader": "^0.7.2",
        "vue": "^2.6.10",
        "vue-axios": "^2.1.2",
        "vue-i18n": "^8.7.0",
        "vue-router": "^3.0.1",
        "vue2-countdown": "^1.0.8",
        "vuex": "^3.1.1"
    },
    "devDependencies": {
        "@vue/cli-plugin-babel": "^3.1.1",
        "@vue/cli-plugin-eslint": "^3.1.5",
        "@vue/cli-service": "^3.1.4",
        "chai": "^4.1.2",
        "node-sass": "^4.14.1",
        "sass-loader": "^7.0.1",
        "vue-template-compiler": "^2.5.17",
        "webpack-bundle-analyzer": "^3.0.3"
    },
    "lint-staged": {
        "*.js": [
            "vue-cli-service lint",
            "git add"
        ],
        "*.vue": [
            "vue-cli-service lint",
            "git add"
        ]
    }
}
src/components/map/Draw.js
New file
@@ -0,0 +1,1163 @@
var __extends = (this && this.__extends) || (function() {
    var extendStatics = function(d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] }
                instanceof Array && function(d, b) { d.__proto__ = b; }) ||
            function(d, b) { for (var p in b)
                    if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function(d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
/**
 * @module ol/interaction/Draw
 */
import Circle from 'ol/geom/Circle.js';
import Event from 'ol/events/Event.js';
import EventType from 'ol/events/EventType.js';
import Feature from 'ol/Feature.js';
import GeometryType from 'ol/geom/GeometryType.js';
import InteractionProperty from 'ol/interaction/Property.js';
import LineString from 'ol/geom/LineString.js';
import MapBrowserEvent from 'ol/MapBrowserEvent.js';
import MapBrowserEventType from 'ol/MapBrowserEventType.js';
import MultiLineString from 'ol/geom/MultiLineString.js';
import MultiPoint from 'ol/geom/MultiPoint.js';
import MultiPolygon from 'ol/geom/MultiPolygon.js';
import Point from 'ol/geom/Point.js';
import PointerInteraction from 'ol/interaction/Pointer.js';
import Polygon, { fromCircle, makeRegular } from 'ol/geom/Polygon.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import { FALSE, TRUE } from 'ol/functions.js';
import { always, noModifierKeys, shiftKeyOnly } from 'ol/events/condition.js';
import { boundingExtent, getBottomLeft, getBottomRight, getTopLeft, getTopRight, } from 'ol/extent.js';
import { createEditingStyle } from 'ol/style/Style.js';
import { fromUserCoordinate, getUserProjection } from 'ol/proj.js';
import { squaredDistance as squaredCoordinateDistance } from 'ol/coordinate.js';
/**
 * @typedef {Object} Options
 * @property {import("../geom/GeometryType.js").default} type Geometry type of
 * the geometries being drawn with this instance.
 * @property {number} [clickTolerance=6] The maximum distance in pixels between
 * "down" and "up" for a "up" event to be considered a "click" event and
 * actually add a point/vertex to the geometry being drawn.  The default of `6`
 * was chosen for the draw interaction to behave correctly on mouse as well as
 * on touch devices.
 * @property {import("../Collection.js").default<Feature>} [features]
 * Destination collection for the drawn features.
 * @property {VectorSource} [source] Destination source for
 * the drawn features.
 * @property {number} [dragVertexDelay=500] Delay in milliseconds after pointerdown
 * before the current vertex can be dragged to its exact position.
 * @property {number} [snapTolerance=12] Pixel distance for snapping to the
 * drawing finish. Must be greater than `0`.
 * @property {boolean} [stopClick=false] Stop click, singleclick, and
 * doubleclick events from firing during drawing.
 * @property {number} [maxPoints] The number of points that can be drawn before
 * a polygon ring or line string is finished. By default there is no
 * restriction.
 * @property {number} [minPoints] The number of points that must be drawn
 * before a polygon ring or line string can be finished. Default is `3` for
 * polygon rings and `2` for line strings.
 * @property {import("../events/condition.js").Condition} [finishCondition] A function
 * that takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
 * boolean to indicate whether the drawing can be finished. Not used when drawing
 * POINT or MULTI_POINT geometries.
 * @property {import("../style/Style.js").StyleLike} [style]
 * Style for sketch features.
 * @property {GeometryFunction} [geometryFunction]
 * Function that is called when a geometry's coordinates are updated.
 * @property {string} [geometryName] Geometry name to use for features created
 * by the draw interaction.
 * @property {import("../events/condition.js").Condition} [condition] A function that
 * takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
 * boolean to indicate whether that event should be handled.
 * By default {@link module:ol/events/condition.noModifierKeys}, i.e. a click,
 * adds a vertex or deactivates freehand drawing.
 * @property {boolean} [freehand=false] Operate in freehand mode for lines,
 * polygons, and circles.  This makes the interaction always operate in freehand
 * mode and takes precedence over any `freehandCondition` option.
 * @property {import("../events/condition.js").Condition} [freehandCondition]
 * Condition that activates freehand drawing for lines and polygons. This
 * function takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and
 * returns a boolean to indicate whether that event should be handled. The
 * default is {@link module:ol/events/condition.shiftKeyOnly}, meaning that the
 * Shift key activates freehand drawing.
 * @property {boolean} [wrapX=false] Wrap the world horizontally on the sketch
 * overlay.
 */
/**
 * Coordinate type when drawing points.
 * @typedef {import("../coordinate.js").Coordinate} PointCoordType
 */
/**
 * Coordinate type when drawing lines.
 * @typedef {Array<import("../coordinate.js").Coordinate>} LineCoordType
 */
/**
 * Coordinate type when drawing polygons.
 * @typedef {Array<Array<import("../coordinate.js").Coordinate>>} PolyCoordType
 */
/**
 * Types used for drawing coordinates.
 * @typedef {PointCoordType|LineCoordType|PolyCoordType} SketchCoordType
 */
/**
 * Function that takes an array of coordinates and an optional existing geometry
 * and a projection as arguments, and returns a geometry. The optional existing
 * geometry is the geometry that is returned when the function is called without
 * a second argument.
 * @typedef {function(!SketchCoordType, import("../geom/SimpleGeometry.js").default,
 *     import("../proj/Projection.js").default):
 *     import("../geom/SimpleGeometry.js").default} GeometryFunction
 */
/**
 * Draw mode.  This collapses multi-part geometry types with their single-part
 * cousins.
 * @enum {string}
 */
var Mode = {
    POINT: 'Point',
    LINE_STRING: 'LineString',
    POLYGON: 'Polygon',
    CIRCLE: 'Circle',
};
/**
 * @enum {string}
 */
var DrawEventType = {
    /**
     * Triggered upon feature draw start
     * @event DrawEvent#drawstart
     * @api
     */
    DRAWSTART: 'drawstart',
    /**
     * Triggered upon feature draw end
     * @event DrawEvent#drawend
     * @api
     */
    DRAWEND: 'drawend',
    /**
     * Triggered upon feature draw abortion
     * @event DrawEvent#drawabort
     * @api
     */
    DRAWABORT: 'drawabort',
};
/**
 * @classdesc
 * Events emitted by {@link module:ol/interaction/Draw~Draw} instances are
 * instances of this type.
 */
var DrawEvent = /** @class */ (function(_super) {
    __extends(DrawEvent, _super);
    /**
     * @param {DrawEventType} type Type.
     * @param {Feature} feature The feature drawn.
     */
    function DrawEvent(type, feature) {
        var _this = _super.call(this, type) || this;
        /**
         * The feature being drawn.
         * @type {Feature}
         * @api
         */
        _this.feature = feature;
        return _this;
    }
    return DrawEvent;
}(Event));
export { DrawEvent };
/***
 * @template Return
 * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
 *   import("../Observable").OnSignature<import("../ObjectEventType").Types|
 *     'change:active', import("../Object").ObjectEvent, Return> &
 *   import("../Observable").OnSignature<'drawabort'|'drawend'|'drawstart', DrawEvent, Return> &
 *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("../ObjectEventType").Types|
 *     'change:active'|'drawabort'|'drawend'|'drawstart', Return>} DrawOnSignature
 */
/**
 * @classdesc
 * Interaction for drawing feature geometries.
 *
 * @fires DrawEvent
 * @api
 */
var Draw = /** @class */ (function(_super) {
    __extends(Draw, _super);
    /**
     * @param {Options} options Options.
     */
    function Draw(options) {
        var _this = this;
        var pointerOptions = /** @type {import("./Pointer.js").Options} */ (options);
        if (!pointerOptions.stopDown) {
            pointerOptions.stopDown = FALSE;
        }
        _this = _super.call(this, pointerOptions) || this;
        /***
         * 自定义输入
         */
        _this._coordinate = options.coordinate || function() { return false };
        /***
         * 自定义输出
         */
        _this._coordinateOver = options.coordinateOver || function() { return false };
        /***
         * @type {DrawOnSignature<import("../Observable").OnReturn>}
         */
        _this.on;
        /***
         * @type {DrawOnSignature<import("../Observable").OnReturn>}
         */
        _this.once;
        /***
         * @type {DrawOnSignature<void>}
         */
        _this.un;
        /**
         * @type {boolean}
         * @private
         */
        _this.shouldHandle_ = false;
        /**
         * @type {import("../pixel.js").Pixel}
         * @private
         */
        _this.downPx_ = null;
        /**
         * @type {?}
         * @private
         */
        _this.downTimeout_;
        /**
         * @type {number|undefined}
         * @private
         */
        _this.lastDragTime_;
        /**
         * Pointer type of the last pointermove event
         * @type {string}
         * @private
         */
        _this.pointerType_;
        /**
         * @type {boolean}
         * @private
         */
        _this.freehand_ = false;
        /**
         * Target source for drawn features.
         * @type {VectorSource}
         * @private
         */
        _this.source_ = options.source ? options.source : null;
        /**
         * Target collection for drawn features.
         * @type {import("../Collection.js").default<Feature>}
         * @private
         */
        _this.features_ = options.features ? options.features : null;
        /**
         * Pixel distance for snapping.
         * @type {number}
         * @private
         */
        _this.snapTolerance_ = options.snapTolerance ? options.snapTolerance : 12;
        /**
         * Geometry type.
         * @type {import("../geom/GeometryType.js").default}
         * @private
         */
        _this.type_ = /** @type {import("../geom/GeometryType.js").default} */ (options.type);
        /**
         * Drawing mode (derived from geometry type.
         * @type {Mode}
         * @private
         */
        _this.mode_ = getMode(_this.type_);
        /**
         * Stop click, singleclick, and doubleclick events from firing during drawing.
         * Default is `false`.
         * @type {boolean}
         * @private
         */
        _this.stopClick_ = !!options.stopClick;
        /**
         * The number of points that must be drawn before a polygon ring or line
         * string can be finished.  The default is 3 for polygon rings and 2 for
         * line strings.
         * @type {number}
         * @private
         */
        _this.minPoints_ = options.minPoints ?
            options.minPoints :
            _this.mode_ === Mode.POLYGON ?
            3 :
            2;
        /**
         * The number of points that can be drawn before a polygon ring or line string
         * is finished. The default is no restriction.
         * @type {number}
         * @private
         */
        _this.maxPoints_ =
            _this.mode_ === Mode.CIRCLE ?
            2 :
            options.maxPoints ?
            options.maxPoints :
            Infinity;
        /**
         * A function to decide if a potential finish coordinate is permissible
         * @private
         * @type {import("../events/condition.js").Condition}
         */
        _this.finishCondition_ = options.finishCondition ?
            options.finishCondition :
            TRUE;
        var geometryFunction = options.geometryFunction;
        if (!geometryFunction) {
            var mode_1 = _this.mode_;
            if (mode_1 === Mode.CIRCLE) {
                /**
                 * @param {!LineCoordType} coordinates The coordinates.
                 * @param {import("../geom/SimpleGeometry.js").default|undefined} geometry Optional geometry.
                 * @param {import("../proj/Projection.js").default} projection The view projection.
                 * @return {import("../geom/SimpleGeometry.js").default} A geometry.
                 */
                geometryFunction = function(coordinates, geometry, projection) {
                    var circle = geometry ?
                        /** @type {Circle} */ (geometry) :
                        new Circle([NaN, NaN]);
                    var center = fromUserCoordinate(coordinates[0], projection);
                    var squaredLength = squaredCoordinateDistance(center, fromUserCoordinate(coordinates[coordinates.length - 1], projection));
                    circle.setCenterAndRadius(center, Math.sqrt(squaredLength));
                    var userProjection = getUserProjection();
                    if (userProjection) {
                        circle.transform(projection, userProjection);
                    }
                    return circle;
                };
            } else {
                var Constructor_1;
                if (mode_1 === Mode.POINT) {
                    Constructor_1 = Point;
                } else if (mode_1 === Mode.LINE_STRING) {
                    Constructor_1 = LineString;
                } else if (mode_1 === Mode.POLYGON) {
                    Constructor_1 = Polygon;
                }
                /**
                 * @param {!LineCoordType} coordinates The coordinates.
                 * @param {import("../geom/SimpleGeometry.js").default|undefined} geometry Optional geometry.
                 * @param {import("../proj/Projection.js").default} projection The view projection.
                 * @return {import("../geom/SimpleGeometry.js").default} A geometry.
                 */
                geometryFunction = function(coordinates, geometry, projection) {
                    if (geometry) {
                        if (mode_1 === Mode.POLYGON) {
                            if (coordinates[0].length) {
                                // Add a closing coordinate to match the first
                                geometry.setCoordinates([
                                    coordinates[0].concat([coordinates[0][0]]),
                                ]);
                            } else {
                                geometry.setCoordinates([]);
                            }
                        } else {
                            geometry.setCoordinates(coordinates);
                        }
                    } else {
                        geometry = new Constructor_1(coordinates);
                    }
                    return geometry;
                };
            }
        }
        /**
         * @type {GeometryFunction}
         * @private
         */
        _this.geometryFunction_ = geometryFunction;
        /**
         * @type {number}
         * @private
         */
        _this.dragVertexDelay_ =
            options.dragVertexDelay !== undefined ? options.dragVertexDelay : 500;
        /**
         * Finish coordinate for the feature (first point for polygons, last point for
         * linestrings).
         * @type {import("../coordinate.js").Coordinate}
         * @private
         */
        _this.finishCoordinate_ = null;
        /**
         * Sketch feature.
         * @type {Feature}
         * @private
         */
        _this.sketchFeature_ = null;
        /**
         * Sketch point.
         * @type {Feature<Point>}
         * @private
         */
        _this.sketchPoint_ = null;
        /**
         * Sketch coordinates. Used when drawing a line or polygon.
         * @type {SketchCoordType}
         * @private
         */
        _this.sketchCoords_ = null;
        /**
         * Sketch line. Used when drawing polygon.
         * @type {Feature<LineString>}
         * @private
         */
        _this.sketchLine_ = null;
        /**
         * Sketch line coordinates. Used when drawing a polygon or circle.
         * @type {LineCoordType}
         * @private
         */
        _this.sketchLineCoords_ = null;
        /**
         * Squared tolerance for handling up events.  If the squared distance
         * between a down and up event is greater than this tolerance, up events
         * will not be handled.
         * @type {number}
         * @private
         */
        _this.squaredClickTolerance_ = options.clickTolerance ?
            options.clickTolerance * options.clickTolerance :
            36;
        /**
         * Draw overlay where our sketch features are drawn.
         * @type {VectorLayer}
         * @private
         */
        _this.overlay_ = new VectorLayer({
            source: new VectorSource({
                useSpatialIndex: false,
                wrapX: options.wrapX ? options.wrapX : false,
            }),
            style: options.style ? options.style : getDefaultStyleFunction(),
            updateWhileInteracting: true,
        });
        /**
         * Name of the geometry attribute for newly created features.
         * @type {string|undefined}
         * @private
         */
        _this.geometryName_ = options.geometryName;
        /**
         * @private
         * @type {import("../events/condition.js").Condition}
         */
        _this.condition_ = options.condition ? options.condition : noModifierKeys;
        /**
         * @private
         * @type {import("../events/condition.js").Condition}
         */
        _this.freehandCondition_;
        if (options.freehand) {
            _this.freehandCondition_ = always;
        } else {
            _this.freehandCondition_ = options.freehandCondition ?
                options.freehandCondition :
                shiftKeyOnly;
        }
        _this.addChangeListener(InteractionProperty.ACTIVE, _this.updateState_);
        return _this;
    }
    /**
     * Remove the interaction from its current map and attach it to the new map.
     * Subclasses may set up event handlers to get notified about changes to
     * the map here.
     * @param {import("../PluggableMap.js").default} map Map.
     */
    Draw.prototype.setMap = function(map) {
        _super.prototype.setMap.call(this, map);
        this.updateState_();
    };
    /**
     * Get the overlay layer that this interaction renders sketch features to.
     * @return {VectorLayer} Overlay layer.
     * @api
     */
    Draw.prototype.getOverlay = function() {
        return this.overlay_;
    };
    /**
     * Handles the {@link module:ol/MapBrowserEvent map browser event} and may actually draw or finish the drawing.
     * @param {import("../MapBrowserEvent.js").default} event Map browser event.
     * @return {boolean} `false` to stop event propagation.
     * @api
     */
    Draw.prototype.handleEvent = function(event) {
        if (event.originalEvent.type === EventType.CONTEXTMENU) {
            // Avoid context menu for long taps when drawing on mobile
            event.originalEvent.preventDefault();
        }
        this.freehand_ =
            this.mode_ !== Mode.POINT && this.freehandCondition_(event);
        var move = event.type === MapBrowserEventType.POINTERMOVE;
        var pass = true;
        if (!this.freehand_ &&
            this.lastDragTime_ &&
            event.type === MapBrowserEventType.POINTERDRAG) {
            var now = Date.now();
            if (now - this.lastDragTime_ >= this.dragVertexDelay_) {
                this.downPx_ = event.pixel;
                this.shouldHandle_ = !this.freehand_;
                move = true;
            } else {
                this.lastDragTime_ = undefined;
            }
            if (this.shouldHandle_ && this.downTimeout_ !== undefined) {
                clearTimeout(this.downTimeout_);
                this.downTimeout_ = undefined;
            }
        }
        if (this.freehand_ &&
            event.type === MapBrowserEventType.POINTERDRAG &&
            this.sketchFeature_ !== null) {
            this.addToDrawing_(event.coordinate);
            pass = false;
        } else if (this.freehand_ &&
            event.type === MapBrowserEventType.POINTERDOWN) {
            pass = false;
        } else if (move && this.getPointerCount() < 2) {
            pass = event.type === MapBrowserEventType.POINTERMOVE;
            if (pass && this.freehand_) {
                this.handlePointerMove_(event);
                if (this.shouldHandle_) {
                    // Avoid page scrolling when freehand drawing on mobile
                    event.originalEvent.preventDefault();
                }
            } else if (event.originalEvent.pointerType === 'mouse' ||
                (event.type === MapBrowserEventType.POINTERDRAG &&
                    this.downTimeout_ === undefined)) {
                this.handlePointerMove_(event);
            }
        } else if (event.type === MapBrowserEventType.DBLCLICK) {
            pass = false;
        }
        return _super.prototype.handleEvent.call(this, event) && pass;
    };
    /**
     * Handle pointer down events.
     * @param {import("../MapBrowserEvent.js").default} event Event.
     * @return {boolean} If the event was consumed.
     */
    Draw.prototype.handleDownEvent = function(event) {
        this.shouldHandle_ = !this.freehand_;
        if (this.freehand_) {
            this.downPx_ = event.pixel;
            if (!this.finishCoordinate_) {
                this.startDrawing_(event.coordinate);
            }
            return true;
        } else if (this.condition_(event)) {
            this.lastDragTime_ = Date.now();
            this.downTimeout_ = setTimeout(function() {
                this.handlePointerMove_(new MapBrowserEvent(MapBrowserEventType.POINTERMOVE, event.map, event.originalEvent, false, event.frameState));
            }.bind(this), this.dragVertexDelay_);
            this.downPx_ = event.pixel;
            return true;
        } else {
            this.lastDragTime_ = undefined;
            return false;
        }
    };
    /**
     * Handle pointer up events.
     * @param {import("../MapBrowserEvent.js").default} event Event.
     * @return {boolean} If the event was consumed.
     */
    Draw.prototype.handleUpEvent = function(event) {
        var pass = true;
        if (this.getPointerCount() === 0) {
            if (this.downTimeout_) {
                clearTimeout(this.downTimeout_);
                this.downTimeout_ = undefined;
            }
            this.handlePointerMove_(event);
            if (this.shouldHandle_) {
                var startingToDraw = !this.finishCoordinate_;
                if (startingToDraw) {
                    this.startDrawing_(event.coordinate);
                }
                if (!startingToDraw && this.freehand_) {
                    this.finishDrawing();
                } else if (!this.freehand_ &&
                    (!startingToDraw || this.mode_ === Mode.POINT)) {
                    if (this.atFinish_(event.pixel)) {
                        if (this.finishCondition_(event)) {
                            this.finishDrawing();
                        }
                    } else {
                        this.addToDrawing_(event.coordinate);
                    }
                }
                pass = false;
            } else if (this.freehand_) {
                this.abortDrawing();
            }
        }
        if (!pass && this.stopClick_) {
            event.preventDefault();
        }
        return pass;
    };
    /**
     * Handle move events.
     * @param {import("../MapBrowserEvent.js").default} event A move event.
     * @private
     */
    Draw.prototype.handlePointerMove_ = function(event) {
        this.pointerType_ = event.originalEvent.pointerType;
        if (this.downPx_ &&
            ((!this.freehand_ && this.shouldHandle_) ||
                (this.freehand_ && !this.shouldHandle_))) {
            var downPx = this.downPx_;
            var clickPx = event.pixel;
            var dx = downPx[0] - clickPx[0];
            var dy = downPx[1] - clickPx[1];
            var squaredDistance = dx * dx + dy * dy;
            this.shouldHandle_ = this.freehand_ ?
                squaredDistance > this.squaredClickTolerance_ :
                squaredDistance <= this.squaredClickTolerance_;
            if (!this.shouldHandle_) {
                return;
            }
        }
        if (this.finishCoordinate_) {
            this.modifyDrawing_(event.coordinate);
        } else {
            this.createOrUpdateSketchPoint_(event.coordinate.slice());
        }
    };
    /**
     * Determine if an event is within the snapping tolerance of the start coord.
     * @param {import("../pixel.js").Pixel} pixel Pixel.
     * @return {boolean} The event is within the snapping tolerance of the start.
     * @private
     */
    Draw.prototype.atFinish_ = function(pixel) {
        var at = false;
        if (this.sketchFeature_) {
            var potentiallyDone = false;
            var potentiallyFinishCoordinates = [this.finishCoordinate_];
            var mode = this.mode_;
            if (mode === Mode.POINT) {
                at = true;
            } else if (mode === Mode.CIRCLE) {
                at = this.sketchCoords_.length === 2;
            } else if (mode === Mode.LINE_STRING) {
                potentiallyDone = this.sketchCoords_.length > this.minPoints_;
            } else if (mode === Mode.POLYGON) {
                var sketchCoords = /** @type {PolyCoordType} */ (this.sketchCoords_);
                potentiallyDone = sketchCoords[0].length > this.minPoints_;
                potentiallyFinishCoordinates = [
                    sketchCoords[0][0],
                    sketchCoords[0][sketchCoords[0].length - 2],
                ];
            }
            if (potentiallyDone) {
                var map = this.getMap();
                for (var i = 0, ii = potentiallyFinishCoordinates.length; i < ii; i++) {
                    var finishCoordinate = potentiallyFinishCoordinates[i];
                    var finishPixel = map.getPixelFromCoordinate(finishCoordinate);
                    var dx = pixel[0] - finishPixel[0];
                    var dy = pixel[1] - finishPixel[1];
                    var snapTolerance = this.freehand_ ? 1 : this.snapTolerance_;
                    at = Math.sqrt(dx * dx + dy * dy) <= snapTolerance;
                    if (at) {
                        this.finishCoordinate_ = finishCoordinate;
                        break;
                    }
                }
            }
        }
        return at;
    };
    /**
     * @param {import("../coordinate").Coordinate} coordinates Coordinate.
     * @private
     */
    Draw.prototype.createOrUpdateSketchPoint_ = function(coordinates) {
        if (!this.sketchPoint_) {
            this.sketchPoint_ = new Feature(new Point(coordinates));
            this.updateSketchFeatures_();
        } else {
            var sketchPointGeom = this.sketchPoint_.getGeometry();
            sketchPointGeom.setCoordinates(coordinates);
        }
    };
    /**
     * @param {import("../geom/Polygon.js").default} geometry Polygon geometry.
     * @private
     */
    Draw.prototype.createOrUpdateCustomSketchLine_ = function(geometry) {
        if (!this.sketchLine_) {
            this.sketchLine_ = new Feature();
        }
        var ring = geometry.getLinearRing(0);
        var sketchLineGeom = this.sketchLine_.getGeometry();
        if (!sketchLineGeom) {
            sketchLineGeom = new LineString(ring.getFlatCoordinates(), ring.getLayout());
            this.sketchLine_.setGeometry(sketchLineGeom);
        } else {
            sketchLineGeom.setFlatCoordinates(ring.getLayout(), ring.getFlatCoordinates());
            sketchLineGeom.changed();
        }
    };
    /**
     * Start the drawing.
     * @param {import("../coordinate.js").Coordinate} start Start coordinate.
     * @private
     */
    Draw.prototype.startDrawing_ = function(start) {
        var projection = this.getMap().getView().getProjection();
        this.finishCoordinate_ = start;
        this._coordinate(this.finishCoordinate_)
        if (this.mode_ === Mode.POINT) {
            this.sketchCoords_ = start.slice();
        } else if (this.mode_ === Mode.POLYGON) {
            this.sketchCoords_ = [
                [start.slice(), start.slice()]
            ];
            this.sketchLineCoords_ = this.sketchCoords_[0];
        } else {
            this.sketchCoords_ = [start.slice(), start.slice()];
        }
        if (this.sketchLineCoords_) {
            this.sketchLine_ = new Feature(new LineString(this.sketchLineCoords_));
        }
        var geometry = this.geometryFunction_(this.sketchCoords_, undefined, projection);
        this.sketchFeature_ = new Feature();
        if (this.geometryName_) {
            this.sketchFeature_.setGeometryName(this.geometryName_);
        }
        this.sketchFeature_.setGeometry(geometry);
        this.updateSketchFeatures_();
        this.dispatchEvent(new DrawEvent(DrawEventType.DRAWSTART, this.sketchFeature_));
    };
    /**
     * Modify the drawing.
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @private
     */
    Draw.prototype.modifyDrawing_ = function(coordinate) {
        var map = this.getMap();
        var geometry = this.sketchFeature_.getGeometry();
        var projection = map.getView().getProjection();
        var coordinates, last;
        if (this.mode_ === Mode.POINT) {
            last = this.sketchCoords_;
        } else if (this.mode_ === Mode.POLYGON) {
            coordinates = /** @type {PolyCoordType} */ (this.sketchCoords_)[0];
            last = coordinates[coordinates.length - 1];
            if (this.atFinish_(map.getPixelFromCoordinate(coordinate))) {
                // snap to finish
                coordinate = this.finishCoordinate_.slice();
            }
        } else {
            coordinates = this.sketchCoords_;
            last = coordinates[coordinates.length - 1];
        }
        last[0] = coordinate[0];
        last[1] = coordinate[1];
        this.geometryFunction_(
            /** @type {!LineCoordType} */
            (this.sketchCoords_), geometry, projection);
        if (this.sketchPoint_) {
            var sketchPointGeom = this.sketchPoint_.getGeometry();
            sketchPointGeom.setCoordinates(coordinate);
        }
        if (geometry.getType() === GeometryType.POLYGON &&
            this.mode_ !== Mode.POLYGON) {
            this.createOrUpdateCustomSketchLine_( /** @type {Polygon} */ (geometry));
        } else if (this.sketchLineCoords_) {
            var sketchLineGeom = this.sketchLine_.getGeometry();
            sketchLineGeom.setCoordinates(this.sketchLineCoords_);
        }
        this.updateSketchFeatures_();
    };
    /**
     * Add a new coordinate to the drawing.
     * @param {!PointCoordType} coordinate Coordinate
     * @private
     */
    Draw.prototype.addToDrawing_ = function(coordinate) {
        var geometry = this.sketchFeature_.getGeometry();
        var projection = this.getMap().getView().getProjection();
        var done;
        var coordinates;
        var mode = this.mode_;
        if (mode === Mode.LINE_STRING || mode === Mode.CIRCLE) {
            this.finishCoordinate_ = coordinate.slice();
            coordinates = /** @type {LineCoordType} */ (this.sketchCoords_);
            if (coordinates.length >= this.maxPoints_) {
                if (this.freehand_) {
                    coordinates.pop();
                } else {
                    done = true;
                }
            }
            coordinates.push(coordinate.slice());
            this._coordinate(coordinate.slice())
            this.geometryFunction_(coordinates, geometry, projection);
        } else if (mode === Mode.POLYGON) {
            coordinates = /** @type {PolyCoordType} */ (this.sketchCoords_)[0];
            if (coordinates.length >= this.maxPoints_) {
                if (this.freehand_) {
                    coordinates.pop();
                } else {
                    done = true;
                }
            }
            coordinates.push(coordinate.slice());
            if (done) {
                this.finishCoordinate_ = coordinates[0];
            }
            this.geometryFunction_(this.sketchCoords_, geometry, projection);
        }
        this.createOrUpdateSketchPoint_(coordinate.slice());
        this.updateSketchFeatures_();
        if (done) {
            this.finishDrawing();
        }
    };
    /**
     * Remove last point of the feature currently being drawn. Does not do anything when
     * drawing POINT or MULTI_POINT geometries.
     * @api
     */
    Draw.prototype.removeLastPoint = function() {
        if (!this.sketchFeature_) {
            return;
        }
        var geometry = this.sketchFeature_.getGeometry();
        var projection = this.getMap().getView().getProjection();
        var coordinates;
        var mode = this.mode_;
        if (mode === Mode.LINE_STRING || mode === Mode.CIRCLE) {
            coordinates = /** @type {LineCoordType} */ (this.sketchCoords_);
            coordinates.splice(-2, 1);
            if (coordinates.length >= 2) {
                this.finishCoordinate_ = coordinates[coordinates.length - 2].slice();
                var finishCoordinate = this.finishCoordinate_.slice();
                coordinates[coordinates.length - 1] = finishCoordinate;
                this.createOrUpdateSketchPoint_(finishCoordinate);
            }
            this.geometryFunction_(coordinates, geometry, projection);
            if (geometry.getType() === GeometryType.POLYGON && this.sketchLine_) {
                this.createOrUpdateCustomSketchLine_( /** @type {Polygon} */ (geometry));
            }
        } else if (mode === Mode.POLYGON) {
            coordinates = /** @type {PolyCoordType} */ (this.sketchCoords_)[0];
            coordinates.splice(-2, 1);
            var sketchLineGeom = this.sketchLine_.getGeometry();
            if (coordinates.length >= 2) {
                var finishCoordinate = coordinates[coordinates.length - 2].slice();
                coordinates[coordinates.length - 1] = finishCoordinate;
                this.createOrUpdateSketchPoint_(finishCoordinate);
            }
            sketchLineGeom.setCoordinates(coordinates);
            this.geometryFunction_(this.sketchCoords_, geometry, projection);
        }
        if (coordinates.length === 1) {
            this.abortDrawing();
        }
        this.updateSketchFeatures_();
    };
    /**
     * Stop drawing and add the sketch feature to the target layer.
     * The {@link module:ol/interaction/Draw~DrawEventType.DRAWEND} event is
     * dispatched before inserting the feature.
     * @api
     */
    Draw.prototype.finishDrawing = function() {
        var sketchFeature = this.abortDrawing_();
        if (!sketchFeature) {
            return;
        }
        var coordinates = this.sketchCoords_;
        var geometry = sketchFeature.getGeometry();
        var projection = this.getMap().getView().getProjection();
        if (this.mode_ === Mode.LINE_STRING) {
            // remove the redundant last point
            coordinates.pop();
            this.geometryFunction_(coordinates, geometry, projection);
        } else if (this.mode_ === Mode.POLYGON) {
            // remove the redundant last point in ring
            /** @type {PolyCoordType} */
            (coordinates)[0].pop();
            this.geometryFunction_(coordinates, geometry, projection);
            coordinates = geometry.getCoordinates();
        }
        // cast multi-part geometries
        if (this.type_ === GeometryType.MULTI_POINT) {
            sketchFeature.setGeometry(new MultiPoint([ /** @type {PointCoordType} */ (coordinates)]));
        } else if (this.type_ === GeometryType.MULTI_LINE_STRING) {
            sketchFeature.setGeometry(new MultiLineString([ /** @type {LineCoordType} */ (coordinates)]));
        } else if (this.type_ === GeometryType.MULTI_POLYGON) {
            sketchFeature.setGeometry(new MultiPolygon([ /** @type {PolyCoordType} */ (coordinates)]));
        }
        // First dispatch event to allow full set up of feature
        this.dispatchEvent(new DrawEvent(DrawEventType.DRAWEND, sketchFeature));
        // Then insert feature
        if (this.features_) {
            this.features_.push(sketchFeature);
        }
        if (this.source_) {
            this.source_.addFeature(sketchFeature);
        }
        this._coordinateOver();
    };
    /**
     * Stop drawing without adding the sketch feature to the target layer.
     * @return {Feature} The sketch feature (or null if none).
     * @private
     */
    Draw.prototype.abortDrawing_ = function() {
        this.finishCoordinate_ = null;
        var sketchFeature = this.sketchFeature_;
        this.sketchFeature_ = null;
        this.sketchPoint_ = null;
        this.sketchLine_ = null;
        this.overlay_.getSource().clear(true);
        return sketchFeature;
    };
    /**
     * Stop drawing without adding the sketch feature to the target layer.
     * @api
     */
    Draw.prototype.abortDrawing = function() {
        var sketchFeature = this.abortDrawing_();
        if (sketchFeature) {
            this.dispatchEvent(new DrawEvent(DrawEventType.DRAWABORT, sketchFeature));
        }
    };
    /**
     * Append coordinates to the end of the geometry that is currently being drawn.
     * This can be used when drawing LineStrings or Polygons. Coordinates will
     * either be appended to the current LineString or the outer ring of the current
     * Polygon. If no geometry is being drawn, a new one will be created.
     * @param {!LineCoordType} coordinates Linear coordinates to be appended to
     * the coordinate array.
     * @api
     */
    Draw.prototype.appendCoordinates = function(coordinates) {
        var mode = this.mode_;
        var newDrawing = !this.sketchFeature_;
        if (newDrawing) {
            this.startDrawing_(coordinates[0]);
        }
        /** @type {LineCoordType} */
        var sketchCoords;
        if (mode === Mode.LINE_STRING || mode === Mode.CIRCLE) {
            sketchCoords = /** @type {LineCoordType} */ (this.sketchCoords_);
        } else if (mode === Mode.POLYGON) {
            sketchCoords =
                this.sketchCoords_ && this.sketchCoords_.length ?
                /** @type {PolyCoordType} */ (this.sketchCoords_)[0] :
                [];
        } else {
            return;
        }
        if (newDrawing) {
            sketchCoords.shift();
        }
        // Remove last coordinate from sketch drawing (this coordinate follows cursor position)
        sketchCoords.pop();
        // Append coordinate list
        for (var i = 0; i < coordinates.length; i++) {
            this.addToDrawing_(coordinates[i]);
        }
        var ending = coordinates[coordinates.length - 1];
        // Duplicate last coordinate for sketch drawing (cursor position)
        this.addToDrawing_(ending);
        this.modifyDrawing_(ending);
    };
    /**
     * Initiate draw mode by starting from an existing geometry which will
     * receive new additional points. This only works on features with
     * `LineString` geometries, where the interaction will extend lines by adding
     * points to the end of the coordinates array.
     * This will change the original feature, instead of drawing a copy.
     *
     * The function will dispatch a `drawstart` event.
     *
     * @param {!Feature<LineString>} feature Feature to be extended.
     * @api
     */
    Draw.prototype.extend = function(feature) {
        var geometry = feature.getGeometry();
        var lineString = geometry;
        this.sketchFeature_ = feature;
        this.sketchCoords_ = lineString.getCoordinates();
        var last = this.sketchCoords_[this.sketchCoords_.length - 1];
        this.finishCoordinate_ = last.slice();
        this.sketchCoords_.push(last.slice());
        this.sketchPoint_ = new Feature(new Point(last));
        this.updateSketchFeatures_();
        this.dispatchEvent(new DrawEvent(DrawEventType.DRAWSTART, this.sketchFeature_));
    };
    /**
     * Redraw the sketch features.
     * @private
     */
    Draw.prototype.updateSketchFeatures_ = function() {
        var sketchFeatures = [];
        if (this.sketchFeature_) {
            sketchFeatures.push(this.sketchFeature_);
        }
        if (this.sketchLine_) {
            sketchFeatures.push(this.sketchLine_);
        }
        if (this.sketchPoint_) {
            sketchFeatures.push(this.sketchPoint_);
        }
        var overlaySource = this.overlay_.getSource();
        overlaySource.clear(true);
        overlaySource.addFeatures(sketchFeatures);
    };
    /**
     * @private
     */
    Draw.prototype.updateState_ = function() {
        var map = this.getMap();
        var active = this.getActive();
        if (!map || !active) {
            this.abortDrawing();
        }
        this.overlay_.setMap(active ? map : null);
    };
    return Draw;
}(PointerInteraction));
/**
 * @return {import("../style/Style.js").StyleFunction} Styles.
 */
function getDefaultStyleFunction() {
    var styles = createEditingStyle();
    return function(feature, resolution) {
        return styles[feature.getGeometry().getType()];
    };
}
/**
 * Create a `geometryFunction` for `type: 'Circle'` that will create a regular
 * polygon with a user specified number of sides and start angle instead of a
 * `import("../geom/Circle.js").Circle` geometry.
 * @param {number} [opt_sides] Number of sides of the regular polygon.
 *     Default is 32.
 * @param {number} [opt_angle] Angle of the first point in counter-clockwise
 *     radians. 0 means East.
 *     Default is the angle defined by the heading from the center of the
 *     regular polygon to the current pointer position.
 * @return {GeometryFunction} Function that draws a polygon.
 * @api
 */
export function createRegularPolygon(opt_sides, opt_angle) {
    return function(coordinates, opt_geometry, projection) {
        var center = fromUserCoordinate(
            /** @type {LineCoordType} */
            (coordinates)[0], projection);
        var end = fromUserCoordinate(
            /** @type {LineCoordType} */
            (coordinates)[coordinates.length - 1], projection);
        var radius = Math.sqrt(squaredCoordinateDistance(center, end));
        var geometry = opt_geometry ?
            /** @type {Polygon} */ (opt_geometry) :
            fromCircle(new Circle(center), opt_sides);
        var angle = opt_angle;
        if (!opt_angle && opt_angle !== 0) {
            var x = end[0] - center[0];
            var y = end[1] - center[1];
            angle = Math.atan2(y, x);
        }
        makeRegular(geometry, center, radius, angle);
        var userProjection = getUserProjection();
        if (userProjection) {
            geometry.transform(projection, userProjection);
        }
        return geometry;
    };
}
/**
 * Create a `geometryFunction` that will create a box-shaped polygon (aligned
 * with the coordinate system axes).  Use this with the draw interaction and
 * `type: 'Circle'` to return a box instead of a circle geometry.
 * @return {GeometryFunction} Function that draws a box-shaped polygon.
 * @api
 */
export function createBox() {
    return function(coordinates, opt_geometry, projection) {
        var extent = boundingExtent(
            /** @type {LineCoordType} */
            ([
                coordinates[0],
                coordinates[coordinates.length - 1],
            ]).map(function(coordinate) {
                return fromUserCoordinate(coordinate, projection);
            }));
        var boxCoordinates = [
            [
                getBottomLeft(extent),
                getBottomRight(extent),
                getTopRight(extent),
                getTopLeft(extent),
                getBottomLeft(extent),
            ],
        ];
        var geometry = opt_geometry;
        if (geometry) {
            geometry.setCoordinates(boxCoordinates);
        } else {
            geometry = new Polygon(boxCoordinates);
        }
        var userProjection = getUserProjection();
        if (userProjection) {
            geometry.transform(projection, userProjection);
        }
        return geometry;
    };
}
/**
 * Get the drawing mode.  The mode for mult-part geometries is the same as for
 * their single-part cousins.
 * @param {import("../geom/GeometryType.js").default} type Geometry type.
 * @return {Mode} Drawing mode.
 */
function getMode(type) {
    switch (type) {
        case GeometryType.POINT:
        case GeometryType.MULTI_POINT:
            return Mode.POINT;
        case GeometryType.LINE_STRING:
        case GeometryType.MULTI_LINE_STRING:
            return Mode.LINE_STRING;
        case GeometryType.POLYGON:
        case GeometryType.MULTI_POLYGON:
            return Mode.POLYGON;
        case GeometryType.CIRCLE:
            return Mode.CIRCLE;
        default:
            throw new Error('Invalid type: ' + type);
    }
}
export default Draw;
//# sourceMappingURL=Draw.js.map
src/components/map/main.vue
@@ -1,23 +1,67 @@
<!--
 * @Description: 绘制图形统计圈内点数
 * @Author: Dragon
 * @Date: 2020-12-21 13:19:47
 * @LastEditTime: 2020-12-21 15:03:27
 * @LastEditors: Dragon
 * @Descripttion:
 * @version:
 * @Author: song
 * @Date: 2021-04-08 15:14:57
 * @LastEditors: song
 * @LastEditTime: 2021-04-24 11:59:43
-->
<template>
  <div>
    <div class="query-wrap">
      <el-button type="primary" @click="drawStart('Polygon')">
        {{ isDraw ? "绘制区域查询人数" : "重新绘制" }}
      </el-button>
  <div id="map" style="height: 100%">
    <div class="controlMap">
      <el-button-group>
        <el-button
          type="primary"
          icon="el-icon-edit"
          @click="getTypeSelected"
          :disabled="beginDraw"
          >{{ butTitle }}</el-button
        >
        <el-button
          type="primary"
          :disabled="!beginDraw"
          @click="stopDraw"
          icon="el-icon-delete"
          >取消</el-button
        >
        <!-- <el-button type="primary" icon="el-icon-share"></el-button>
        <el-button type="primary" icon="el-icon-delete"></el-button> -->
      </el-button-group>
    </div>
    <div id="map"></div>
    <tip v-show="showTip" :title="tipTitle" :position="position"></tip>
  </div>
</template>
<script>
import "ol/ol.css";
import OlView from "ol/View.js";
import XYZ from "ol/source/XYZ";
import OlLayerTile from "ol/layer/Tile.js";
import OlMap from "ol/Map.js";
import tip from "./tip.vue";
import {
  // eslint-disable-next-line no-unused-vars
  defaults as OlControlDefaults,
  defaults,
  // 全屏控件
  FullScreen,
  // 比例尺控件
  ScaleLine,
  // 缩放滚动条控件
  // eslint-disable-next-line no-unused-vars
  ZoomSlider,
  // 鼠标位置控件
  // eslint-disable-next-line no-unused-vars
  MousePosition,
  // -地图属性控件
  Attribution,
  // 鹰眼控件
  // eslint-disable-next-line no-unused-vars
  OverviewMap,
  // 缩放到范围控件
  // eslint-disable-next-line no-unused-vars
  ZoomToExtent,
  Rotate,
} from "ol/control.js";
import "ol/ol.css";
import { Map, View, Feature } from "ol";
import { Image as ImageLayer, Vector as VectorLayer } from "ol/layer";
@@ -27,39 +71,128 @@
import Draw from "ol/interaction/Draw";
import { Point } from "ol/geom";
import { Icon, Style, Text, Fill, Stroke } from "ol/style";
import staticMap from "@/assets/img/car.png";
import { Vector } from "ol/source";
// import Draw from "./Draw";
import LineString from "ol/geom/LineString.js";
import img from "@/assets/img/car.png";
export default {
  name: "Map",
  components: {
    tip,
  },
  data() {
    return {
      map: null, // 地图
      imgx: 0, // 当前地图宽
      imgy: 0, // 当前地图高
      isDraw: true, // 是否绘制
      draw: null,
      source: null,
      vector: null,
      styles: [
        new Style({
          stroke: new Stroke({
            color: "rgba(255,0,0,0.6)",
            width: 2,
          }),
          fill: new Fill({
            color: "rgba(255,0,0,0.3)",
          }),
        }),
      ],
      peopleLineAddlayer: new VectorLayer({
        // 图标图层
        zIndex: 22,
        source: new VectorSource(),
      }),
      //多边形Layer
      polygonlayer: new VectorLayer({
        // 图标图层
        zIndex: 22,
        source: new VectorSource(),
      }),
      vectorSource: new VectorSource(),
      features: [],
      feature: null,
      // 存储新增点,线,面,数据的地方
      persons: [],
      polygon: [],
      polygonPersons: [],
      features: [],
      feature: null,
      vectorSource: new VectorSource(),
      timer: null,
      // polygonData: [],
      // polygonFlag: false,
      // editToolbar: null,
      // addPolygonEntitys: null,
      typeSelected: "Polygon",
      drawLayer: null,
      draw: null,
      drawSource:null,
      coordinates: [],
      coordinatesStr: "",
      beginDraw: false,
      butTitle: "开始绘画",
      view: "",
      isDraw: true, // 是否绘制
      showTip: false,
      tipTitle: "",
      position: {
        w: 200,
        h: 10,
      },
    };
  },
  mounted() {
    const ol2d = new OlMap({
      layers: [
        new OlLayerTile({
          zIndex: 4,
          title: "影像",
          source: new XYZ({
            url: "https://webmap-tile.sf-express.com/MapTileService/rt?fetchtype=static&x={x}&y={y}&z={z}&project=sfmap&pic_size=256&pic_type=png8&data_name=361100&data_format=merged-dat&data_type=normal", // 行政区划
          }),
        }),
      ],
      // 注意地图控件的写法
      controls: defaults().extend([
        // new FullScreen(),
        // new ScaleLine(),
        // new MousePosition(),
        // new Rotate(),
        // new Attribution()
      ]),
      target: "map",
      view: new OlView({
        center: [0, 0],
        zoom: 2,
        projection: "EPSG:4326",
      }),
    });
    window.ol2d = ol2d;
    var view = ol2d.getView();
    // view.setCenter([115.85883507433789, 28.708432053474827])
    view.setCenter([115.9032747077233, 28.67433116990186]);
    //设置放大层级
    view.setZoom(13);
    this.view = view;
    // const drawSource = new VectorSource();
    // const drawLayer = new VectorLayer({
    //     source: drawSource
    // });
    // this.drawSource = drawSource;
    // ol2d.addLayer(drawLayer);
    ol2d.addLayer(this.peopleLineAddlayer);
    ol2d.addLayer(this.polygonlayer);
    //监听鼠标位置
    var that = this;
    //
    that.addNewLine();
    var obj = {
        fenceId: '12',
        name: '围栏3',
        center: '',
        radius: '',
        type: 'polyline',
        points: '113.960623,22.546082;113.958197,22.544029;113.956526,22.543245;113.953562,22.544563'
    }
    this.showFence(obj);
  },
  watch: {
    persons(val) {
@@ -69,49 +202,10 @@
    },
  },
  methods: {
    // 初始化地图
    initMap() {
      let extent = [0, 0, this.imgx, this.imgy];
      let projection = new Projection({
        extent: extent,
      });
      let $this = this;
      // 默认地图
      let mapLayer = new ImageLayer({
        source: new ImageStatic({
          url: staticMap,
          projection: projection,
          imageExtent: extent,
        }),
      });
      // 绘制点
      let featureLayer = new VectorLayer({
        source: this.vectorSource,
      });
      this.map = new Map({
        target: "map",
        layers: [
          mapLayer, // 展示地图层
          featureLayer, // 点
        ],
        view: new View({
          projection: projection,
          center: getCenter(extent),
          zoom: 2,
          maxZoom: 18,
        }),
      });
      this.source = new VectorSource({ wrapX: false });
      this.vector = new VectorLayer({
        source: this.source,
        style: this.styles,
      });
      this.map.addLayer(this.vector);
    goTudefault(x, y) {
      this.view.setCenter([x, y]);
      this.view.setZoom(14.5);
    },
    // 点
    setFeature() {
      let that = this;
@@ -148,18 +242,231 @@
      });
      that.vectorSource.addFeatures(that.features);
    },
    // 开始绘制多边形
    addEntitys(item, icon, scale, name, type) {
      const iconFeature = new Feature({
        geometry: new Point([Number(item.LGTD), Number(item.LTTD)]),
        name: name,
        attributes: item,
      });
      const iconStyle = new Style({
        image: new Icon({
          scale: scale,
          opacity: 1,
          src: icon,
          // src: require('../../assets/Mark.png')
        }),
      });
      iconFeature.setStyle(iconStyle);
      this[type].getSource().addFeature(iconFeature);
    },
    addLines(ringId) {
      var that = this;
      if (ringId != null && ringId != "") {
        $.ajax({
          url: "api/routeIn/routein/selectList",
          type: "post",
          data: {
            id: ringId,
          },
          dataType: "JSON",
          success: function (data) {
            that.peopleLineAddlayer.getSource().clear();
            var entityData = "";
            var entityArr = [];
            entityData = data.data[0].routeInfo.match(/\(([^)]*)\)/);
            // 此时result=["(dsfasjfj3124123)", "dsfasjfj3124123"];
            if (entityData && entityData != "") {
              entityData = entityData[1].split(",");
              for (var j = 0; j < entityData.length; j++) {
                entityArr.push([
                  Number(entityData[j].split(" ")[0]),
                  Number(entityData[j].split(" ")[1]),
                ]);
              }
            }
            var lineCoords = entityArr; // 线里点的集合
            var view = ol2d.getView();
            view.setCenter([
              lineCoords[Math.ceil(entityArr.length / 2)][0],
              lineCoords[Math.ceil(entityArr.length / 2)][1],
            ]);
            view.setZoom(14.5);
            // 要素
            // var lineCoords = [[featureInfo.lineString[0][0],featureInfo.lineString[0][0]],[featureInfo.lineString(0),featureInfo.lineString(0)]];
            var feature_LineString = new Feature({
              geometry: new LineString(lineCoords),
            });
            feature_LineString.setStyle(
              new Style({
                //填充色
                fill: new Fill({
                  color: "rgba(255, 255, 255, 0.2)",
                }),
                //边线颜色
                stroke: new Stroke({
                  color: "rgb(252, 94, 32)",
                  width: 5,
                }),
              })
            );
            that.peopleLineAddlayer.getSource().addFeature(feature_LineString);
            that.butTitle = "修改绘画";
          },
          error: function (data) {
            // 请求失败函数
            console.log(data);
          },
        });
      }
    },
    addNewLine() {
      this.map = ol2d;
      // 添加一个绘制的线使用的layer
      this.drawLayer = new VectorLayer({
        //layer所对应的source
        source: new Vector(),
      });
      //把layer加入到地图中
      this.map.addLayer(this.drawLayer);
    },
    //转换坐标点(多)
    transPoints(points) {
        let arr = points.split(';');
        let point = [];
        arr.forEach(item => {
            let newPoint = item.split(',');
            point.push(newPoint)
        })
        let _points = point.map(item => {
            item = [parseFloat(item[0]), parseFloat(item[1])];
            item = ol.proj.transform(item, 'EPSG:4326', 'EPSG:3857');
            return item;
        })
        return _points;
    },
     //回显围栏
    showFence(obj) {
        let {
            fenceId,
            name,
            type,
            center,
            radius,
            points
        } = obj;
        if (type == 'polygon') {
            this.showPolygon(fenceId, points, name)
        }
    },
     /**
     *
     * @param {*} fenceId 围栏id
     * @param {*} points 多边形坐标点
     * @param {*} name 围栏名
     */
    showPolygon(fenceId, points, name) {
        let _points = this.transPoints(points)
        _points = [_points]
        //多边形的数据格式是[[[lng,lat],[lng,lat]……]]外围两个中括号
        var polygonFeature = new ol.Feature({ //路线
            geometry: new ol.geom.Polygon(_points)
        });
        debugger;
        polygonFeature.setId(fenceId)
        this.source.addFeature(polygonFeature);
        console.log(this.source.getFeatures())
    },
    //开始绘制
    getTypeSelected() {
      this.beginDraw = true;
      this.draw && this.map.removeInteraction(this.draw);
      this.peopleLineAddlayer.getSource().clear();
      this.polygonlayer.getSource().clear();
      //再根据typeSelect的值绘制新的Interaction
      // this.addInteraction();
      this.drawStart();
    },
    stopDraw() {
      this.showTip = false;
      this.draw && this.map.removeInteraction(this.draw);
      this.beginDraw = false;
      this.tipTitle = "";
      this.$store.commit("setRotesData", ""); //用vuex传最终数据
    },
    setTipPosition(x, y, n, m) {
      this.position.w = x + n;
      this.position.h = y + m;
    },
    //绘制开始
    addInteraction() {
      this.tipTitle = "单击左键或右键开始绘画";
      // $("#map")
      //   .off("mousemove")
      //   .mousemove(function (e) {
      //     if (!that.showTip) {
      //       that.showTip = true;
      //     }
      //     that.setTipPosition(e.offsetX, e.offsetY, 10, 10);
      //   });
      this.coordinates = [];
      let value = this.typeSelected,
        that = this;
      if (value !== "None") {
        this.draw = new Draw({
          source: this.drawLayer.getSource(),
          type: this.typeSelected,
          style: new Style({
            stroke: new Stroke({
              color: "red",
              width: 3,
            }),
          }),
          coordinate: function (res) {
            //画线中的点
            that.coordinates.push(res);
            that.tipTitle = "可继续,或选择最终位置双击结束";
          },
          coordinateOver: function (res) {
            // 结束绘画 处理数据
            // console.log(that.doData(that.coordinates));
            let d = that.doData(that.coordinates);
            that.addLinesDraw(d);
            // console.log(d);
            // console.log(that.$store);
            that.$store.commit("setRotesData", d); //用vuex传最终数据
            // that.coordinatesStr = that.doData(that.coordinates);
          },
        });
        this.map.addInteraction(this.draw);
      }
    },
     // 开始绘制多边形
    drawStart(type) {
      type = 'Polygon';
      let that = this;
      var draw;
      if (this.isDraw) {
        this.isDraw = false;
        this.draw = new Draw({
        draw = new Draw({
          source: this.source,
          type: type,
        });
        this.map.addInteraction(this.draw);
        this.draw.on("drawend", function (evt) {
        draw.on("drawend", function (evt) {
          that.drawingEnd(evt);
        });
      } else {
@@ -183,79 +490,107 @@
          that.polygon.push({ lng: item[0], lat: item[1] });
        });
        for (let i = 0; i < this.persons.length; i++) {
          let boxFlag = this.isRegion(this.persons[i].x, this.persons[i].y, this.polygon);
          if (boxFlag) {
            this.polygonPersons.push(this.persons[i]);
          }
          this.polygonPersons.push(this.persons[i]);
        }
        this.$message({
          type: "success",
          message: `区域内有${this.polygonPersons.length}人`,
        });
        console.warn(this.polygonPersons, `区域内有${this.polygonPersons.length}人`);
        this.map.removeInteraction(this.draw);
        this.isDraw = false;
      }
    },
    // 验证点是否在区域内
    isRegion(lon, lat, aPoints) {
      let num = 0,
        iCount;
      let dLon1, dLon2, dLat1, dLat2, dLon;
      if (aPoints.length < 3) return false;
      iCount = aPoints.length;
      for (let i = 0; i < iCount; i++) {
        if (i == iCount - 1) {
          dLon1 = aPoints[i].lng;
          dLat1 = aPoints[i].lat;
          dLon2 = aPoints[0].lng;
          dLat2 = aPoints[0].lat;
        } else {
          dLon1 = aPoints[i].lng;
          dLat1 = aPoints[i].lat;
          dLon2 = aPoints[i + 1].lng;
          dLat2 = aPoints[i + 1].lat;
        }
        if ((lat >= dLat1 && lat < dLat2) || (lat >= dLat2 && lat < dLat1)) {
          if (Math.abs(dLat1 - dLat2) > 0) {
            dLon = dLon1 - ((dLon1 - dLon2) * (dLat1 - lat)) / (dLat1 - dLat2);
            if (dLon < lon) num++;
          }
    doData(val) {
      //      ` routeInfo: "
      //      LINESTRING(
      //        115.875489096939 28.7179278611352
      //        ,115.8794051221 28.7176267680684
      //        ,115.879340749084 28.7143052776491
      //        ,115.878879409134 28.7140324026424
      //        ,115.875220876038 28.7150580325974
      //        ,115.875489096939 28.7179466794231
      //        ,115.875489096939 28.7179466794231
      //        )"
      // `
      let str = "LINESTRING(";
      for (let k = 0; k < val.length; k++) {
        str += `${val[k][0]} ${val[k][1]}`;
        if (k != val.length - 1) {
          str += ",";
        }
      }
      if (num % 2 != 0) return true;
      return false;
      str += ")";
      // console.log(str, 111);
      return str;
    },
  },
  mounted() {
    let img = new Image();
    img.src = staticMap;
    let that = this;
    img.onload = function (res) {
      that.imgx = res.target.width;
      that.imgy = res.target.height;
      that.initMap();
    };
  },
  created() {
    let that = this;
    that.timer = setInterval(function () {
      that.persons = [
        { id: 1, name: "点-1", x: 497.08, y: 187.88, z: 0 },
        { id: 2, name: "点-2", x: 725.32, y: 565.88, z: 0 },
        { id: 3, name: "点-3", x: 643.24, y: 503.96, z: 0 },
      ];
    }, 2000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
    addLinesDraw(val) {
      var that = this;
      that.peopleLineAddlayer.getSource().clear();
      that.polygonlayer.getSource().clear();
      var entityData = "";
      var entityArr = [];
      entityData = val.match(/\(([^)]*)\)/);
      // 此时result=["(dsfasjfj3124123)", "dsfasjfj3124123"];
      if (entityData && entityData != "") {
        entityData = entityData[1].split(",");
        for (var j = 0; j < entityData.length; j++) {
          entityArr.push([
            Number(entityData[j].split(" ")[0]),
            Number(entityData[j].split(" ")[1]),
          ]);
        }
      }
      var lineCoords = entityArr; // 线里点的集合
      var view = ol2d.getView();
      view.setCenter([
        lineCoords[Math.ceil(entityArr.length / 2)][0],
        lineCoords[Math.ceil(entityArr.length / 2)][1],
      ]);
      view.setZoom(14.5);
      // 要素
      // var lineCoords = [[featureInfo.lineString[0][0],featureInfo.lineString[0][0]],[featureInfo.lineString(0),featureInfo.lineString(0)]];
      var feature_LineString = new Feature({
        geometry: new LineString(lineCoords),
      });
      feature_LineString.setStyle(
        new Style({
          //填充色
          fill: new Fill({
            color: "rgba(255, 255, 255, 0.2)",
          }),
          //边线颜色
          stroke: new Stroke({
            color: "rgb(252, 94, 32)",
            width: 5,
          }),
        })
      );
      that.peopleLineAddlayer.getSource().addFeature(feature_LineString);
      that.polygonlayer.getSource().addFeature(feature_LineString);
      if (that.draw != null) {
        that.beginDraw = false;
        that.butTitle = "重新绘画";
        that.draw.abortDrawing_();
        that.tipTitle = "已结束绘画,点击重新绘画清除上次内容并开始绘画";
        $("#map").unbind("mousemove");
        // setTimeout(() => {
        this.tipTitle = "";
        this.showTip = false;
      }
    },
  },
};
</script>
<style>
<style scoped lang="scss">
#map {
  width: 100%;
  height: calc(100vh - 50px);
  position: relative;
  .controlMap {
    position: absolute;
    top: 10px;
    left: calc(50% - 80px);
    z-index: 2 !important;
  }
}
</style>
src/components/map/main1.vue
File was deleted
src/components/map/main2.vue
New file
@@ -0,0 +1,270 @@
<!--
 * @Description: 绘制图形统计圈内点数
 * @Author: Dragon
 * @Date: 2020-12-21 13:19:47
 * @LastEditTime: 2020-12-21 15:03:27
 * @LastEditors: Dragon
-->
<template>
  <div>
    <div class="query-wrap">
      <el-button type="primary" @click="drawStart('Polygon')">
        {{ isDraw ? "绘制区域查询人数" : "重新绘制" }}
      </el-button>
    </div>
    <div id="map"></div>
  </div>
</template>
<script>
import "ol/ol.css";
import { Map, View, Feature } from "ol";
import { Image as ImageLayer, Vector as VectorLayer } from "ol/layer";
import XYZ from "ol/source/XYZ";
import { ImageStatic, Vector as VectorSource } from "ol/source";
import { getCenter } from "ol/extent";
import OlLayerTile from "ol/layer/Tile.js";
import { Projection } from "ol/proj";
import Draw from "ol/interaction/Draw";
import { Point } from "ol/geom";
import { Icon, Style, Text, Fill, Stroke } from "ol/style";
import staticMap from "@/assets/img/car.png";
import img from "@/assets/img/car.png";
export default {
  data() {
    return {
      map: null, // 地图
      imgx: 0, // 当前地图宽
      imgy: 0, // 当前地图高
      isDraw: true, // 是否绘制
      draw: null,
      source: null,
      vector: null,
      styles: [
        new Style({
          stroke: new Stroke({
            color: "rgba(255,0,0,0.6)",
            width: 2,
          }),
          fill: new Fill({
            color: "rgba(255,0,0,0.3)",
          }),
        }),
      ],
      persons: [],
      polygon: [],
      polygonPersons: [],
      features: [],
      feature: null,
      vectorSource: new VectorSource(),
      timer: null,
    };
  },
  watch: {
    persons(val) {
      if (val) {
        this.setFeature();
      }
    },
  },
  methods: {
    // 初始化地图
    initMap() {
      let extent = [0, 0, this.imgx, this.imgy];
      let projection = new Projection({
        extent: extent,
      });
      let $this = this;
      // 默认地图
      let mapLayer = new OlLayerTile({
          zIndex: 4,
          title: "影像",
          source: new XYZ({
            url: "https://webmap-tile.sf-express.com/MapTileService/rt?fetchtype=static&x={x}&y={y}&z={z}&project=sfmap&pic_size=256&pic_type=png8&data_name=361100&data_format=merged-dat&data_type=normal", // 行政区划
          }),
        });
      // 绘制点
      let featureLayer = new VectorLayer({
        source: this.vectorSource,
      });
      this.map = new Map({
        target: "map",
        layers: [
          mapLayer, // 展示地图层
          featureLayer, // 点
        ],
        view: new View({
          projection: "EPSG:4326",
          center: [0, 0],
          zoom: 2,
          maxZoom: 13,
        }),
      });
       var view = this.map.getView();
    // view.setCenter([115.85883507433789, 28.708432053474827])
    view.setCenter([115.9032747077233, 28.67433116990186]);
      this.source = new VectorSource({ wrapX: false });
      this.vector = new VectorLayer({
        source: this.source,
        style: this.styles,
      });
      this.map.addLayer(this.vector);
    },
    // 点
    setFeature() {
      let that = this;
      that.features = [];
      that.vectorSource.clear();
      that.persons.map((item) => {
        that.feature = new Feature({
          geometry: new Point([item.x, item.y]),
          name: item.name,
        });
        // 设置Feature的样式,使用小旗子图标
        that.feature.setStyle(
          new Style({
            image: new Icon({
              anchor: [0, 1],
              src: img,
            }),
            text: new Text({
              // 位置
              textAlign: "center",
              // 基准线
              textBaseline: "middle",
              // 文字样式
              font: "normal 20px 微软雅黑",
              // 文本内容
              text: item.name,
              // 文本填充样式(即文字颜色)
              fill: new Fill({ color: "#aa3300" }),
              stroke: new Stroke({ color: "#ffcc33", width: 2 }),
            }),
          })
        );
        that.features.push(that.feature);
      });
      that.vectorSource.addFeatures(that.features);
    },
    // 开始绘制多边形
    drawStart(type) {
      let that = this;
      if (this.isDraw) {
        this.isDraw = false;
        this.draw = new Draw({
          source: this.source,
          type: type,
        });
        this.map.addInteraction(this.draw);
        this.draw.on("drawend", function (evt) {
          that.drawingEnd(evt);
        });
      } else {
        this.source.clear();
        this.map.removeInteraction(this.draw);
        this.isDraw = true;
        this.polygon = [];
        this.polygonPersons = [];
      }
    },
    // 构建多边形结束
    drawingEnd(evt) {
      let that = this;
      const geo = evt.feature.getGeometry();
      const t = geo.getType();
      if (t === "Polygon") {
        // 获取坐标点
        const points = geo.getCoordinates();
        points[0].map((item) => {
          that.polygon.push({ lng: item[0], lat: item[1] });
        });
        console.log(this.polygon,1111);
        for (let i = 0; i < this.persons.length; i++) {
          let boxFlag = this.isRegion(this.persons[i].x, this.persons[i].y, this.polygon);
          if (boxFlag) {
            this.polygonPersons.push(this.persons[i]);
          }
        }
        this.$message({
          type: "success",
          message: `区域内有${this.polygonPersons.length}人`,
        });
        console.warn(this.polygonPersons, `区域内有${this.polygonPersons.length}人`);
        debugger;
        this.map.removeInteraction(this.draw);
      }
    },
    // 验证点是否在区域内
    isRegion(lon, lat, aPoints) {
      let num = 0,
        iCount;
      let dLon1, dLon2, dLat1, dLat2, dLon;
      if (aPoints.length < 3) return false;
      iCount = aPoints.length;
      for (let i = 0; i < iCount; i++) {
        if (i == iCount - 1) {
          dLon1 = aPoints[i].lng;
          dLat1 = aPoints[i].lat;
          dLon2 = aPoints[0].lng;
          dLat2 = aPoints[0].lat;
        } else {
          dLon1 = aPoints[i].lng;
          dLat1 = aPoints[i].lat;
          dLon2 = aPoints[i + 1].lng;
          dLat2 = aPoints[i + 1].lat;
        }
        if ((lat >= dLat1 && lat < dLat2) || (lat >= dLat2 && lat < dLat1)) {
          if (Math.abs(dLat1 - dLat2) > 0) {
            dLon = dLon1 - ((dLon1 - dLon2) * (dLat1 - lat)) / (dLat1 - dLat2);
            if (dLon < lon) num++;
          }
        }
      }
      if (num % 2 != 0) return true;
      return false;
    },
  },
  mounted() {
    let img = new Image();
    img.src = staticMap;
    let that = this;
    img.onload = function (res) {
      that.imgx = res.target.width;
      that.imgy = res.target.height;
      that.initMap();
    };
  },
  created() {
    let that = this;
    that.timer = setInterval(function () {
      that.persons = [
        { id: 1, name: "点-1", x: 497.08, y: 187.88, z: 0 },
        { id: 2, name: "点-2", x: 725.32, y: 565.88, z: 0 },
        { id: 3, name: "点-3", x: 643.24, y: 503.96, z: 0 },
      ];
    }, 2000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
};
</script>
<style>
#map {
  width: 100%;
  height: calc(100vh - 50px);
}
</style>
src/components/map/tip.vue
New file
@@ -0,0 +1,25 @@
<template>
  <div
    class="mapTip"
    :style="{ top: position.h + 'px', left: position.w + 'px' }"
  >
    {{ title }}
  </div>
</template>
<script>
export default {
  props: ["title", "position"],
};
</script>
<style lang="scss" scoped>
.mapTip {
  background-color: rgb(168, 168, 168);
  padding: 5px;
  border: 1px solid #000;
  position: absolute;
  z-index: 10 !important;
  border-radius: 5px;
}
</style>
src/page/index/tags.vue
@@ -6,9 +6,9 @@
      class="avue-tags__contentmenu"
      :style="{ left: contentmenuX + 'px', top: contentmenuY + 'px' }"
    >
      <div class="item" @click="clearCacheTags">
      <!-- <div class="item" @click="clearCacheTags">
        {{ $t("tagsView.clearCache") }}
      </div>
      </div> -->
      <div class="item" @click="closeOthersTags">
        {{ $t("tagsView.closeOthers") }}
      </div>
@@ -51,9 +51,9 @@
          <el-dropdown-item @click.native="closeAllTags">{{
            $t("tagsView.closeAll")
          }}</el-dropdown-item>
          <el-dropdown-item @click.native="clearCacheTags">{{
          <!-- <el-dropdown-item @click.native="clearCacheTags">{{
            $t("tagsView.clearCache")
          }}</el-dropdown-item>
          }}</el-dropdown-item> -->
        </el-dropdown-menu>
      </el-dropdown>
    </div>
test.html
New file
@@ -0,0 +1,68 @@
<!DOCTYPE html>
<html>
<head>
    <title>GeoJSON画多边形 - Openlayers3</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v4.4.2/css/ol.css" type="text/css">
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
    <script src="https://openlayers.org/en/v4.4.2/build/ol.js"></script>
</head>
<body>
    <div id="map" class="map"></div>
    <script>
        var points = [
            [113.05310369309863, 23.02901122314222],
            [113.21103215989551, 23.01081511718519],
            [113.09258580979785, 22.928074333493782]
        ];
        var styles = {
            'Polygon': new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: 'blue',
                    lineDash: [3],
                    width: 2
                }),
                fill: new ol.style.Fill({
                    color: 'rgba(0, 0, 255, 0.2)'
                })
            })
        };
        var geojsonObject = {
            'type': 'FeatureCollection',
            'features': [{
                'type': 'Feature',
                'geometry': {
                    'type': 'Polygon',
                    'coordinates': [points]
                }
            }]
        };
        var vectorSource = new ol.source.Vector({
            features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
        });
        var vectorLayer = new ol.layer.Vector({
            source: vectorSource,
            style: function(feature) {
                return styles[feature.getGeometry().getType()];
            }
        });
        //初始化点
        var map = new ol.Map({
            layers: [new ol.layer.Tile({
                source: new ol.source.OSM()
            })],
            target: 'map',
            view: new ol.View({
                projection: 'EPSG:4326',
                center: points[0],
                zoom: 10
            })
        });
        map.addLayer(vectorLayer);
    </script>
</body>
</html>