Clustered Features——聚合要素

来源:互联网 发布:程序员大学学什么专业 编辑:程序博客网 时间:2024/06/05 22:32

This example shows how to do clustering on point features.

这个例子用来展示如何对点要素尽心聚合。


代码:

<!DOCTYPE html><html>  <head>    <title>Clustered Features</title>    <link rel="stylesheet" href="https://openlayers.org/en/v4.2.0/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.2.0/build/ol.js"></script>  </head>  <body>    <div id="map" class="map"></div>    <form>      <label>cluster distance</label>      <input id="distance" type="range" min="0" max="100" step="1" value="40"/>    </form>    <script>      // 距离      var distance = document.getElementById('distance');      // 点的数量      var count = 20000;      var features = new Array(count);      var e = 4500000;      // 创建点要素      for (var i = 0; i < count; ++i) {        var coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e];        features[i] = new ol.Feature(new ol.geom.Point(coordinates));      }      // 创建矢量数据源      var source = new ol.source.Vector({        features: features      });      // 创建聚合数据源      var clusterSource = new ol.source.Cluster({        distance: parseInt(distance.value, 10), // 距离        source: source // 数据源      });      // 样式缓存数组      var styleCache = {};      // 聚合矢量图层      var clusters = new ol.layer.Vector({        source: clusterSource,        // 样式函数        style: function(feature) {          var size = feature.get('features').length;          var style = styleCache[size];          if (!style) {            style = new ol.style.Style({              image: new ol.style.Circle({                radius: 10,                stroke: new ol.style.Stroke({                  color: '#fff'                }),                fill: new ol.style.Fill({                  color: '#3399CC'                })              }),              text: new ol.style.Text({                text: size.toString(),                fill: new ol.style.Fill({                  color: '#fff'                })              })            });            styleCache[size] = style;          }          return style;        }      });      // 栅格图层      var raster = new ol.layer.Tile({        source: new ol.source.OSM()      });      // 初始化地图      var map = new ol.Map({        layers: [raster, clusters],        target: 'map',        view: new ol.View({          center: [0, 0],          zoom: 2        })      });      // 监听range的input事件      distance.addEventListener('input', function() {        clusterSource.setDistance(parseInt(distance.value, 10));      });    </script>  </body></html>


原创粉丝点击