使用query-overpass和turf.js将geojson多边形转换为具有节点的点

时间:2018-05-14 13:35:00

标签: node.js openstreetmap geojson overpass-api turfjs

我使用节点模块“query-overpass”查询来从openstreetmaps获取farmhops。我想将所有多边形转换为此脚本中的点。我使用turf.js来获取theese多边形的质心,但我无法以永久的方式更改对象。到目前为止,这是我的代码:

const query_overpass = require("query-overpass");
const turf = require ("turf");
const fs = require("fs")
let test
let filename = "data/test.js"
let bbox = "48.91821286473131,8.309097290039062,49.0610446187357,8.520584106445312";
console.log('starting query for ' +filename)
console.log('bbox: ' +bbox)
let query = ` 
  [out:json][timeout:250];
  // gather results
  (
  // query part for: “vending=milk”
  node["vending"="milk"](${bbox});
  way["vending"="milk"](${bbox});
  relation["vending"="milk"](${bbox});
  // query part for: “shop=farm”
  node["shop"="farm"](${bbox});
  way["shop"="farm"](${bbox});
  relation["shop"="farm"](${bbox});
  // query part for: “vending=food”
  node["vending"="food"](${bbox});
  way["vending"="food"](${bbox});
  relation["vending"="food"](${bbox});
  );
  // print results
  out body;
  >;
  out skel qt;
`;

// query overpass, write result to file
query_overpass(query, (error, data)  => {
    data = JSON.stringify(data , null, 1)
    console.log(data)
    test = JSON.parse(data)


//create centroids for every polyon and save them as a point
    for (var i = 0; i < test.features.length; i++) { 
      console.log("Log: " +test.features[i].geometry.type)
      console.log("Log: " +test.features[i].properties.name)
      if (test.features[i].geometry.type === "Polygon"){
        console.log("polygon detected")
        var centroid = turf.centroid(test.features[i]);
            var lon = centroid.geometry.coordinates[0];
            var lat = centroid.geometry.coordinates[1];
            console.log(" lon: " +lon +" lat: " +lat)

            test.features[i].geometry.type = 'Point'
            //delete Polygon structure and insert centroids as new points here
            console.log("polygon deleted and changed to point")
      }

  }
  console.log(test)
   fs.writeFile(filename, `var file = ${test};` , ["utf-8"], (error, data) => {if (error) {console.log(error)}})
 }, {flatProperties: true}
)

似乎我可以更改for循环中的内容,但是稍后保存数据时它们不会出现。这基本上是一个如何正确编辑json对象的问题,但我无法弄清楚为什么它在这里根本不起作用。

所以基本上有两个问题:

  • 为什么我无法覆盖上面示例中的geometry.type?
  • 如何删除旧多边形并为要素添加新点?

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

这很复杂......为什么不让Overpass API完成这项工作并使用out center;代替out body;>;out skel qt;来返回所有节点,方式和关系的中心点。你可以先用overpass-turbo.eu来试试这个。