三十六、openlayers官网示例Earthquake Clusters解析——在聚合图层鼠标触摸显示五角星

openlayers常用示例 简单说一下吧,最近做了十来天的的openlayers,然后稍微研究了一下,这里总结并做了一些示例给大家分享一下,应该是相对常用的一部分吧,由于做的时间比较短,这里写了十来个示例了,有实际项目用到的,也有自己想实现的,根据官网的示例改编总结之后的。虽然只有十几个示例,但是代码量还是很大,所以代码就不在这里贴了,我都写在了Gitee上,大家可以拉下来看源码,每个示例都是单独来写,一个组件一个示例(公用的部分抽离了),相对简洁明了。然后看下目前已经做了的示例吧! 阅读详情

官网demo地址:

Earthquake Clusters

这篇展示了鼠标触摸聚合图层点位显示五角星的效果。

首先是初始化地图,加载了一个KML格式的矢量数据源,extractStyles为false表示不从kml数据源中提取样式。使用Select添加了鼠标选中的交互事件

vector = new VectorLayer({
      source: new Cluster({
        distance: 40,
        source: new VectorSource({
          url: "https://openlayers.org/en/latest/examples/data/kml/2012_Earthquakes_Mag5.kml",
          format: new KML({
            extractStyles: false,
          }),
        }),
      }),
      style: styleFunction,
    });
    const raster = new TileLayer({
      source: new StadiaMaps({
        layer: "stamen_toner",
      }),
    }); 
const map = new Map({
      layers: [raster, vector],
      interactions: defaultInteractions().extend([
        new Select({
          condition: function (evt) {
            return evt.type == "pointermove" || evt.type == "singleclick";
          },
          style: selectStyleFunction,
        }),
      ]),
      target: "map",
      view: new View({
        center: [0, 0],
        zoom: 2,
      }),
    });

其中有两个样式函数,先来看第一个styleFunction。

如果有子feature就显示为黄色圆圈,如果没有子feature则绘制成五角星。

 let currentResolution;
    function styleFunction(feature, resolution) {
      if (resolution != currentResolution) {
        calculateClusterInfo(resolution);
        currentResolution = resolution;
      }
      let style;
      const size = feature.get("features").length;
      if (size > 1) {
        style = new Style({
          image: new CircleStyle({
            radius: feature.get("radius"),
            fill: new Fill({
              color: [255, 153, 0, Math.min(0.8, 0.4 + size / maxFeatureCount)],
            }),
          }),
          text: new Text({
            text: size.toString(),
            fill: textFill,
            stroke: textStroke,
          }),
        });
      } else {
        const originalFeature = feature.get("features")[0];
        style = createEarthquakeStyle(originalFeature);
      }
      return style;
    }

使用calculateClusterInfo 函数计算圆圈的半径,将子feature的extent合并到了一起,结合分辨率算出半径。

const calculateClusterInfo = function (resolution) {
      maxFeatureCount = 0;
      const features = vector.getSource().getFeatures();
      let feature, radius;
      for (let i = features.length - 1; i >= 0; --i) {
        feature = features[i];
        const originalFeatures = feature.get("features");
        const extent = createEmpty(); //创建一个空的范围对象,用来存储聚类的总范围。
        let j, jj;
        for (j = 0, jj = originalFeatures.length; j < jj; ++j) {
        //获取当前原始特征的几何范围。将这个几何范围合并到总范围 extent 中
          extend(extent, originalFeatures[j].getGeometry().getExtent());
        }
        maxFeatureCount = Math.max(maxFeatureCount, jj);
        radius = (0.25 * (getWidth(extent) + getHeight(extent))) / resolution;
        feature.set('radius',radius)
      }
    };

extend方法示例

假设你有一个聚类包含三个特征,其范围分别为:

  • 特征1: [0, 0, 1, 1]
  • 特征2: [2, 2, 3, 3]
  • 特征3: [1, 1, 4, 4]

