# 五.format

# 1.GeoJSON

通过 getFeatureByGeoJson 方法,将 GeoJson 数据转为 feature
/**
 * @todo 图形对象转化成GeoJson格式数据(postgis)
 * @param {string|object} geojson geojson字符串或者对象
 * @param {string|Projection} sourceCode 源投影坐标系
 * @param {string|Projection} targetCode 目标投影坐标系
 * @returns {Feature}
 */
function getFeatureByGeoJson(geojson, sourceCode, targetCode) {
  let view = map.getView()
  if (!geojson) {
    return null
  }
  let feature
  if (typeof geojson == "string") {
    // 替换 null 字符
    while (geojson.indexOf("null") != -1) {
      // geojson = geojson
      geojson = geojson.replace("null", "")
    }
  }
  feature = new ol.format.GeoJSON().readFeature(geojson, {
    dataProjection: sourceCode || view.getProjection(), // 设定JSON数据使用的坐标系
    featureProjection: targetCode || view.getProjection(), // 设定当前地图使用的feature的坐标系
  })
  return feature
}
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
// 添加 geojson 数据
var geojson = {
  type: "Feature",
  geometry: {
    type: "Polygon",
    coordinates: [
      [
        [116.09129344901807, 39.976463050783],
        [116.12802898368604, 39.986934394777144],
        [116.14845668754346, 39.970454902589644],
        [116.14365016898877, 39.952945442140425],
        [116.11069118461377, 39.95037052148613],
        [116.09129344901807, 39.976463050783],
      ],
    ],
  },
  properties: null,
}
// 转换
let feature = getFeatureByGeoJson(geojson)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//GeoJSON
var jsonshape = new ol.format.GeoJSON().writeFeature(feature)
1
2
  • GeoJSON().readFeature(data)

查看代码详情
<template>
  <div>
    <div ref="map" class="map"></div>
    <form class="form-inline">
      <label for="type">选择数据源 &nbsp;</label>
      <select ref="select" v-model="selected">
        <option value="line-samples.geojson">线类型</option>
        <option value="all.geojson">所有类型</option>
        <option value="photovoltaic.json">绘制</option>
        <option value="point-samples.geojson">点类型</option>
        <option value="polygon-samples.geojson">绘制</option>
        <option value="roads-seoul.geojson">修改</option>
        <option value="switzerland.geojson">修改</option>
        <option value="vienna-streets.geojson">绘制</option>
        <option value="world-cities.geojson">修改</option>
      </select>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selected: "",
    };
  },
  async mounted() {
    let {
      Feature,
      geom: { Circle },
      format: { GeoJSON },
      Map,
      View,
      layer: { Tile: TileLayer, Vector: VectorLayer },
      source: { OSM, Vector: VectorSource },
      style: { Circle: CircleStyle, Fill, Stroke, Style },
    } = ol;
    // 获取轨迹点
    let res = await this.$axios({
      type: "get",
      url: this.$withBase(
        `/data/geojson/${localStorage.geojson || "line-samples.geojson"}`
      ),
    });
    const geojsonObject = res.data;
    const image = new CircleStyle({
      radius: 5,
      fill: null,
      stroke: new Stroke({ color: "red", width: 1 }),
    });

    const styles = {
      Point: new Style({
        image: image,
      }),
      LineString: new Style({
        stroke: new Stroke({
          color: "green",
          width: 1,
        }),
      }),
      MultiLineString: new Style({
        stroke: new Stroke({
          color: "green",
          width: 1,
        }),
      }),
      MultiPoint: new Style({
        image: image,
      }),
      MultiPolygon: new Style({
        stroke: new Stroke({
          color: "yellow",
          width: 1,
        }),
        fill: new Fill({
          color: "rgba(255, 255, 0, 0.1)",
        }),
      }),
      Polygon: new Style({
        stroke: new Stroke({
          color: "blue",
          lineDash: [4],
          width: 3,
        }),
        fill: new Fill({
          color: "rgba(0, 0, 255, 0.1)",
        }),
      }),
      GeometryCollection: new Style({
        stroke: new Stroke({
          color: "magenta",
          width: 2,
        }),
        fill: new Fill({
          color: "magenta",
        }),
        image: new CircleStyle({
          radius: 10,
          fill: null,
          stroke: new Stroke({
            color: "magenta",
          }),
        }),
      }),
      Circle: new Style({
        stroke: new Stroke({
          color: "red",
          width: 2,
        }),
        fill: new Fill({
          color: "rgba(255,0,0,0.2)",
        }),
      }),
    };
    const styleFunction = function (feature) {
      return styles[feature.getGeometry().getType()];
    };
    const vectorSource = new VectorSource({
      features: new GeoJSON().readFeatures(geojsonObject), // geojson --> feature
    });
    vectorSource.addFeature(new Feature(new Circle([5e6, 7e6], 1e6)));
    const vectorLayer = new VectorLayer({
      source: vectorSource,
      style: styleFunction,
    });

    const map = new Map({
      layers: [
        new TileLayer({
          source: new OSM(),
        }),
        vectorLayer,
      ],
      target: this.$refs.map,
      view: new View({
        center: [12579156, 3274244],
        zoom: 2,
      }),
    });
    this.$refs.select.addEventListener(
      "change",
      function getDataSource(e) {
        this.selected = localStorage.geojson = e.target.value;
      },
      false
    );
    this.selected = localStorage.geojson || "line-samples.geojson";
  },
};
</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
  • GeoJSON()

