turf-centroid

Calculates the centroid of a polygon Feature or FeatureCollection using the geometric mean of all vertices. This lessens the effect of small islands and artifacts when calculating the centroid of a set of polygons.

<!doctype html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="https://rawcdn.githack.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" type="text/css">
    <link rel="stylesheet" href="assets/css/styles.css" type="text/css">
    <script src="//cdn.jsdelivr.net/npm/@turf/turf@5/turf.min.js"></script>
    <script src="https://rawcdn.githack.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
    <script src="assets/js/es6-promise.min.js"></script>
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL,fetch"></script>
    <script src="assets/js/helpers.js"></script>
    <title>Turf and OpenLayers - Centroid</title>
  </head>
  <body>
    <div id="map" class="map"></div>
    <script type="text/javascript">

      // Declare a source for points and drawing
      var vectorSourceCentroid = new ol.source.Vector();
      var vectorSourcePolygon = new ol.source.Vector();

      var polygonStyle = [new ol.style.Style({
        stroke: new ol.style.Stroke({
          color: 'white'
        }),
        fill: new ol.style.Fill({
          color: '#1f6b75'
        })
      })];

      var centroidStyle = [new ol.style.Style({
        image: new ol.style.Circle({
          stroke: new ol.style.Stroke({
            color: 'white'
          }),
          fill: new ol.style.Fill({
            color: 'black'
          }),
          radius: 5
        })
      })];

      var vectorLayerCentroid = new ol.layer.Vector({
        source: vectorSourceCentroid,
        style: centroidStyle
      });

      var vectorLayerPolygon = new ol.layer.Vector({
        source: vectorSourcePolygon,
        style: polygonStyle
      });

      // Instantiate a map and add layers
      var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          }),
          vectorLayerPolygon,
          vectorLayerCentroid
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([-1.5603, 47.2383]),
          zoom: 11
        })
      });

      fetch('assets/data/agglo_poly_nantes.geojson').then(function(response) {
        return response.json().then(function(polygon) {
          console.log(polygon);

          var centroid = turf.centroid(polygon);
          console.log(centroid);
          vectorSourceCentroid.addFeatures(geojsonToFeatures(centroid, {
            featureProjection: 'EPSG:3857'
          }));

          vectorSourcePolygon.addFeatures(geojsonToFeatures(polygon, {
            featureProjection: 'EPSG:3857'
          }));
        });
      });
    </script>
  </body>
</html>

results matching ""

    No results matching ""