turf-inside

Checks to see if a point is inside of a polygon. The polygon can be convex or concave. The function accepts any valid polygon or multipolygon and accounts for holes.

<!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" type="text/javascript"></script>
    <script src="assets/js/helpers.js"></script>
    <title>Turf and OpenLayers 3 - Inside</title>
  </head>
  <body>
    <div id="map" class="map"></div>
    <button id="drawtoggle" data-toggle="false" type="button">
      Activate/Desactivate drawing
    </button>
    <script type="text/javascript">

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

      // Create a style function for coloring points
      var pointStyles = (function() {
        var defaultStyle = [
          new ol.style.Style({
            image: new ol.style.Circle({
              stroke: new ol.style.Stroke({
                color: 'white'
              }),
              fill: new ol.style.Fill({
                color: '#1f6b75'
              }),
              radius: 4
            })
          })
        ];
        var ruleStyle = [new ol.style.Style({
          image: new ol.style.Circle({
            stroke: new ol.style.Stroke({
              color: 'white'
            }),
            fill: new ol.style.Fill({
              color: 'red'
            }),
            radius: 5
          })
        })];
        return function(feature, resolution) {
          var isInside = feature.get('isInside');
          if (isInside != undefined && isInside === true) {
            return ruleStyle;
          } else {
            return defaultStyle;
          }
        };
      })();

      // Declare vector layers, one for points and the other for the drawing
      var vectorLayer = new ol.layer.Vector({
        source: vectorSource,
        style: pointStyles
      });

      var vectorLayerDrawing = new ol.layer.Vector({
        source: vectorSourceDrawing
      });

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

      // Generate and add random features
      var newfeatures = (new ol.format.GeoJSON()).readFeatures(
        turf.random('point', 50, {
          bbox: ol.proj.transformExtent(map.getView().calculateExtent(map.getSize()), 'EPSG:3857', 'EPSG:4326')
        }), {
          featureProjection: 'EPSG:3857'
        }
      );
      vectorSource.addFeatures(newfeatures);

      // Create a button and bind a click function
      var button = document.getElementById('drawtoggle');
      var draw;
      button.addEventListener('click', function(e) {
        var toggleState = this.getAttribute('data-toggle');
        // Some issues due to type. Can't use !toggleState to go back and forth
        // between true and false (type not boolean but string)
        // Remove drawing interaction if true
        if (toggleState === 'true') {
          this.setAttribute('data-toggle', 'false');
          map.removeInteraction(draw);
        } else {
          this.setAttribute('data-toggle', 'true');
          // Assign draw interaction (variable created before for scope reason)
          draw = new ol.interaction.Draw({
            source: vectorSourceDrawing,
            type: 'Polygon'
          });

          // Bind event on the draw component
          draw.on('drawend', function(e) {
            // Remove immediately other features for demo purpose
            vectorSourceDrawing.clear();
            var formatDraw = new ol.format.GeoJSON();
            var featureDraw = formatDraw.writeFeature(e.feature, {
              featureProjection: 'EPSG:3857'
            });

            // Loop on features
            vectorSource.getFeatures().forEach(function(el) {
              var feat = formatDraw.writeFeature(el, {
                featureProjection: 'EPSG:3857'
              });
              // Below function can be replaced with ol.extent.intersects
              // if drawing a bounding box
              var isInside = turf.inside(JSON.parse(feat), JSON.parse(featureDraw));
              el.set('isInside', isInside);
            });
          });
          // Add the interaction to the map
          map.addInteraction(draw);
        }
      });
    </script>
  </body>
</html>

results matching ""

    No results matching ""