0

I have a linestring and a polygon and I am using turf.booleanIntersect() to determine if the line goes through the polygon. The example that i have tested and works is:

var poly1 = turf.polygon([
                [
                    [148.535693, -29.6],
                    [154.553967, -29.64038],
                    [154.526554, -33.820031],
                    [148.535693, -33.6],
                    [148.535693, -29.6]
                ]
            ]);
            //const p1 = L.geoJSON(poly1).addTo(mymap);

            console.log("TEST: " + turf.booleanIntersects(line, poly1));

In my real code I read the polygon values from a file and need to insert them into an array which needs to be converted into a "GeoJSON Feature or Geometry" (from webpage).

I am having trouble getting the array to json convert correct.

var polygonlines = [];
var start = [long,lat]; 
polygonlines.push([start]); //add multiple of these points to the to polygonlines array
//create my json
var geojsonPolygon =
    {
    "type": "Feature",
    "properties": {},
    "geometry": {
    "type": "Polygon",
    "coordinates": polygonlines
    }
}

var turfpolygon = turf.polygon(geojsonPolygon.data.geometry.coordinates); //ERROR HERE
const p2 = L.geoJSON(turfpolygon).addTo(mymap);
var result = turf.booleanIntersects(line, turfpolygon)

The error I get is "Uncaught Error Error: Each LinearRing of a Polygon must have 4 or more Positions."

I can't quite get the structure of the geojsonPolygon correct. I think that it is look at geojsonPolygon Array(1) in attached picture instead of Array(10), but I can't work out how to fix it.

Would love some help getting this structure fixed. Thank you :)

p.s. please ignore values of lat/longs, just examples.

I have seen this question but it hasn't helped How to feed JSON data of coordinates to turf.polygon?

enter image description here

tj26
  • 197
  • 1
  • 10
  • Turfjs uses long then lat, thus, `start = [lat,long]` is wrong. Also when you create a polygon, make sure it has at least 4 pairs of (long,lat). – swatchai Nov 10 '22 at 10:02
  • @swatchai Sorry lat,long a typo. There are 10 pairs of long,lat as shown in image geojsonpolygon Coordinates: Array(10) – tj26 Nov 10 '22 at 10:30
  • `geojsonPolygon.data.geometry.coordinates` causes error because there is no `data` key in `geojsonPolygon`. And if it works, coordinates in `polygonlines` could be another error. Check the correct geojson data structure in my demo LIVE code. – swatchai Nov 10 '22 at 12:32

2 Answers2

0

Ongoing answer..., content and code will be edited as needed.

Here is a LIVE demo code that you can run to see how it works. It may help answering the question.

Usage:

  • click Run code snippet button
  • click Full page in top-right corner to see map and console

//Using turf_polygon object style
var poly1 = turf.polygon([
                [
                    [148.535693, -29.6],
                    [154.553967, -29.64038],
                    [154.526554, -33.820031],
                    [148.535693, -33.6],
                    [148.535693, -29.6]
                ]
            ]);

// Using geojson style data 
// Coordinates are slightly different from poly1
// This can be used as a good example to compare/contrast with your implementation
// This geojson of poly2 works, you can see it on the map.
var poly2 = {
      type: "Feature",
      properties: { id: 102, name: "Poly_2" },
      geometry: {
        type: "Polygon",
        coordinates: [
          [
            [148, -29],
            [154, -29],
            [154, -33],
            [148, -33],
            [148, -29]
          ]
        ]
      }
    };
       
var line12 = turf.lineString([[144, -30], [153, -31.8], [159, -32]]);
var line34 = turf.lineString([[144, -20], [160, -30]]);
            
/*  Init and draw Leaflet map  */
var map;

function initMap(coords, zoom) {
  // initialize map container
  map = L.map("mapid").setView(coords, zoom);
  // get the stamen toner-lite tiles
  var Stamen_Toner = L.tileLayer(
    "https://stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.{ext}",
    {
      attribution:
        'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> — Map data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
      subdomains: "abcd",
      minZoom: 0,
      maxZoom: 20,
      ext: "png"
    }
  );
  // add the tiles to the map
  Stamen_Toner.addTo(map);
  //disable scroll wheel zoom
  map.scrollWheelZoom.disable();
}


/* Leaflet use (lat,long) */
var coordinates = [-30, 150]; //[lat,long]
var zoom = 5;
initMap(coordinates, zoom);

//Add polygons and lines
L.geoJson(turf.featureCollection([poly1, poly2, line12, line34])).addTo(map);

// Intersection op
var result1 = turf.booleanIntersects(line12, poly1); //True
var result2 = turf.booleanIntersects(line34, poly1); //False
console.log(result1, result2);

//EOF
#mapid { height: 480px; width: 800px}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin="" />
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js" integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA==" crossorigin=""></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Turf.js/6.5.0/turf.min.js"></script>
<div id="mapid"></div>
swatchai
  • 17,400
  • 3
  • 39
  • 58
0

How to get the polygonline array into geojson for use in turf polygon:

var polygonlines = [];

//these 2 lines occur multiple times in a loop
{
  var start = [vol.lines[k].start.lng, vol.lines[k].start.lat]; 
  polygonlines.push(start); 
}

var geojsonPolygon =
{
        "type": "Feature",
        "properties": {},
        "geometry": {
        "type": "Polygon",
        "coordinates": [polygonlines]
}

var turfpolygon = turf.polygon(geojsonPolygon.geometry.coordinates);
turf.booleanIntersects(line, turfpolygon)   
tj26
  • 197
  • 1
  • 10