通过逐步扩展 extent:

  • 初始 extent 是空的。
  • 扩展第一个特征后,extent 变为 [0, 0, 1, 1]。
  • 扩展第二个特征后,extent 变为 [0, 0, 3, 3]。
  • 扩展第三个特征后,extent 变为 [0, 0, 4, 4]。

最终的 extent 包含了所有特征的范围,即 [0, 0, 4, 4]。

 createEarthquakeStyle是绘制星星的方法,主要用了RegularShape这个类。

function createEarthquakeStyle(feature) {
      const name = feature.get("name");
      const magnitude = parseFloat(name.substr(2));
      const radius = 5 + 20 * (magnitude - 5);
      return new Style({
        geometry: feature.getGeometry(),
        image: new RegularShape({
          radius: radius,
          radius2: 3,
          points: 5,
          angle: Math.PI,
          fill: earthquakeFill,
          stroke: earthquakeStroke,
        }),
      });
    }

写一个小demo来理解RegularShape

//小demo
    let piontArr = [-213399.46385070545, -7204129.9025042085];
    let pointFeature = new Feature({
      geometry: new MultiPoint([piontArr]),
    });
    let newLayer = new VectorLayer({
      source: new VectorSource({
        features: [pointFeature],
      }),
      style: [
        new Style({
          image: new RegularShape({
            radius: 50,
            radius2:20,
            points: 5,
            angle: Math.PI,
            fill: earthquakeFill,
            stroke: earthquakeStroke,
          }),
        }),
      ],
    });
    map.addLayer(newLayer)

 RegularShape参数解释:

  • radius:

    • 含义: 图形的外半径,即从图形中心到外顶点的距离。
  • radius2:

    • 含义: 图形的内半径,仅在绘制星形时有效。表示从图形中心到内顶点的距离。
  • points:

    • 含义: 图形的顶点数。如果 radius2 被定义,则 points 表示星形的顶点数(外顶点和内顶点的总数),否则表示多边形的边数。
    • 示例值: 6 表示绘制一个六边形或六角星形。
  • angle:

    • 含义: 图形的旋转角度,以弧度为单位。Math.PI 表示旋转 180 度。
    • 示例值: Math.PI 表示图形旋转 180 度。

 然后是第二个样式函数selectStyleFunction

鼠标触摸的时候获取到feature自定义属性features取出来,把每一个子feature绘制成星星形状展示。

function selectStyleFunction(feature) {
      const styles = [
        new Style({
          image: new CircleStyle({
            radius: feature.get("radius"),
            fill: invisibleFill,
          }),
        }),
      ];
      const originalFeatures = feature.get("features");
      let originalFeature;
      for (let i = originalFeatures.length - 1; i >= 0; --i) {
        originalFeature = originalFeatures[i];
        styles.push(createEarthquakeStyle(originalFeature));
      }
      return styles;
    }

完整代码:

<template>
  <div class="box">
    <h1>Earthquake Clusters</h1>
    <div id="map"></div>
  </div>
</template>

