Search code examples
arraysjsonturfjs

Feeding array to json for use in turf.polygon, structure problems


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


Solution

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