查看代码详情
<template>
  <div ref="map" class="map"></div>
</template>

<script>
export default {
  mounted() {
    let {
      format: { GeoJSON },
      Map,
      View,
      layer: { Tile: TileLayer, Vector: VectorLayer },
      source: { XYZ, Vector: VectorSource },
      style: { Fill, Style, Text },
      extent: { getCenter },
    } = ol

    const style = new Style({
      text: new Text({
        font: 'bold 11px "Open Sans", "Arial Unicode MS", "sans-serif"',
        placement: "line",
        fill: new Fill({
          color: "white",
        }),
      }),
    })

    const attributions =
      '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
      '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'

    const viewExtent = [1817379, 6139595, 1827851, 6143616]
    const map = new Map({
      layers: [
        new TileLayer({
          source: new XYZ({
            attributions: attributions,
            url:
              "https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=" +
              mapkeys.maptiler,
            maxZoom: 20,
          }),
        }),
        new VectorLayer({
          declutter: true,
          source: new VectorSource({
            format: new GeoJSON(),
            url: this.$withBase("/data/geojson/vienna-streets.geojson"),
          }),
          style: function (feature) {
            style.getText().setText(feature.get("name"))
            return style
          },
        }),
      ],
      target: this.$refs.map,
      view: new View({
        extent: viewExtent,
        center: getCenter(viewExtent),
        zoom: 17,
        minZoom: 14,
      }),
    })
  },
}
</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

# 2.EsriJSON

  • EsriJSON().readFeature(data)

查看代码详情
<template>
  <div>
    <div ref="map" class="map"></div>
    <form class="form-inline">
      <label for="type">绘制或修改 &nbsp;</label>
      <select ref="type">
        <option value="DRAW">绘制</option>
        <option value="MODIFY">修改</option>
      </select>
    </form>
  </div>
</template>