<script>
import KML from "ol/format/KML.js";
import Map from "ol/Map.js";
import View from "ol/View.js";
import {
  Circle as CircleStyle,
  Fill,
  RegularShape,
  Stroke,
  Style,
  Text,
  Circle,
} from "ol/style.js";
import { MultiPoint, Point } from "ol/geom.js";
import { Cluster, StadiaMaps, Vector as VectorSource } from "ol/source.js";
import { Select, defaults as defaultInteractions } from "ol/interaction.js";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer.js";
import { createEmpty, extend, getHeight, getWidth } from "ol/extent.js";
import Feature from "ol/Feature.js";
export default {
  name: "",
  components: {},
  data() {
    return {
      map: null,
    };
  },
  computed: {},
  created() {},
  mounted() {
    const earthquakeFill = new Fill({
      color: "rgba(255, 153, 0, 0.8)",
    });
    const earthquakeStroke = new Stroke({
      color: "rgba(255, 204, 0, 0.2)",
      width: 1,
    });
    const textFill = new Fill({
      color: "#fff",
    });
    const textStroke = new Stroke({
      color: "rgba(0, 0, 0, 0.6)",
      width: 3,
    });
    const invisibleFill = new Fill({
      color: "rgba(255, 255, 255, 0.01)",
    });

    function createEarthquakeStyle(feature) {
      const name = feature.get("name");
      const magnitude = parseFloat(name.substr(2));
      const radius = 5 + 20 * (magnitude - 5);
      return new Style({
        geometry: feature.getGeometry(),
        image: new RegularShape({
          radius: radius,
          radius2: 3,
          points: 5,
          angle: Math.PI,
          fill: earthquakeFill,
          stroke: earthquakeStroke,
        }),
      });
    }

    let maxFeatureCount;
    let vector = null;
    const calculateClusterInfo = function (resolution) {
      maxFeatureCount = 0;
      const features = vector.getSource().getFeatures();
      let feature, radius;
      for (let i = features.length - 1; i >= 0; --i) {
        feature = features[i];
        const originalFeatures = feature.get("features");
        const extent = createEmpty();
        let j, jj;
        for (j = 0, jj = originalFeatures.length; j < jj; ++j) {
          extend(extent, originalFeatures[j].getGeometry().getExtent());
        }
        maxFeatureCount = Math.max(maxFeatureCount, jj);
        radius = (0.25 * (getWidth(extent) + getHeight(extent))) / resolution;
        feature.set('radius',radius)
      }
    };

    let currentResolution;
    function styleFunction(feature, resolution) {
      if (resolution != currentResolution) {
        calculateClusterInfo(resolution);
        currentResolution = resolution;
      }
      let style;
      const size = feature.get("features").length;
      if (size > 1) {
        style = new Style({
          image: new CircleStyle({
            radius: feature.get("radius"),
            fill: new Fill({
              color: [255, 153, 0, Math.min(0.8, 0.4 + size / maxFeatureCount)],
            }),
          }),
          text: new Text({
            text: size.toString(),
            fill: textFill,
            stroke: textStroke,
          }),
        });
      } else {
        const originalFeature = feature.get("features")[0];
        style = createEarthquakeStyle(originalFeature);
      }
      return style;
    }

    function selectStyleFunction(feature) {
      const styles = [
        new Style({
          image: new CircleStyle({
            radius: feature.get("radius"),
            fill: invisibleFill,
          }),
        }),
      ];
      const originalFeatures = feature.get("features");
      let originalFeature;
      for (let i = originalFeatures.length - 1; i >= 0; --i) {
        originalFeature = originalFeatures[i];
        styles.push(createEarthquakeStyle(originalFeature));
      }
      return styles;
    }

    vector = new VectorLayer({
      source: new Cluster({
        distance: 40,
        source: new VectorSource({
          url: "https://openlayers.org/en/latest/examples/data/kml/2012_Earthquakes_Mag5.kml",
          format: new KML({
            extractStyles: false,
          }),
        }),
      }),
      style: styleFunction,
    });
    const raster = new TileLayer({
      source: new StadiaMaps({
        layer: "stamen_toner",
      }),
    });

    const map = new Map({
      layers: [raster,vector],
      interactions: defaultInteractions().extend([
        new Select({
          condition: function (evt) {
            return evt.type == "pointermove" || evt.type == "singleclick";
          },
          style: selectStyleFunction,
        }),
      ]),
      target: "map",
      view: new View({
        center: [0, 0],
        zoom: 2,
      }),
    });

    //小demo
    let piontArr = [-213399.46385070545, -7204129.9025042085];
    let pointFeature = new Feature({
      geometry: new MultiPoint([piontArr]),
    });
    let newLayer = new VectorLayer({
      source: new VectorSource({
        features: [pointFeature],
      }),
      style: [
        new Style({
          image: new RegularShape({
            radius: 50,
            radius2:20,
            points: 5,
            angle: Math.PI,
            fill: earthquakeFill,
            stroke: earthquakeStroke,
          }),
        }),
      ],
    });
    // map.addLayer(newLayer)
  },
  methods: {},
};
</script>

