3

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

codejunkie
  • 908
  • 2
  • 21
  • 34

1 Answers1

2

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).

IvanSanchez
  • 18,272
  • 3
  • 30
  • 45
  • How can I automatically adjust the zoom level of the map to fit all/ a majority of the polygons? – codejunkie Dec 01 '16 at 08:53
  • 1
    Get the bounds for every polygon, and create an instance of `L.Bounds` that extends over all the bounds. Read the leaflet docs, it should be simple to do by yourself. – IvanSanchez Dec 01 '16 at 09:02
  • http://stackoverflow.com/questions/16845614/zoom-to-fit-all-markers-in-mapbox-or-leaflet ---> helped me – codejunkie Dec 02 '16 at 03:40