<script>
export default {
  mounted() {
    let {
      format: { EsriJSON },
      Map,
      View,
      layer: { Tile: TileLayer, Vector: VectorLayer },
      source: { XYZ, Vector: VectorSource },
      tilegrid: { createXYZ },
      proj: { fromLonLat },
      loadingstrategy: { tile: tileStrategy },
      interaction: { Draw, Modify, Select, defaults: defaultInteractions },
    } = ol;
    const serviceUrl =
      "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Wildfire/FeatureServer/";
    const layer = "2";
    const esrijsonFormat = new EsriJSON();
    const vectorSource = new VectorSource({
      loader: function (extent, resolution, projection) {
        const url =
          serviceUrl +
          layer +
          "/query/?f=json&" +
          "returnGeometry=true&spatialRel=esriSpatialRelIntersects&geometry=" +
          encodeURIComponent(
            '{"xmin":' +
              extent[0] +
              ',"ymin":' +
              extent[1] +
              ',"xmax":' +
              extent[2] +
              ',"ymax":' +
              extent[3] +
              ',"spatialReference":{"wkid":102100}}'
          ) +
          "&geometryType=esriGeometryEnvelope&inSR=102100&outFields=*" +
          "&outSR=102100";
        // $.ajax({
        //   url: url,
        //   dataType: "jsonp",
        //   success: function (response) {
        //     if (response.error) {
        //       alert(
        //         response.error.message +
        //           "\n" +
        //           response.error.details.join("\n")
        //       )
        //     } else {
        //       const projection = { featureProjection: projection }
        //       const features = esrijsonFormat.readFeatures(response, projection) // esrijson --> feature
        //       if (features.length > 0) {
        //         vectorSource.addFeatures(features)
        //       }
        //     }
        //   },
        // })
      },
      strategy: tileStrategy(
        createXYZ({
          tileSize: 512,
        })
      ),
    });
    const vector = new VectorLayer({
      source: vectorSource,
    });
    const raster = new TileLayer({
      source: new XYZ({
        attributions:
          'Tiles © <a href="https://services.arcgisonline.com/ArcGIS/' +
          'rest/services/World_Topo_Map/MapServer">ArcGIS</a>',
        url:
          "https://server.arcgisonline.com/ArcGIS/rest/services/" +
          "World_Topo_Map/MapServer/tile/{z}/{y}/{x}",
      }),
    });
    const draw = new Draw({
      source: vectorSource,
      type: "Polygon",
    });
    const select = new Select();
    select.setActive(false);
    const selected = select.getFeatures();
    const modify = new Modify({
      features: selected,
    });
    modify.setActive(false);
    const map = new Map({
      interactions: defaultInteractions().extend([draw, select, modify]),
      layers: [raster, vector],
      target: this.$refs.map,
      view: new View({
        center: fromLonLat([-110.875, 37.345]),
        zoom: 5,
      }),
    });
    const typeSelect = this.$refs.type;
    typeSelect.onchange = function () {
      draw.setActive(typeSelect.value === "DRAW");
      select.setActive(typeSelect.value === "MODIFY");
      modify.setActive(typeSelect.value === "MODIFY");
    };
    const dirty = {};
    selected.on("add", function (evt) {
      const feature = evt.element;
      feature.on("change", function (evt) {
        dirty[evt.target.get("objectid")] = true;
      });
    });
    selected.on("remove", function (evt) {
      const feature = evt.element;
      const fid = feature.get("objectid");
      if (dirty[fid] === true) {
        const payload =
          "[" +
          esrijsonFormat.writeFeature(feature, {
            featureProjection: map.getView().getProjection(),
          }) +
          "]";
        const url = serviceUrl + layer + "/updateFeatures";
        // $.post(url, { f: "json", features: payload }).done(function (data) {
        //   const result = typeof data === "string" ? JSON.parse(data) : data
        //   if (result.updateResults && result.updateResults.length > 0) {
        //     if (result.updateResults[0].success !== true) {
        //       const error = result.updateResults[0].error
        //       alert(error.description + " (" + error.code + ")")
        //     } else {
        //       delete dirty[fid]
        //     }
        //   }
        // })
      }
    });
    draw.on("drawend", function (evt) {
      const feature = evt.feature;
      const payload =
        "[" +
        esrijsonFormat.writeFeature(feature, {
          featureProjection: map.getView().getProjection(),
        }) +
        "]";
      const url = serviceUrl + layer + "/addFeatures";
      // $.post(url, { f: "json", features: payload }).done(function (data) {
      //   const result = typeof data === "string" ? JSON.parse(data) : data
      //   if (result.addResults && result.addResults.length > 0) {
      //     if (result.addResults[0].success === true) {
      //       feature.set("objectid", result.addResults[0]["objectId"])
      //     } else {
      //       const error = result.addResults[0].error
      //       alert(error.description + " (" + error.code + ")")
      //     }
      //   }
      // })
    });
  },
};
</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

# 3.OSMXML

  • OSMXML().readFeature(data)

查看代码详情
<template>
  <div ref="map" class="map"></div>
</template>