<style lang="scss" scoped>
#map {
  width: 100%;
  height: 500px;
}
.box {
  height: 100%;
}
</style>

openlayers全面教程306+【目录】 vue+openlayers系列教程旨在为开发者提供简单快捷的示例。在每一个示例中,解释相应的API知识点。 阅读详情

相关推荐

001:vue+openlayers 从0 到1 搭建开发环境

本系列教程是在vue2.X的基础上加载openlayers程序,来开发各种示例程序。

大剑师兰特的GIS世界 1万+

【Openlayers】绘制和编辑图形(完整示例)

OpenLayers是一个开源的JavaScript库,它用于在Web页面中创建交互式地图应用程序。使用OpenLayers可以绘制各种类型的图形,如点、线、面等。以上是一个基本的使用OpenLayers绘制图形的示例。你可以根据自己的需求,修改代码中的地图配置、绘制交互类型等。

weixin_43180565的博客 2687

Openlayers 教程 03 - Style 样式演示 - 基础样式、标签文本(label)、标签背景和边框、渐变色等

Openlayers 对样式的控制是通过一个通用的样式对象 Style,图层(Layer)和图形要素(Feature)都可以设置 Style 对象,来展示想要的结果。

非科班Java出身GISer的博客 7224

openlayers常见实例

http://openlayers.org/en/master/examples/epsg-4326.html – 标尺 http://openlayers.org/en/master/examples/export-map.html – 截图 http://openlayers.org/en/master/examples/export-pdf.html – 导出PDF http://openl...

weixin_39520640的博客 4122

Openlayers 中文版:API + 示例翻译

Openlayers 中文版(v10.9.0):API + 示例翻译。

非科班Java出身GISer的博客 8590

【cocos2dx面试题干货】--2021年最新cocos2dx面试干货(引擎篇)

【cocos2dx面试题干货】--2020年度最新cocos2dx面试干货(引擎篇 ) 大家好,我是Lampard~~ 经过春招一番艰苦奋战之后,我终于是进入了心仪的公司。 今天给大家分享一下我在之前精心准备的一套面试知识。 由于我面试的岗位是cocos2dx的开发岗,今天就先给大家分享一下引擎方面的知识。 本人亲测80%的引擎相关题目都...

Lampard的博客 1万+

openlayers案例

1.openlayers案例一 这个例子是我创建gs项目区域预警gis功能的原型demo,在此demo上学到了基本的html知识和openlayers项目搭建;是一个很不错的demo。 文章分为以下五个部分: 序例子运行图示调用OpenLayers 用来包含地图 JavaScript来创建map 2.全球地震系统的可视化 这个例子,从wms请求、地图图层分类、设置基本环境、生成矢

GIS笔记 3460

EEGNet 网络代码解析与实战复现指南

本文详细解析了EEGNet这一轻量级卷积神经网络的结构与设计思想,重点阐述了其利用深度可分离卷积高效处理脑电信号的原理。文章提供了基于PyTorch的完整代码复现指南,包括网络搭建、数据模拟、训练调试及关键参数解析,旨在帮助读者掌握EEGNet的代码复现技巧,并将其应用于脑机接口等实际场景。

honey的博客 532

OpenLayers官方实例全集

OpenLayers官方实例,源码整理改写。

GISer小辉 1450

Android Studio安装常见问题详解——Android Emulator Hypervisor Driver for AMD Processors installation failed.

