How to convert Turf.js polygon to WKT

1.9k Views Asked by At

I'm using Turf.js to generate circle geometry from point and radius, using the circle functions. Example:

c = turf.circle([0.0, 0.0], 100, {steps:1000, units:'kilometers'})

The returned result is Feature object, and the only way I managed to represent the geometry is by applying c.geometry.coordinates which returns an array.

However, my goal is to generate a WKT or at least a GeoJSON, but I haven't found a way to do so. Does anyone know how to do it with turf.js or alternatively know of a way to get a WKT representation of a circle with center and radius as inputs?

1

There are 1 best solutions below

0
On

To get GeoJSON text of the feature, you can do this

var gjs = JSON.stringify(polygon_object);

(Inverse check) To parse the string gjs and convert it back to object (GeoJSON) again

var ojn = JSON.parse(gjs);

Live code:-

const pgon = turf.polygon(
    [
      [
        [50.848677, 4.338074],
        [50.833264, 4.344961],
        [50.840809, 4.366227],
        [50.852455, 4.367945],
        [50.858306, 4.346693],
        [50.848677, 4.338074]
      ]
    ],
    { name: "pgon1" }
  );
  
  const coords0 = pgon.geometry.coordinates[0];
  
  // Create WKT of the polygon
  var phead = `POLYGON((`;
  var ptail =  `))`;
  var pbody = "";
  var cur_xy = "";
  coords0.forEach( function(item, index){
   //console.log(item, index);
   //lonlat.push([...item]); //OK
   cur_xy = item[0].toFixed(4) +" "+ item[1].toFixed(4);
   pbody += cur_xy + ","; 
  }, pbody);
  
  console.log("*WKT*", phead+pbody+cur_xy+ptail);
  
  // Create geojson of the polygon
  console.log("*GeoJSON*" + JSON.stringify(pgon));
<script src="https://cdnjs.cloudflare.com/ajax/libs/Turf.js/5.1.5/turf.min.js"></script>
<p>TurfJS uses GeoJSON to represent geometric features. Here a polygon feature is created and its geometry / properties are manipulated.<br/><br/>The result is printed on the console.</p>