<script>
export default {
  mounted() {
    let {
      format: { OSMXML },
      Map,
      View,
      layer: { Tile: TileLayer, Vector: VectorLayer },
      source: { XYZ, Vector: VectorSource },
      style: { Circle: CircleStyle, Fill, Stroke, Style },
      loadingstrategy: { bbox: bboxStrategy },
      proj: { transformExtent },
    } = ol
    let map = null
    const styles = {
      amenity: {
        parking: new Style({
          stroke: new Stroke({
            color: "rgba(170, 170, 170, 1.0)",
            width: 1,
          }),
          fill: new Fill({
            color: "rgba(170, 170, 170, 0.3)",
          }),
        }),
      },
      building: {
        ".*": new Style({
          zIndex: 100,
          stroke: new Stroke({
            color: "rgba(246, 99, 79, 1.0)",
            width: 1,
          }),
          fill: new Fill({
            color: "rgba(246, 99, 79, 0.3)",
          }),
        }),
      },
      highway: {
        service: new Style({
          stroke: new Stroke({
            color: "rgba(255, 255, 255, 1.0)",
            width: 2,
          }),
        }),
        ".*": new Style({
          stroke: new Stroke({
            color: "rgba(255, 255, 255, 1.0)",
            width: 3,
          }),
        }),
      },
      landuse: {
        "forest|grass|allotments": new Style({
          stroke: new Stroke({
            color: "rgba(140, 208, 95, 1.0)",
            width: 1,
          }),
          fill: new Fill({
            color: "rgba(140, 208, 95, 0.3)",
          }),
        }),
      },
      natural: {
        tree: new Style({
          image: new CircleStyle({
            radius: 2,
            fill: new Fill({
              color: "rgba(140, 208, 95, 1.0)",
            }),
            stroke: null,
          }),
        }),
      },
    }
    const vectorSource = new VectorSource({
      format: new OSMXML(),
      loader: function (extent, resolution, projection, success, failure) {
        const epsg4326Extent = transformExtent(extent, projection, "EPSG:4326")
        const client = new XMLHttpRequest()
        client.open("POST", "https://overpass-api.de/api/interpreter")
        client.addEventListener("load", function () {
          const features = new OSMXML().readFeatures(client.responseText, {
            featureProjection: map.getView().getProjection(),
          })
          vectorSource.addFeatures(features)
          success(features)
        })
        client.addEventListener("error", failure)
        const query =
          "(node(" +
          epsg4326Extent[1] +
          "," +
          Math.max(epsg4326Extent[0], -180) +
          "," +
          epsg4326Extent[3] +
          "," +
          Math.min(epsg4326Extent[2], 180) +
          ");rel(bn)->.foo;way(bn);node(w)->.foo;rel(bw););out meta;"
        client.send(query)
      },
      strategy: bboxStrategy,
    })
    const vector = new VectorLayer({
      source: vectorSource,
      style: function (feature) {
        for (const key in styles) {
          const value = feature.get(key)
          if (value !== undefined) {
            for (const regexp in styles[key]) {
              if (new RegExp(regexp).test(value)) {
                return styles[key][regexp]
              }
            }
          }
        }
        return null
      },
    })
    const attributions =
      '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
      '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'
    const raster = new TileLayer({
      source: new XYZ({
        attributions: attributions,
        url:
          "https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=" +
          mapkeys.maptiler,
        maxZoom: 20,
      }),
    })
    map = new Map({
      layers: [raster, vector],
      target: this.$refs.map,
      view: new View({
        center: [739218, 5906096],
        maxZoom: 19,
        zoom: 17,
      }),
    })
  },
}
</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

# 4.WKB

通过 getFeatureByWKB 方法,将 WKB 数据转为 feature
/**
 * @todo WKB格式数据转化成图形对象
 * @param {string} coordinate   0101000020E610000063B48EAA26105D404E7FF623451C4440 格式数据
 * @param {string|Projection} sourceCode 源投影坐标系
 * @param {string|Projection} targetCode 目标投影坐标系
 * @returns {Feature}
 */
function getFeatureByWKB(coordinate, sourceCode, targetCode) {
  try {
    let view = map.getView()
    if (!coordinate) {
      return null
    }
    // 数据格式类型
    let format = new ol.format.WKB()
    let feature
    // 判断收尾,是否为 WKB 格式
    if (coordinate.indexOf("010") == 0) {
      // 判断字符结尾
      let confirmEnding = function (str, target) {
        // 请把你的代码写在这里
        var start = str.length - target.length
        var arr = str.substr(start, target.length)
        if (arr == target) {
          return true
        }
        return false
      }
      if (confirmEnding(coordinate, "40")) {
        feature = format.readFeature(coordinate, {
          dataProjection: sourceCode || view.getProjection(), // 设定JSON数据使用的坐标系
          featureProjection: targetCode || view.getProjection(), // 设定当前地图使用的feature的坐标系
        })
      }
    }
    return feature
  } catch (e) {
    console.log(e)
    return null
  }
}
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
// 添加 WKB 数据
let wkb =
  "0102000020E6100000040000004AB6DE424F095D4024548C542D0144404AB6DE42E10D5D4024548CD46D0444404AB6DE022D115D4024548CD4DBFF43404AB6DE42DB135D4024548CD46D044440"