目录一、问题描述二、解决方案2.1 开启CPU虚拟化2.2 禁用Hyper-V2.3 使用管理员命令行在驱动程序包中执行“silent_install.bat” 一、问题描述 新买的AMD轻薄本,在安装Android Studio时遇到问题: Android Emulator Hypervisor Driver for AMD Processors installation failed. 笔记本配置为: 二、解决方案 2.1 开启CPU虚拟化 设置虚拟化的步骤这里不进行详细介绍了。如果需要,可以自行百

Wendy的博客 4万+

微信内置浏览器抓包全攻略:从ADB配置到Chrome调试(附常见问题解决)

本文提供了一套完整的微信内置浏览器抓包与调试解决方案。从ADB工具的深度配置与稳定性连接开始,详细讲解了如何开启X5内核调试开关,并利用Chrome DevTools建立远程连接。文章重点剖析了Network面板进行网络请求抓取、性能分析和问题定位的实战技巧,并附带了设备连接失败、无网络请求等常见问题的排查指南,帮助开发者高效解决微信H5页面调试难题。

gitlab7runner的博客 543

Openlayers 常用实例

#openlayers常用实例 http://openlayers.org/en/master/examples/epsg-4326.html – 标尺 http://openlayers.org/en/master/examples/export-map.html – 截图 http://openlayers.org/en/master/examples/export-pdf.html – 导出...

Chiangku的博客 1720

大模型训练(1):流水线并行

Gpipe的方法是,在训练时计算和运用的是micro-batch里的均值和方差,但同时持续追踪全部mini-batch的移动平均和方差,以便在测试阶段进行使用。流水线并行的核心思想是:在模型并行的基础上,进一步引入数据并行的办法,即把原先的数据再划分成若干个更小的batch,分批送入GPU进行训练,算一部分就让下一个GPU动起来。从实验结果可知,在关掉NVlinks的情况下,Gpipe一样也能实现随着GPU数量的增加,训练速度也增加的效果。前文说过,随着模型的增加,每块GPU中存储的中间结果也会越大。

呆呆象呆呆的博客 1970

OpenLayers开发离线地图支持谷歌、高德、百度

