如何使用Mapbox的群集设置reduce选项?

时间:2018-05-23 08:49:32

标签: javascript mapbox

我用Mabpox-gl-js v0.45 POC-ing集群。

我想自定义我的群集属性(实际默认值为point_count和point_count_abbreviated)。我的每个点(每个城市一个)都有一个表面属性(整数),我希望在点聚集时求和。

我在mapbox's sources中看到了一个用于计算自定义属性的reduce函数的引用:

SuperCluster.prototype = {
    options: {
        minZoom: 0,   // min zoom to generate clusters on
        // .....
        log: false,   // whether to log timing info

        // a reduce function for calculating custom cluster properties
        reduce: null, // function (accumulated, props) { accumulated.sum += props.sum; }

        // initial properties of a cluster (before running the reducer)
        initial: function () { return {}; }, // function () { return {sum: 0}; },

        // properties to use for individual points when running the reducer
        map: function (props) { return props; } // function (props) { return {sum: props.my_value}; },
    },

但我在文档中没有看到任何关于它的提及。 如何设置这些选项?

Mapbox似乎不会发布这些界面(see cluster's documentation),并且没有在provided exemple上提及:

map.addSource("earthquakes", {
    type: "geojson",
    // Point to GeoJSON data. This example visualizes all M1.0+ earthquakes
    // from 12/22/15 to 1/21/16 as logged by USGS' Earthquake hazards program.
    data: "/mapbox-gl-js/assets/earthquakes.geojson",
    cluster: true,
    clusterMaxZoom: 14, // Max zoom to cluster points on
    clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
});

2 个答案:

答案 0 :(得分:1)

有人给了我一个解决方法:不要使用嵌入式supecluster,而是自己创建并将其用作源:

var myCluster = supercluster({
    radius: 40,
    maxZoom: 16,
    reduce: function(p) { /* I can use reduce/map/... functions! */ }
});

// My clustered source is created without Mapbox's clusters since I managed my clusters outside Mapbox library.
map.addSource("earthquakes", {
    type: "geojson",
    data : {
      "type" : "FeatureCollection",
      "features" : []
    }
});

function loadRemoteGeoJson() {
    var features
    // Do what you want, when you want to retrieve remote features...
    // ...
    // In the end set features into your supercluster
    myCluster.load(features)
    pushClusterIntoMapbox(map)
}

// Function to call when you load remote data AND when you zoom in or out !
function pushClusterIntoMapbox(map) {
  // I maybe should be bounded here...
  var clusters = myCluster.getClusters([ -180.0000, -90.0000, 180.0000, 90.0000 ], Math
      .floor(map.getZoom()))

  // My colleague advice me to use http://turfjs.org as helper but I think it's quite optionnal
  var features = turf.featureCollection(clusters)
  map.getSource("earthquakes").setData(features)
}

答案 1 :(得分:0)

它看起来好像是常规缩减。每个点都会调用一个,并允许您使用该点的属性为整个集群创建属性。

所以,如果你像这样定义你的;

supercluster({
  reduce: (clusterProps, pointProps) => {
    clusterProps.sum += pointProps.surface;
  }
});

然后,群集上的sum属性将是点上所有surface属性的总和。