let features = getFeatureByWKB(wkb)
1
2
3
4
  • WKB().readFeature(data)

查看代码详情
<template>
  <div ref="map" class="map"></div>
</template>

<script>
export default {
  mounted() {
    let {
      format: { WKB },
      Map,
      View,
      layer: { Tile: TileLayer, Vector: VectorLayer },
      source: { OSM, Vector: VectorSource },
    } = ol
    const raster = new TileLayer({
      source: new OSM(),
    })
    const wkb =
      "0103000000010000000500000054E3A59BC4602540643BDF4F8D1739C05C8FC2F5284C4140EC51B81E852B34C0D578E926316843406F1283C0CAD141C01B2FDD2406012B40A4703D0AD79343C054E3A59BC4602540643BDF4F8D1739C0"
    const format = new WKB()
    const feature = format.readFeature(wkb, {
      dataProjection: "EPSG:4326",
      featureProjection: "EPSG:3857",
    })
    const vector = new VectorLayer({
      source: new VectorSource({
        features: [feature],
      }),
    })
    const map = new Map({
      layers: [raster, vector],
      target: this.$refs.map,
      view: new View({
        center: [2952104.0199, -3277504.823],
        zoom: 4,
      }),
    })
  },
}
</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

# 5.WKT

通过 getFeatureByWKT 方法,将 WKT 数据转为 feature
/**
 * @todo wkt格式数据转化成图形对象
 * @param {string} wkt   "POINT(112.7197265625,39.18164062499999)" 格式数据
 * @param {string|Projection} sourceCode 源投影坐标系
 * @param {string|Projection} targetCode 目标投影坐标系
 * @returns {Feature}
 */
function getFeatureByWKT(wkt, sourceCode, targetCode) {
  try {
    let view = map.getView()
    if (!wkt) {
      return null
    }
    // 数据格式类型
    let format = new ol.format.WKT()
    let feature
    feature = format.readFeature(wkt, {
      featureProjection: targetCode || view.getProjection(),
      dataProjection: sourceCode || view.getProjection(),
    })
    return feature
  } catch (e) {
    console.log(e)
    return null
  }
}
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
// 添加 WKT 数据
let wkt = "POINT(116.17983834030585 39.98298600752048)"
let feature = getFeatureByWKT(wkt)
1
2
3
//WKT
var wktshape = new ol.format.WKT().writeFeature(feature)
1
2
  • WKT().readFeature(data)

查看代码详情
<template>
  <div ref="map" class="map"></div>
</template>

<script>
export default {
  mounted() {
    let {
      format: { WKT },
      Map,
      View,
      layer: { Tile: TileLayer, Vector: VectorLayer },
      source: { OSM, Vector: VectorSource },
    } = ol
    const raster = new TileLayer({
      source: new OSM(),
    })
    const wkt =
      "POLYGON((10.689 -25.092, 34.595 " +
      "-20.170, 38.814 -35.639, 13.502 " +
      "-39.155, 10.689 -25.092))"
    const format = new WKT()
    const feature = format.readFeature(wkt, {
      dataProjection: "EPSG:4326",
      featureProjection: "EPSG:3857",
    })
    const vector = new VectorLayer({
      source: new VectorSource({
        features: [feature],
      }),
    })
    const map = new Map({
      layers: [raster, vector],
      target: this.$refs.map,
      view: new View({
        center: [2952104.0199, -3277504.823],
        zoom: 4,
      }),
    })
  },
}
</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

# 6.WMSGetFeatureInfo

  • WMSGetFeatureInfo().readFeature(data)

查看代码详情
<template>
  <table ref="info">
    <tr>
      <td>All features:</td>
      <td ref="all"></td>
    </tr>
    <tr>
      <td>Hotel features:</td>
      <td ref="hotel"></td>
    </tr>
    <tr>
      <td>Restaurant features:</td>
      <td ref="restaurant"></td>
    </tr>
  </table>
</template>

<script>
export default {
  async mounted() {
    let {
      format: { WMSGetFeatureInfo },
    } = ol
    let res = await this.$axios({
      type:'get',
      url:this.$withBase("/data/wmsgetfeatureinfo/osm-restaurant-hotel.xml")
    })
    const allFeatures = new WMSGetFeatureInfo().readFeatures(res.data)
    this.$refs.all.innerText = allFeatures.length.toString()
    const hotelFeatures = new WMSGetFeatureInfo({
      layers: ["hotel"],
    }).readFeatures(res.data)
    this.$refs.hotel.innerText = hotelFeatures.length.toString()
    const restaurantFeatures = new WMSGetFeatureInfo({
      layers: ["restaurant"],
    }).readFeatures(res.data)
    this.$refs.restaurant.innerText = restaurantFeatures.length.toString()
  },
}
</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