(OpenLayers DEMO)点击下载 本案例介绍如何在离线(单机、或局域网无Internet)状态下发布离线地图,且结合OpenLayer做基于地图的二次开发。 一、 离线地图数据下载 离线地图下载,可以使用bigemap地图下载器全能版(下载地址http://www.bigemap.com/reader/download/detail201802015.html)。 打开bigemap地图下载器,左上角“选择地图”选择谷歌地球,右上角“选择行政区域”我们...

bigemap的博客 3752

Hypermesh到Abaqus CEL网格转换全攻略:解决欧拉体导入难题

本文详细解析了Hypermesh到Abaqus CEL网格转换的全流程,重点解决欧拉体导入难题。通过单元类型转换、INP文件编辑和多组件合并技术,实现流固耦合仿真的高效前处理。文章包含实用脚本和工程案例,帮助工程师突破ABAQUS CEL分析中的网格转换瓶颈。

weixin_30832143的博客 190

光学测量仿真软件:OpticsBuilder_(9).热应力分析与补偿

在OpticsBuilder中,定义材料的热膨胀系数可以通过API进行。以下是一个Python代码示例,展示如何在OpticsBuilder中定义材料的热膨胀系数。

kkchenjj的博客 1085

OpenLayers项目入门-实例

文章目录前言一、OpenLayers是什么?二、入门实例1.在线版本2.离线版本总结 前言 由于工作,需要学习一下OpenLayers,了解了基础知识后发现网上好多所谓入门实例太坑人了,对我这样的前端小白太不友好了,所以,在测试了一个最简单的版本后,我准备自己写一个,喜欢点赞哈。 一、OpenLayers是什么? OpenLayers使在任何网页中轻松放置动态地图成为可能。它可以显示从任何来源加载的地图图块,矢量数据和标记。OpenLayers的开发旨在进一步利用各种地理信息。重点在于是一个完全免费的J

qq_41829867的博客 2728

【Unity-UGUI控件全面解析】| Layout自动布局组件详解

UGUI中有个自动布局组件Auto Layout,主要包含下面几个模块(点击可进入官方文档下查看描述): 自动布局 布局元素 (Layout Element) 水平布局组 (Horizontal Layout Group) 垂直布局组 (Vertical Layout Group) 网格布局组 (Grid Layout Group) 内容大小适配器 (Content Size Fitter) 自动布局系统 基于布局元素和布局控制器的概念。一个布局元素是具有矩形变换以及其他可选组件的游戏对象。布局元素对自身

努力前行,总会成为自己心中的那道光 2万+

OpenLayers官网示例精选

如题

GIS小虫的博客 1803

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

OpenLayers官方示例详解一:Custom Interactions

  目录   一、示例概述 二、代码详解 2.1、派生自定义类Drag 2.1、添加Drag类的原型方法 2.3、将自定义交互小部件添加到地图 三、完整代码 四、总结 一、示例概述     这个示例演示了通过ol/interactions/Pointer类创建一个自定义交互小部件(custom interaction)。     这个自定义小部件的功能是让用户能够在地图上面...

不睡觉的怪叔叔的博客 3733

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

openlayers 入门教程(二):map 篇

OpenLayers 是一个开源的 JavaScript 库,用于在网页中构建交互式的地图应用程序。ol/Map 类是 OpenLayers API 中的核心组件之一,它负责创建和管理整个地图实例。**

大剑师兰特的GIS世界 7168

Vue结合Openlayers示例

文章目录1、简单示例1.1创建一个mapView组件1.2 创建一个Vue实例,并注册mapView组件1.3在页面中应用2、地图配置3、npm 构建3.1 安装openlayers3.2 在mapView组建中导入相关模块 1、简单示例 先看下以引入< JavaScript >的方式的使用方法 1.1创建一个mapView组件 mapView.js export default { ...

此爱如少年 9271

openlayers开发示例

openlayers开发内容中一些比较新奇需求的实现方式示例: 调用canvas绘制几何图形 <!DOCTYPE html> <html> <head> <title>Render geometries to a canvas</title> <link rel="stylesheet" href="https:...

DIY_Liu的博客 1111

OpenLayers如何使用官网实例

最近一直在寻找如何运行成功官网的例子,花费几天时间终于解决了。 官网的代码是ECMAScript的写法需要用到import,需要依赖node.js,对于新手来说这个有点难以理解 所以我们还是按照熟悉的方式,将js包下载到本地引用,并且需要修改import的内容 现在以openlayers官网Examples 第一个实例(View Animation)为例,说一下我修改的过程 首先,要把所有...

m0_37565924的博客 1657

openlayers 入门教程(十):style 篇

OpenLayers 提供了一种强大且灵活的方式来自定义地图上的矢量要素(如点、线、面)的样式,这些样式是通过 `ol/style` 模块中的 `ol.style.Style` 类和其他相关子类(如 `ol.style.Icon`、`ol.style.Stroke`、`ol.style.Fill`、`ol.style.Text` 等)来实现的。

大剑师兰特的GIS世界 4505

OpenLayer示例网址汇总

1.https://openlayers.org/en/latest/examples/feature-move-animation.html 图标 行进轨迹动画 使用后期渲染事件和矢量上下文沿线对标记要素设置动画。在该示例中,使用了编码折线。 2.https://openlayers.org/en/latest/examples/utfgrid.html?q=dynamic-data 有用...

sdfvsdfsdfsdfsd的博客 2615
上一篇: 三十七、openlayers官网示例Earthquakes Heatmap解析——在地图上加载热力图
下一篇: 三十八、openlayers官网示例Earthquakes with custom symbols——将矢量数据渲染为自定义图形
卷新心菜
博客等级 码龄4年 720粉丝 65原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值