Leaflet.js union/merge circles

2019-06-03 22:14发布

问题:

I draw a lot of circles onto a map using Leaflet.js. Sometimes many of these circles overlap. Even though the circles are transparent (CSS opacity set to 0.3), the map then cannot be seen properly anymore. I am looking for a way to create one figure out of n circles. I found Greiner Hormann, however, this seems to work for polygons only.

My question is: How is it possible to union circles that are to be added to a leaflet.js map.

Thank you in advance.

回答1:

I don't think there is an easy way to perform union operations on L.circle objects. What you can do, however, is use Leaflet Geodesy to create ~circular polygons and perform union operations on those. My suggestion would be to create your circles as LGeo.circle objects and place them all in the same layerGroup, e.g.:

var cities = new L.LayerGroup();
var chicago = LGeo.circle([41.84, -87.68], 1000000).addTo(cities);
var newOrleans = LGeo.circle([29.95, -90.07], 1000000).addTo(cities);
var denver = LGeo.circle([39.74, -104.99], 1000000).addTo(cities);

This is handy because once they are grouped together, you can use .getLayers() to get an array of all the layers, then iterate over them to get their union. This function, for example, will take an array of your layers and return a L.geoJson object of their union, calculated with Turf.js:

function unify(polyList) {
  for (var i = 0; i < polyList.length; ++i) {
    if (i == 0) {
      var unionTemp = polyList[i].toGeoJSON();
    } else {
      unionTemp = turf.union(unionTemp, polyList[i].toGeoJSON());
    }
  }
  return L.geoJson(unionTemp);
}

var cityUnion = unify(cities.getLayers()).addTo(map);

Here is an example fiddle of this at work:

http://fiddle.jshell.net/nathansnider/ehpL8fho/

[ While using Turf is probably the better solution, if you want to try using Greiner Hormann instead, here is an example fiddle using that. You may notice that this produces an error if you try it with circles that are not all overlapping. This is because the Greiner Hormann routine returns nothing when the input polygons do not overlap. Using Turf will avoid this problem, because its union routine handles non-contiguous polygons by returning a multipolygon object instead. ]