codejunkie
codejunkie

Reputation: 968

Determine the center point of multiple polygons in leaflet

How can I determine a point central to multiple polygons?

What I mean is a point that is indicated as a red dot in the attached figure. PS: The number of polygons can vary. The algorithm should be able to determine an approximate point which is central to a majority of the polygons.

enter image description here

Upvotes: 4

Views: 6040

Answers (1)

IvanSanchez
IvanSanchez

Reputation: 19069

There are several approaches to this, depending on what you exactly want.

The easiest one is to calculate the centroid of the polygons as a whole. A lot of geospatial software is capable of calculating centroids of multipolygons, polygons with multiple outer rings, etc.

If you're using Leaflet and GeoJSON, my personal choice would be to use Turf.js for the geoprocessing, e.g.:

var poly1 = {
  type: 'Feature',
  geometry: {
    type: 'Polygon',
    coordinates: [[[10, 10], [10, 20], [20, 15]]]
  }
}; 

var poly2 = {
  type: 'Feature',
  geometry: {
    type: 'Polygon',
    coordinates: [[[10, 45], [20, 40], [20, 50]]]
  }
};

var featCollection = {
  type: 'FeatureCollection',
  features: [poly1, poly2]
}

L.geoJSON(featCollection).addTo(map)

// Magic happens here:
var centroid = turf.centroid(featCollection);

L.geoJSON(centroid).addTo(map);

You can see that as a working example.

Now, the centroid is the center of density of the polygons. If you remember high-school geometry, you remember there are lots of centers for something as simple as a triangle, each with its own properties.

This is true for more complex polygons: some times you don't want the centroid. If you take geodesics into account (i.e. the fact that the earth is not a 2D plane), things get... way more complicated.

So depending on what you want to do, you might want a more elaborated solution, in order to find not the centroid, but a point which minimizes the distance to any of the polygons (understood as the minimum distance to any of the vertices to that polygon).

Upvotes: 3

Related Questions