turf.nearest

Takes a reference point and a FeatureCollection of Features with Point geometries and returns the point from the FeatureCollection closest to the reference. This calculation is geodesic.

<!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 3 - Nearest</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">

      // Style
      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
          })
        })
      ];

      // Declare a source for polygons
      var vectorSourcePoints = new ol.source.Vector();

      var vectorLayerPoints = new ol.layer.Vector({
        source: vectorSourcePoints,
        style: defaultStyle
      });

      // Declare a source for drawing
      var vectorSourceDrawing = new ol.source.Vector();
      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()
          }),
          vectorLayerPoints,
          vectorLayerDrawing
        ],
        view: new ol.View({
          center: ol.proj.transform(
            [-1.5603, 47.2383],
            'EPSG:4326',
            'EPSG:3857'
          ),
          zoom: 10
        })
      });

      var styleOverlay = 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
        })
      });

      // We will share the geojson content to be able to use Turf
      var myPoints;

      fetch('assets/data/key_shop_with_name_nantes_area.geojson').then(function(response) {
        return response.json().then(function(points_fc) {
          myPoints = points_fc;

          vectorSourcePoints.addFeatures(geojsonToFeatures(points_fc, {
            featureProjection: 'EPSG:3857'
          }));
        });
      })

      // Create a button and bind a click function
      var button = document.getElementById('drawtoggle');
      var draw;
      button.onclick = 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 is not boolean but a string)
        // Remove drawing interaction because
        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: 'Point'
          });

          // 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();
            featureDraw = formatDraw.writeFeature(e.feature.clone(), {
              dataProjection: 'EPSG:4326',
              featureProjection: 'EPSG:3857'
            });
            //vectorSourceDrawing.addFeature(e.feature);
            console.log(featureDraw);
            var nearest = turf.nearest(JSON.parse(featureDraw), myPoints);
            var featureId = nearest.properties.osm_id;
            console.log(nearest);
            // Loop on features
            vectorSourcePoints.getFeatures().forEach(function(feature) {
               if (feature.get('osm_id') === featureId) {
                 console.log('a');
                 feature.setStyle(styleOverlay);
               } else {
                console.log('b');
                 feature.setStyle(defaultStyle);
               }
            });
          });
          // Add the interaction to the map
          map.addInteraction(draw);
        }
      };

    </script>
    </body>
</html>

results matching ""

    No results matching ""