• 三十四、openlayers官网示例Dynamic clusters解析——动态的聚合图层


    官网demo地址:

    https://openlayers.org/en/latest/examples/clusters-dynamic.html

    这篇绘制了多个聚合图层。

    先初始化地图 ,设置了地图视角的边界extent,限制了地图缩放的范围

    1. initMap() {
    2. const raster = new TileLayer({
    3. source: new XYZ({
    4. attributions:
    5. 'Base map: basemap.at',
    6. url: "https://maps{1-4}.wien.gv.at/basemap/bmapgrau/normal/google3857/{z}/{y}/{x}.png",
    7. }),
    8. });
    9. this.map = new Map({
    10. layers: [raster],
    11. target: "map",
    12. view: new View({
    13. center: [0, 0],
    14. zoom: 2,
    15. maxZoom: 19,
    16. extent: [
    17. ...fromLonLat([16.1793, 48.1124]),
    18. ...fromLonLat([16.5559, 48.313]),
    19. ],
    20. showFullExtent: true,
    21. }),
    22. });
    23. this.map.on("pointermove", this.moveEvent);
    24. this.map.on("click", this.clickEvent);
    25. },

    创建一个聚合数据源,数据是geoJson格式的。

    1. const vectorSource = new VectorSource({
    2. format: new GeoJSON(),
    3. url: "https://openlayers.org/en/latest/examples/data/geojson/photovoltaic.json",
    4. });
    5. const clusterSource = new Cluster({
    6. attributions:
    7. 'Data: Stadt Wien',
    8. distance: 35,
    9. source: vectorSource,
    10. });

     然后创建一个聚合图层

    1. //聚合图层
    2. this.clustersLayer = new VectorLayer({
    3. source: clusterSource,
    4. style: this.clusterStyle,
    5. });
    6. this.map.addLayer(this.clustersLayer);

    因为每个feature的样式不一样,所以样式这里都绑定了函数。

    这里的outerCircle定义为全局变量而并非局部变量,主要是因为clusterStyle函数是个高频触发函数,将outerCircle写成全局的可以不用new那么多次。使用样式组的方法绘制出来了外发光效果,其实就是画了两次圆形。

    1. //黄色圆圈 内外两层 发光效果
    2. clusterStyle(feature) {
    3. const size = feature.get("features").length;
    4. //还有下级
    5. if (size > 1) {
    6. return [
    7. new Style({
    8. image: this.outerCircle,
    9. }),
    10. new Style({
    11. image: this.innerCircle,
    12. text: new Text({
    13. text: size.toString(),
    14. fill: this.textFill,
    15. stroke: this.textStroke,
    16. }),
    17. }),
    18. ];
    19. }
    20. //没有下级
    21. const originalFeature = feature.get("features")[0];
    22. return this.clusterMemberStyle(originalFeature);
    23. },
    1. this.textFill = new Fill({
    2. color: "#fff",
    3. });
    4. this.textStroke = new Stroke({
    5. color: "rgba(0, 0, 0, 0.6)",
    6. width: 3,
    7. });
    8. this.innerCircle = new CircleStyle({
    9. radius: 14,
    10. fill: new Fill({
    11. color: "rgba(255, 165, 0, 0.7)",
    12. }),
    13. });
    14. this.outerCircle = new CircleStyle({
    15. radius: 20,
    16. fill: new Fill({
    17. color: "rgba(255, 153, 102, 0.3)",
    18. }),
    19. });

    有下级的时候图形是橙色发光的样式,没有下级的时候。根据feature的LEISTUNG字段显示为不同的icon图形。

    1. clusterMemberStyle(clusterMember) {
    2. return new Style({
    3. geometry: clusterMember.getGeometry(),
    4. image:
    5. clusterMember.get("LEISTUNG") > 5 ? this.darkIcon : this.lightIcon,
    6. });
    7. },
    1. this.darkIcon = new Icon({
    2. src: "data/icons/emoticon-cool.svg",
    3. });
    4. this.lightIcon = new Icon({
    5. src: "data/icons/emoticon-cool-outline.svg",
    6. });

     创建一个凸包图层。

    凸包是包含给定点集的最小凸多边形,在许多计算几何应用中非常重要,如图形学、地理信息系统(GIS)和形状分析。计算凸包的算法通常基于点的排序和几何性质,可以有效地处理大规模的数据。 

    下载引入monotone-chain-convex-hull

    1. npm i monotone-chain-convex-hull
    2. import monotoneChainConvexHull from "monotone-chain-convex-hull";
    1. //凸包图层样式
    2. this.convexHullFill = new Fill({
    3. color: "rgba(255, 153, 0, 0.4)",
    4. });
    5. this.convexHullStroke = new Stroke({
    6. color: "rgba(204, 85, 0, 1)",
    7. width: 1.5,
    8. });
    1. //凸包图层
    2. this.clusterHulls = new VectorLayer({
    3. source: clusterSource,
    4. style: this.clusterHullStyle,
    5. });
    1. clusterHullStyle(cluster) {
    2. if (cluster !== this.hoverFeature) {
    3. return null;
    4. }
    5. const originalFeatures = cluster.get("features");
    6. const points = originalFeatures.map((feature) =>
    7. feature.getGeometry().getCoordinates()
    8. );
    9. return new Style({
    10. geometry: new Polygon([monotoneChainConvexHull(points)]),
    11. fill: this.convexHullFill,
    12. stroke: this.convexHullStroke,
    13. });
    14. },

    当鼠标移动到点图层时,显示凸包效果。 

    1. moveEvent(event) {
    2. this.clustersLayer.getFeatures(event.pixel).then((features) => {
    3. if (features[0] !== this.hoverFeature) {
    4. this.hoverFeature = features[0];
    5. this.clusterHulls.setStyle(this.clusterHullStyle);
    6. this.map.getTargetElement().style.cursor =
    7. this.hoverFeature && this.hoverFeature.get("features").length > 1
    8. ? "pointer"
    9. : "";
    10. }
    11. });
    12. },

    然后是点线图层

    1. this.clusterCircles = new VectorLayer({
    2. source: clusterSource,
    3. style: this.clusterCircleStyle,
    4. });

    当前视图的缩放级别达到了最大缩放级别或者范围的宽度和高度都小于当前视图的分辨率      

    往点线图层的style数组中添加两个样式。。

    1. clusterCircleStyle(cluster, resolution) {
    2. if (cluster !== this.clickFeature || resolution !== this.clickResolution) {
    3. return null;
    4. }
    5. const clusterMembers = cluster.get("features");
    6. const centerCoordinates = cluster.getGeometry().getCoordinates();
    7. return this.generatePointsCircle(
    8. clusterMembers.length,
    9. cluster.getGeometry().getCoordinates(),
    10. resolution
    11. ).reduce((styles, coordinates, i) => {
    12. const point = new Point(coordinates);
    13. const line = new LineString([centerCoordinates, coordinates]);
    14. styles.unshift(
    15. new Style({
    16. geometry: line,
    17. stroke: this.convexHullStroke,
    18. })
    19. );
    20. styles.push(
    21. this.clusterMemberStyle(
    22. new Feature({
    23. ...clusterMembers[i].getProperties(),
    24. geometry: point,
    25. })
    26. )
    27. );
    28. return styles;
    29. }, []);
    30. },

    generatePointsCircle 方法根据聚类成员的数量、中心坐标和当前分辨率,生成一个圆周上的点坐标数组。 

    1. generatePointsCircle(count, clusterCenter, resolution) {
    2. //计算圆周长度和每个点的角度步长
    3. const circumference =
    4. this.circleDistanceMultiplier * this.circleFootSeparation * (2 + count);
    5. let legLength = circumference / (Math.PI * 2);
    6. const angleStep = (Math.PI * 2) / count;
    7. const res = [];
    8. let angle;
    9. //调整线段长度 确保线段长度至少为 35,并根据分辨率进行调整。
    10. legLength = Math.max(legLength, 35) * resolution;
    11. //生成圆周上的点坐标
    12. for (let i = 0; i < count; ++i) {
    13. angle = this.circleStartAngle + i * angleStep;
    14. res.push([
    15. clusterCenter[0] + legLength * Math.cos(angle),
    16. clusterCenter[1] + legLength * Math.sin(angle),
    17. ]);
    18. }
    19. return res;
    20. },

     点击事件时,获取当前点击的feature的边界值,定位到指定位置。

    1. clickEvent(event) {
    2. this.clustersLayer.getFeatures(event.pixel).then((features) => {
    3. if (features.length > 0) {
    4. const clusterMembers = features[0].get("features");
    5. if (clusterMembers.length > 1) {
    6. const extent = createEmpty();
    7. clusterMembers.forEach((feature) =>
    8. extend(extent, feature.getGeometry().getExtent())
    9. );
    10. const view = this.map.getView();
    11. const resolution = this.map.getView().getResolution();
    12. //如果当前视图的缩放级别达到了最大缩放级别 如果范围的宽度和高度都小于当前视图的分辨率
    13. if (
    14. view.getZoom() === view.getMaxZoom() ||
    15. (getWidth(extent) < resolution && getHeight(extent) < resolution)
    16. ) {
    17. this.clickFeature = features[0];
    18. this.clickResolution = resolution;
    19. this.clusterCircles.setStyle(this.clusterCircleStyle);
    20. } else {
    21. view.fit(extent, { duration: 500, padding: [50, 50, 50, 50] });
    22. }
    23. }
    24. }
    25. });
    26. },

    完整代码:

    1. <template>
    2. <div class="box">
    3. <h1>Dynamic clusters</h1>
    4. <div id="map"></div>
    5. </div>
    6. </template>
    7. <script>
    8. import Feature from "ol/Feature.js";
    9. import GeoJSON from "ol/format/GeoJSON.js";
    10. import Map from "ol/Map.js";
    11. import View from "ol/View.js";
    12. import {
    13. Circle as CircleStyle,
    14. Fill,
    15. Icon,
    16. Stroke,
    17. Style,
    18. Text,
    19. } from "ol/style.js";
    20. import { Cluster, Vector as VectorSource, XYZ } from "ol/source.js";
    21. import { LineString, Point, Polygon } from "ol/geom.js";
    22. import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer.js";
    23. import { createEmpty, extend, getHeight, getWidth } from "ol/extent.js";
    24. import { fromLonLat } from "ol/proj.js";
    25. // import convexHull from "convex-hull";
    26. import monotoneChainConvexHull from "monotone-chain-convex-hull";
    27. export default {
    28. name: "",
    29. components: {},
    30. data() {
    31. return {
    32. map: null,
    33. hoverFeature: null,
    34. convexHullFill: null,
    35. convexHullStroke: null,
    36. textFill: null,
    37. textStroke: null,
    38. innerCircle: null,
    39. outerCircle: null,
    40. darkIcon: null,
    41. lightIcon: null,
    42. circleDistanceMultiplier: 1,
    43. circleFootSeparation: 28,
    44. circleStartAngle: Math.PI / 2,
    45. clickFeature: null,
    46. clustersLayer: null,
    47. clusterHulls: null,
    48. clusterCircles: null,
    49. clickResolution:null,
    50. };
    51. },
    52. computed: {},
    53. created() {},
    54. mounted() {
    55. this.initMap();
    56. this.initStyle();
    57. this.addClusterLayers();
    58. },
    59. methods: {
    60. initMap() {
    61. const raster = new TileLayer({
    62. source: new XYZ({
    63. attributions:
    64. 'Base map: basemap.at',
    65. url: "https://maps{1-4}.wien.gv.at/basemap/bmapgrau/normal/google3857/{z}/{y}/{x}.png",
    66. }),
    67. });
    68. this.map = new Map({
    69. layers: [raster],
    70. target: "map",
    71. view: new View({
    72. center: [0, 0],
    73. zoom: 2,
    74. maxZoom: 19,
    75. extent: [
    76. ...fromLonLat([16.1793, 48.1124]),
    77. ...fromLonLat([16.5559, 48.313]),
    78. ],
    79. showFullExtent: true,
    80. }),
    81. });
    82. this.map.on("pointermove", this.moveEvent);
    83. this.map.on("click", this.clickEvent);
    84. },
    85. addClusterLayers() {
    86. const vectorSource = new VectorSource({
    87. format: new GeoJSON(),
    88. url: "https://openlayers.org/en/latest/examples/data/geojson/photovoltaic.json",
    89. });
    90. const clusterSource = new Cluster({
    91. attributions:
    92. 'Data: Stadt Wien',
    93. distance: 35,
    94. source: vectorSource,
    95. });
    96. //凸包图层
    97. this.clusterHulls = new VectorLayer({
    98. source: clusterSource,
    99. style: this.clusterHullStyle,
    100. });
    101. //聚合图层
    102. this.clustersLayer = new VectorLayer({
    103. source: clusterSource,
    104. style: this.clusterStyle,
    105. });
    106. //特定情况下的图层
    107. this.clusterCircles = new VectorLayer({
    108. source: clusterSource,
    109. style: this.clusterCircleStyle,
    110. });
    111. this.map.addLayer(this.clusterHulls);
    112. this.map.addLayer(this.clustersLayer);
    113. this.map.addLayer(this.clusterCircles);
    114. },
    115. initStyle() {
    116. //凸包图层样式
    117. this.convexHullFill = new Fill({
    118. color: "rgba(255, 153, 0, 0.4)",
    119. });
    120. this.convexHullStroke = new Stroke({
    121. color: "rgba(204, 85, 0, 1)",
    122. width: 1.5,
    123. });
    124. this.textFill = new Fill({
    125. color: "#fff",
    126. });
    127. this.textStroke = new Stroke({
    128. color: "rgba(0, 0, 0, 0.6)",
    129. width: 3,
    130. });
    131. this.innerCircle = new CircleStyle({
    132. radius: 14,
    133. fill: new Fill({
    134. color: "rgba(255, 165, 0, 0.7)",
    135. }),
    136. });
    137. this.outerCircle = new CircleStyle({
    138. radius: 20,
    139. fill: new Fill({
    140. color: "rgba(255, 153, 102, 0.3)",
    141. }),
    142. });
    143. this.darkIcon = new Icon({
    144. src: "data/icons/emoticon-cool.svg",
    145. });
    146. this.lightIcon = new Icon({
    147. src: "data/icons/emoticon-cool-outline.svg",
    148. });
    149. },
    150. clusterMemberStyle(clusterMember) {
    151. return new Style({
    152. geometry: clusterMember.getGeometry(),
    153. image:
    154. clusterMember.get("LEISTUNG") > 5 ? this.darkIcon : this.lightIcon,
    155. });
    156. },
    157. clusterCircleStyle(cluster, resolution) {
    158. if (cluster !== this.clickFeature || resolution !== this.clickResolution) {
    159. return null;
    160. }
    161. const clusterMembers = cluster.get("features");
    162. const centerCoordinates = cluster.getGeometry().getCoordinates();
    163. return this.generatePointsCircle(
    164. clusterMembers.length,
    165. cluster.getGeometry().getCoordinates(),
    166. resolution
    167. ).reduce((styles, coordinates, i) => {
    168. const point = new Point(coordinates);
    169. const line = new LineString([centerCoordinates, coordinates]);
    170. styles.unshift(
    171. new Style({
    172. geometry: line,
    173. stroke: this.convexHullStroke,
    174. })
    175. );
    176. styles.push(
    177. this.clusterMemberStyle(
    178. new Feature({
    179. ...clusterMembers[i].getProperties(),
    180. geometry: point,
    181. })
    182. )
    183. );
    184. return styles;
    185. }, []);
    186. },
    187. generatePointsCircle(count, clusterCenter, resolution) {
    188. //计算圆周长度和每个点的角度步长
    189. const circumference =
    190. this.circleDistanceMultiplier * this.circleFootSeparation * (2 + count);
    191. let legLength = circumference / (Math.PI * 2);
    192. const angleStep = (Math.PI * 2) / count;
    193. const res = [];
    194. let angle;
    195. //调整线段长度 确保线段长度至少为 35,并根据分辨率进行调整。
    196. legLength = Math.max(legLength, 35) * resolution;
    197. //生成圆周上的点坐标
    198. for (let i = 0; i < count; ++i) {
    199. angle = this.circleStartAngle + i * angleStep;
    200. res.push([
    201. clusterCenter[0] + legLength * Math.cos(angle),
    202. clusterCenter[1] + legLength * Math.sin(angle),
    203. ]);
    204. }
    205. return res;
    206. },
    207. clusterHullStyle(cluster) {
    208. if (cluster !== this.hoverFeature) {
    209. return null;
    210. }
    211. const originalFeatures = cluster.get("features");
    212. const points = originalFeatures.map((feature) =>
    213. feature.getGeometry().getCoordinates()
    214. );
    215. return new Style({
    216. geometry: new Polygon([monotoneChainConvexHull(points)]),
    217. fill: this.convexHullFill,
    218. stroke: this.convexHullStroke,
    219. });
    220. },
    221. //黄色圆圈 内外两层 发光效果
    222. clusterStyle(feature) {
    223. const size = feature.get("features").length;
    224. //还有下级
    225. if (size > 1) {
    226. return [
    227. new Style({
    228. image: this.outerCircle,
    229. }),
    230. new Style({
    231. image: this.innerCircle,
    232. text: new Text({
    233. text: size.toString(),
    234. fill: this.textFill,
    235. stroke: this.textStroke,
    236. }),
    237. }),
    238. ];
    239. }
    240. //没有下级
    241. const originalFeature = feature.get("features")[0];
    242. return this.clusterMemberStyle(originalFeature);
    243. },
    244. moveEvent(event) {
    245. this.clustersLayer.getFeatures(event.pixel).then((features) => {
    246. if (features[0] !== this.hoverFeature) {
    247. this.hoverFeature = features[0];
    248. this.clusterHulls.setStyle(this.clusterHullStyle);
    249. this.map.getTargetElement().style.cursor =
    250. this.hoverFeature && this.hoverFeature.get("features").length > 1
    251. ? "pointer"
    252. : "";
    253. }
    254. });
    255. },
    256. clickEvent(event) {
    257. this.clustersLayer.getFeatures(event.pixel).then((features) => {
    258. if (features.length > 0) {
    259. const clusterMembers = features[0].get("features");
    260. if (clusterMembers.length > 1) {
    261. const extent = createEmpty();
    262. clusterMembers.forEach((feature) =>
    263. extend(extent, feature.getGeometry().getExtent())
    264. );
    265. const view = this.map.getView();
    266. const resolution = this.map.getView().getResolution();
    267. //如果当前视图的缩放级别达到了最大缩放级别 如果范围的宽度和高度都小于当前视图的分辨率
    268. if (
    269. view.getZoom() === view.getMaxZoom() ||
    270. (getWidth(extent) < resolution && getHeight(extent) < resolution)
    271. ) {
    272. this.clickFeature = features[0];
    273. this.clickResolution = resolution;
    274. this.clusterCircles.setStyle(this.clusterCircleStyle);
    275. } else {
    276. view.fit(extent, { duration: 500, padding: [50, 50, 50, 50] });
    277. }
    278. }
    279. }
    280. });
    281. },
    282. },
    283. };
    284. </script>
    285. <style lang="scss" scoped>
    286. #map {
    287. width: 100%;
    288. height: 500px;
    289. }
    290. .box {
    291. height: 100%;
    292. }
    293. #info {
    294. width: 100%;
    295. height: 24rem;
    296. overflow: scroll;
    297. display: flex;
    298. align-items: baseline;
    299. border: 1px solid black;
    300. justify-content: flex-start;
    301. }
    302. </style>

  • 相关阅读:
    心情碎片~
    web前端设计与开发期末作品/期末大作业-疫情
    基于SSM的生活缴费系统的设计与实现
    操作系统(三)| 进程管理上 进程状态 同步 互斥
    shell脚本中加入这条可以执行完一个脚本回到这个目录下
    大麦网回流票监控,sing参数分析
    DNS、ICMP和NAT
    AlexNet 06
    【概率论基础进阶】多维随机变量及其分布-随机变量的独立性
    英语学习笔记
  • 原文地址:https://blog.csdn.net/aaa_div/article/details/139412080