0

I have a nodejs server which is connected to PostgreSQL database. I need to create a polygon by using coordinates JSON with fields. In the PostgreSQL database there is a default column as "geom". I tried to add in this column but I think syntax is different with JSON geometry. How can I create a polygon by this way?

coordinates: "34.26874524537533,35.56726640638707,0 34.26879192651798,35.56702498591847,0 34.26950518727496,35.56715326545641,0 34.26951725656846,35.56706234584355,0 34.27010825157995,35.56717295252424,0 34.26990692317912,35.56756882284464,0 34.26974649403571,35.56795560177618,0 34.26906223739066,35.56777705096091,0 34.26860721018177,35.56769205885733,0 34.26874524537533,35.56726640638707,0"
  const deedID = deed.id;
  const coordinate = deed.kml.coordinate; //coming from kml file by using xml parser
  pool.query(
    `INSERT INTO mymap ("geom","deedID") VALUES (${coordinate},${deedID})`,
    (err, response) => {
      console.log(response);
      console.log(err);
      pool.end();
    }
  );

1 Answer 1

1

You are looking for ST_PolygonFromText. You need to modify your coordinates string beforehand. If you have z values you need to keep the third value (always 0 in your case), if not you need to pop those values.

// Keep the 0 values
coordinate = coordinate.split(" ").map(x => x.split(",").join(" ")).join(", ");

// Without the 0 values
coordinate = coordinate.split(" ").map(x => {
   const t = x.split(","); 
   t.splice(-1); 
   t.join(" "); 
   return t
}).join(", ")

const sqlInsert = `INSERT INTO mymap ("geom","deedID") VALUES (ST_PolygonFromText('POLYGON((${coordinate}))'),${deedID})`
7
  • Hi, thank you so much for answer. Its worked but when added geometry by this way, in map there is a only a point not a polygon. How can i fix this ?
    – firstlord
    Apr 25 at 5:51
  • What type is your "geom" column? Apr 25 at 6:57
  • type is geomety
    – firstlord
    Apr 25 at 6:59
  • 1
    I guess you are using WGS84 / EPSG:4326 as CRS - so the type should be geography(Polygon,4326) Apr 25 at 8:33
  • 1
    its worked problem is solved. thank you so much^^ i changed type to geography
    – firstlord
    Apr 25 at 19:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.