# 六.地图绘制

  • 场景
    • 电子围栏

# 1.绘制和修改功能

属性 作用 配置
ol/interaction/Draw 绘制地理要素 -
ol/interaction/Modify 更改要素 -
ol/interaction/Snap 自动吸附到要素 -
查看代码详情
<template>
  <div>
    <div ref="map" class="map"></div>
    <form class="form-inline">
      <label for="type">几何类型 &nbsp;</label>
      <select ref="type">
        <option value="Point"></option>
        <option value="LineString">直线</option>
        <option value="Polygon">多边形</option>
        <option value="Circle"></option>
      </select>
    </form>
  </div>
</template>

<script>
export default {
  mounted() {
    let {
      Map,
      View,
      layer: { Tile: TileLayer, Vector: VectorLayer },
      source: { OSM, Vector: VectorSource },
      style: { Circle: CircleStyle, Fill, Stroke, Style },
      interaction: { Draw, Modify, Snap },
      proj: { get },
    } = ol;
    const raster = new TileLayer({
      source: new OSM(),
    });
    const source = new VectorSource();
    const vector = new VectorLayer({
      source: source,
      style: new Style({
        fill: new Fill({
          color: "rgba(255, 255, 255, 0.2)",
        }),
        stroke: new Stroke({
          color: "#ffcc33",
          width: 2,
        }),
        image: new CircleStyle({
          radius: 7,
          fill: new Fill({
            color: "#ffcc33",
          }),
        }),
      }),
    });
    const extent = get("EPSG:3857").getExtent().slice();
    extent[0] += extent[0];
    extent[2] += extent[2];
    const map = new Map({
      layers: [raster, vector],
      target: this.$refs.map,
      view: new View({
        center: [12579156, 3274244],
        zoom: 3,
        extent,
      }),
    });
    map.addInteraction(new Modify({ source: source }));
    let draw, snap;
    const typeSelect = this.$refs.type;
    function addInteractions() {
      draw = new Draw({
        source: source,
        type: typeSelect.value,
      });
      draw.on("drawend", function (e) {
        const geometry = e.feature.getGeometry();
        const corrdinates = geometry.getCoordinates();
        console.log(corrdinates);
        // map.removeInteraction(draw)
        // map.removeInteraction(snap)
      });
      map.addInteraction(draw);
      snap = new Snap({ source: source });
      map.addInteraction(snap);
    }
    typeSelect.onchange = function () {
      map.removeInteraction(draw);
      map.removeInteraction(snap);
      addInteractions();
    };
    addInteractions();
  },
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

# 2.绘制和修改测地线圆

查看代码详情
<template>
  <div>
    <div ref="map" class="map"></div>
    <form class="form-inline">
      <label for="type">几何类型 &nbsp;</label>
      <select ref="type">
        <option value="Point"></option>
        <option value="LineString">直线</option>
        <option value="Polygon">多边形</option>
        <option value="Circle"></option>
        <option value="Geodesic" selected>测地线圆</option>
      </select>
    </form>
  </div>
</template>

<script>
export default {
  mounted() {
    let {
      geom: { GeometryCollection, Point, Polygon, Polygon: circular },
      Map,
      View,
      layer: { Tile: TileLayer, Vector: VectorLayer },
      source: { OSM, Vector: VectorSource },
      style: { Circle: CircleStyle, Fill, Stroke, Style },
      interaction: { Draw, Modify, Snap },
      proj: { transform },
      sphere: { getDistance },
    } = ol;
    const raster = new TileLayer({
      source: new OSM(),
    });
    const source = new VectorSource();
    const style = new Style({
      fill: new Fill({
        color: "rgba(255, 255, 255, 0.2)",
      }),
      stroke: new Stroke({
        color: "#33cc33",
        width: 2,
      }),
      image: new CircleStyle({
        radius: 7,
        fill: new Fill({
          color: "#ffcc33",
        }),
      }),
    });
    const geodesicStyle = new Style({
      geometry: function (feature) {
        return feature.get("modifyGeometry") || feature.getGeometry();
      },
      fill: new Fill({
        color: "rgba(255, 255, 255, 0.2)",
      }),
      stroke: new Stroke({
        color: "#ff3333",
        width: 2,
      }),
      image: new CircleStyle({
        radius: 7,
        fill: new Fill({
          color: "rgba(0, 0, 0, 0)",
        }),
      }),
    });
    const vector = new VectorLayer({
      source: source,
      style: function (feature) {
        const geometry = feature.getGeometry();
        return geometry.getType() === "GeometryCollection"
          ? geodesicStyle
          : style;
      },
    });
    const map = new Map({
      layers: [raster, vector],
      target: this.$refs.map,
      view: new View({
        center: [12579156, 3274244],
        zoom: 3,
      }),
    });
    const defaultStyle = new Modify({ source: source })
      .getOverlay()
      .getStyleFunction();
    const modify = new Modify({
      source: source,
      style: function (feature) {
        feature.get("features").forEach(function (modifyFeature) {
          const modifyGeometry = modifyFeature.get("modifyGeometry");
          if (modifyGeometry) {
            const modifyPoint = feature.getGeometry().getCoordinates();
            const geometries = modifyFeature.getGeometry().getGeometries();
            const polygon = geometries[0].getCoordinates()[0];
            const center = geometries[1].getCoordinates();
            const projection = map.getView().getProjection();
            let first, last, radius;
            if (modifyPoint[0] === center[0] && modifyPoint[1] === center[1]) {
              first = transform(polygon[0], projection, "EPSG:4326");
              last = transform(
                polygon[(polygon.length - 1) / 2],
                projection,
                "EPSG:4326"
              );
              radius = getDistance(first, last) / 2;
            } else {
              first = transform(center, projection, "EPSG:4326");
              last = transform(modifyPoint, projection, "EPSG:4326");
              radius = getDistance(first, last);
            }
            const circle = circular(
              transform(center, projection, "EPSG:4326"),
              radius,
              128
            );
            circle.transform("EPSG:4326", projection);
            geometries[0].setCoordinates(circle.getCoordinates());
            modifyGeometry.setGeometries(geometries);
          }
        });
        return defaultStyle(feature);
      },
    });
    modify.on("modifystart", function (event) {
      event.features.forEach(function (feature) {
        const geometry = feature.getGeometry();
        if (geometry.getType() === "GeometryCollection") {
          feature.set("modifyGeometry", geometry.clone(), true);
        }
      });
    });
    modify.on("modifyend", function (event) {
      event.features.forEach(function (feature) {
        const modifyGeometry = feature.get("modifyGeometry");
        if (modifyGeometry) {
          feature.setGeometry(modifyGeometry);
          feature.unset("modifyGeometry", true);
        }
      });
    });
    map.addInteraction(modify);
    let draw, snap;
    const typeSelect = this.$refs.type;
    function addInteractions() {
      let value = typeSelect.value;
      let geometryFunction;
      if (value === "Geodesic") {
        value = "Circle";
        geometryFunction = function (coordinates, geometry, projection) {
          if (!geometry) {
            geometry = new GeometryCollection([
              new Polygon([]),
              new Point(coordinates[0]),
            ]);
          }
          const geometries = geometry.getGeometries();
          const center = transform(coordinates[0], projection, "EPSG:4326");
          const last = transform(coordinates[1], projection, "EPSG:4326");
          const radius = getDistance(center, last);
          const circle = circular(center, radius, 128);
          circle.transform("EPSG:4326", projection);
          geometries[0].setCoordinates(circle.getCoordinates());
          geometry.setGeometries(geometries);
          return geometry;
        };
      }
      draw = new Draw({
        source: source,
        type: value,
        geometryFunction: geometryFunction,
      });
      map.addInteraction(draw);
      snap = new Snap({ source: source });
      map.addInteraction(snap);
    }
    typeSelect.onchange = function () {
      map.removeInteraction(draw);
      map.removeInteraction(snap);
      addInteractions();
    };
    addInteractions();
  },
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185

# 3.地理编辑

查看代码详情
<template>
  <div>
    <div ref="map" class="map"></div>
    <select ref="mode">
      <option value="modify">选择要修改的特征</option>
      <option value="draw">画一个新的特征</option>
    </select>
  </div>
</template>

<script>
export default {
  mounted() {
    let {
      format: { GeoJSON },
      Map,
      View,
      layer: { Vector: VectorLayer },
      source: { Vector: VectorSource },
      interaction: { Draw, Modify, Select, Snap },
      proj: { useGeographic },
    } = ol;
    useGeographic();

    const source = new VectorSource({
      url: "https://openlayers.org/data/vector/us-states.json",
      format: new GeoJSON(),
    });

    const map = new Map({
      target: this.$refs.map,
      layers: [
        new VectorLayer({
          background: "white",
          source: source,
        }),
      ],
      view: new View({
        center: [-100, 38.5],
        zoom: 4,
      }),
    });

    const select = new Select();

    const modify = new Modify({
      features: select.getFeatures(),
    });

    const draw = new Draw({
      type: "Polygon",
      source: source,
    });

    const snap = new Snap({
      source: source,
    });

    function removeInteractions() {
      map.removeInteraction(modify);
      map.removeInteraction(select);
      map.removeInteraction(draw);
      map.removeInteraction(select);
    }

    const mode = this.$refs.mode;
    function onChange() {
      removeInteractions();
      switch (mode.value) {
        case "draw": {
          map.addInteraction(draw);
          map.addInteraction(snap);
          break;
        }
        case "modify": {
          map.addInteraction(select);
          map.addInteraction(modify);
          map.addInteraction(snap);
          break;
        }
        default: {
          // pass
        }
      }
    }
    mode.addEventListener("change", onChange);
    onChange();
  },
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89

# 4.手绘

查看代码详情
<template>
  <div>
    <div ref="map" class="map"></div>
    <form class="form-inline">
      <label for="type">几何类型 &nbsp;</label>
      <select ref="type">
        <option value="LineString">线条</option>
        <option value="Polygon">多边形</option>
        <option value="Circle">圆圈</option>
        <option value="None"></option>
      </select>
    </form>
  </div>
</template>

<script>
export default {
  mounted() {
    let {
      Feature,
      interaction: { Draw },
      Map,
      View,
      layer: { Tile: TileLayer, Vector: VectorLayer },
      source: { OSM, Vector: VectorSource },
    } = ol;
    const raster = new TileLayer({
      source: new OSM(),
    });
    const source = new VectorSource({ wrapX: false });
    const vector = new VectorLayer({
      source: source,
    });
    const map = new Map({
      layers: [raster, vector],
      target: this.$refs.map,
      view: new View({
        center: [12579156, 3274244],
        zoom: 3,
      }),
    });
    const typeSelect = this.$refs.type;
    let draw;
    function addInteraction() {
      const value = typeSelect.value;
      if (value !== "None") {
        draw = new Draw({
          source: source,
          type: typeSelect.value,
          freehand: true,
        });
        draw.on("drawend", function (e) {
          const geometry = e.feature.getGeometry();
          const corrdinates = geometry.getCoordinates();
          console.log(corrdinates);
          // map.removeInteraction(draw)
          // map.removeInteraction(snap)
        });
        map.addInteraction(draw);
      }
    }
    typeSelect.onchange = function () {
      map.removeInteraction(draw);
      addInteraction();
    };
    addInteraction();
  },
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

# 5.绘制形状

查看代码详情
<template>
  <div>
    <div ref="map" class="map"></div>
    <form class="form-inline">
      <label for="type">形状类型: &nbsp;</label>
      <select ref="type">
        <option value="Circle"></option>
        <option value="Square">正方形</option>
        <option value="Box">长方形</option>
        <option value="Star">星星</option>
        <option value="None"></option>
      </select>
      <input type="button" value="撤销" ref="undo" />
    </form>
  </div>
</template>

<script>
export default {
  mounted() {
    let {
      geom: { Polygon },
      Map,
      View,
      layer: { Tile: TileLayer, Vector: VectorLayer },
      source: { OSM, Vector: VectorSource },
      interaction: {
        Draw: { createBox, createRegularPolygon },
      },
    } = ol;
    const raster = new TileLayer({
      source: new OSM(),
    });
    const source = new VectorSource({ wrapX: false });
    const vector = new VectorLayer({
      source: source,
    });
    const map = new Map({
      layers: [raster, vector],
      target: this.$refs.map,
      view: new View({
        center: [-11000000, 4600000],
        zoom: 4,
      }),
    });
    const typeSelect = this.$refs.type;
    let draw;
    function addInteraction() {
      let value = typeSelect.value;
      if (value !== "None") {
        let geometryFunction;
        if (value === "Square") {
          value = "Circle";
          geometryFunction = createRegularPolygon(4);
        } else if (value === "Box") {
          value = "Circle";
          geometryFunction = createBox();
        } else if (value === "Star") {
          value = "Circle";
          geometryFunction = function (coordinates, geometry) {
            const center = coordinates[0];
            const last = coordinates[coordinates.length - 1];
            const dx = center[0] - last[0];
            const dy = center[1] - last[1];
            const radius = Math.sqrt(dx * dx + dy * dy);
            const rotation = Math.atan2(dy, dx);
            const newCoordinates = [];
            const numPoints = 12;
            for (let i = 0; i < numPoints; ++i) {
              const angle = rotation + (i * 2 * Math.PI) / numPoints;
              const fraction = i % 2 === 0 ? 1 : 0.5;
              const offsetX = radius * fraction * Math.cos(angle);
              const offsetY = radius * fraction * Math.sin(angle);
              newCoordinates.push([center[0] + offsetX, center[1] + offsetY]);
            }
            newCoordinates.push(newCoordinates[0].slice());
            if (!geometry) {
              geometry = new Polygon([newCoordinates]);
            } else {
              geometry.setCoordinates([newCoordinates]);
            }
            return geometry;
          };
        }
        draw = new ol.interaction.Draw({
          source: source,
          type: value,
          geometryFunction: geometryFunction,
        });
        map.addInteraction(draw);
      }
    }
    typeSelect.onchange = function () {
      map.removeInteraction(draw);
      addInteraction();
    };
    this.$refs.undo.addEventListener("click", function () {
      draw.removeLastPoint();
    });
    addInteraction();
  },
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102