# 7.WMTSCapabilities

  • WMTSCapabilities().read(data)

查看代码详情
<template>
  <div ref="map" class="map"></div>
</template>

<script>
export default {
  async mounted() {
    let {
      Map,
      View,
      layer: { Tile: TileLayer },
      source: {
        OSM,
        WMTS: { optionsFromCapabilities },
      },
      format: { WMTSCapabilities },
    } = ol

    const parser = new WMTSCapabilities()
    let map
    let res = await this.$axios({
      type:'get',
      url:this.$withBase("/data/WMTSCapabilities.xml")
    })
    const result = parser.read(res.data)
    const options = optionsFromCapabilities(result, {
      layer: "layer-7328",
      matrixSet: "EPSG:3857",
    })

    map = new Map({
      layers: [
        new TileLayer({
          source: new OSM(),
          opacity: 0.7,
        }),
        new TileLayer({
          opacity: 1,
          source: new ol.source.WMTS(options),
        }),
      ],
      target: this.$refs.map,
      view: new View({
        center: [19412406.33, -5050500.21],
        zoom: 5,
      }),
    })
  },
}
</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

# 8.TopoJSON

  • TopoJSON()

查看代码详情
<template>
  <div ref="map" class="map"></div>
</template>

<script>
export default {
  mounted() {
    let {
      format: { TopoJSON },
      Map,
      View,
      layer: { Tile: TileLayer, Vector: VectorLayer },
      source: { XYZ, Vector: VectorSource },
      style: { Fill, Stroke, Style },
    } = ol
    const attributions =
      '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
      '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'
    const raster = new TileLayer({
      source: new XYZ({
        attributions: attributions,
        url:
          "https://api.maptiler.com/maps/darkmatter/{z}/{x}/{y}.png?key=" +
          mapkeys.maptiler,
        tileSize: 512,
      }),
    })
    const style = new Style({
      fill: new Fill({
        color: "rgba(255, 255, 255, 0.6)",
      }),
      stroke: new Stroke({
        color: "#319FD3",
        width: 1,
      }),
    })
    const vector = new VectorLayer({
      source: new VectorSource({
        url: this.$withBase("/data/topojson/world-110m.json"),
        format: new TopoJSON({
          layers: ["countries"],
        }),
        overlaps: false,
      }),
      style: style,
    })
    const map = new Map({
      layers: [
        raster,
         vector],
      target: this.$refs.map,
      view: new View({
        center: [12579156, 3274244],
        zoom: 1,
      }),
    })
  },
}
</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

# 9.KML

  • KML()

查看代码详情
<template>
  <div ref="map" class="map"></div>
</template>

<script>
export default {
  mounted() {
    let {
      format: { KML },
      Map,
      View,
      layer: { Vector: VectorLayer },
      source: { Vector: VectorSource },
      has: { DEVICE_PIXEL_RATIO },
      style: { Fill, Stroke, Style },
      proj: { fromLonLat },
    } = ol
    const pixelRatio = DEVICE_PIXEL_RATIO
    const canvas = document.createElement("canvas")
    const context = canvas.getContext("2d")
    const gradient = context.createLinearGradient(0, 0, 1024 * pixelRatio, 0)
    gradient.addColorStop(0, "red")
    gradient.addColorStop(1 / 6, "orange")
    gradient.addColorStop(2 / 6, "yellow")
    gradient.addColorStop(3 / 6, "green")
    gradient.addColorStop(4 / 6, "aqua")
    gradient.addColorStop(5 / 6, "blue")
    gradient.addColorStop(1, "purple")
    const vectorLayer = new VectorLayer({
      background: "white",
      source: new VectorSource({
        url: this.$withBase("/data/kml/states.kml"),
        format: new KML({ extractStyles: false }),
      }),
      style: new Style({
        fill: new Fill({ color: gradient }),
        stroke: new Stroke({
          color: "#333",
          width: 1,
        }),
      }),
    })
    const map = new Map({
      layers: [vectorLayer],
      target: this.$refs.map,
      view: new View({
        center: fromLonLat([-100, 38.5]),
        zoom: 4,
      }),
    })
  },
}
</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