geospatialturfjs

using turf.points to assign each gis coordinate with related property?


i have a set of geo points, such as

let geo_points = [  
   { "lnglat":[100,50], "id": 1 },
   { "lnglat":[100,50], "id": 2 },
   ....
];

by using turf.js, I can transform the geo points with turf points in this method and try to see which points in the predefined geojson

let lnglats = _.map( geo_points, function(item){
    return item.lnglat;
});
let ids = _.map( geo_points, function(item){
    return item.id;
});
let points = turf.points( lnglats  );

let ptsWithin = turf.pointsWithinPolygon( points , predefined);

the output of turf.pointsWithinPolygon only shows the lnglat without id property.

Seeing the documentation, it can add property to points.

 turf.points( lnglats , ids );

trying the method above only add the same property to each point in lnglat array .

{ 
   type: 'FeatureCollection', features:
       [ {type: 'Feature', properties: [ 1, 2 ], geometry: {…}}
         {type: 'Feature', properties: [ 1, 2 ], geometry: {…}}
       ]
}

what I really need is

{ 
   type: 'FeatureCollection', features:
       [ {type: 'Feature', properties: 1, geometry: {…}}
         {type: 'Feature', properties: 2, geometry: {…}}
       ]
}

how would I assign each point with lnglat and related id


Solution

  • Turf has no knowledge of your ids so can't pass them back in the result. Instead, try creating a Feature for each point, which can have its own embedded properties.

    const geo_points = [{
        "lnglat": [100.1, 50.1],
        "id": 1
      },
      {
        "lnglat": [100.2, 50.2],
        "id": 2
      },
    ];
    
    const poly = turf.polygon([
      [
        [99, 49],
        [99, 51],
        [101, 51],
        [101, 49],
        [99, 49]
      ]
    ]);
    
    const pts = geo_points.map(function(item) {
      // Create a Feature<Point> for each geo_point, embedding the id as a property. 
      return turf.point(item.lnglat, {
        id: item.id
      });
    });
    
    const ptsWithin = turf.pointsWithinPolygon(turf.featureCollection(pts), poly);
    
    console.log(ptsWithin);
    <script src="https://cdn.jsdelivr.net/npm/@turf/turf@7.2.0/turf.min.js"></script>