You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用query-overpass与turf.js转换GeoJSON多边形转点时对象修改失效求助

解决你的GeoJSON修改与保存问题

疑问1:为何无法覆盖geometry.type属性?

其实你已经成功修改了属性,问题出在最后保存文件的步骤上!你现在用${test}直接把JavaScript对象插入模板字符串,JS会自动把对象转换成[object Object],导致写入文件的内容根本不是你修改后的GeoJSON数据,所以看起来像是修改没生效。

另外,你一开始把返回的data先转成字符串再解析成test是完全多余的操作——query-overpass回调里的data已经是解析好的GeoJSON对象了,这一步不仅没用,还可能引入不必要的问题。

疑问2:如何删除旧多边形结构并添加新的点数据?

不需要“删除”旧结构,直接覆盖geometry里的内容就行:除了把type改成Point,还要把coordinates替换成质心的坐标数组(质心的坐标是centroid.geometry.coordinates,格式为[lon, lat])。

修正后的完整代码

const query_overpass = require("query-overpass");
const turf = require("turf");
const fs = require("fs");

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, test) => { // 直接用返回的data作为test,不需要额外解析
  if (error) {
    console.error('查询出错:', error);
    return;
  }

  // 创建质心点替换多边形
  for (let i = 0; i < test.features.length; i++) {
    const feature = test.features[i];
    console.log("Log: " + feature.geometry.type);
    console.log("Log: " + feature.properties.name);

    if (feature.geometry.type === "Polygon") {
      console.log("polygon detected");
      const centroid = turf.centroid(feature);
      const [lon, lat] = centroid.geometry.coordinates;
      console.log(" lon: " + lon + " lat: " + lat);

      // 直接覆盖geometry的type和coordinates
      feature.geometry.type = 'Point';
      feature.geometry.coordinates = centroid.geometry.coordinates;
      console.log("polygon converted to point");
    }
  }

  console.log(test);

  // 正确序列化对象为JSON字符串后写入文件
  fs.writeFile(filename, `var file = ${JSON.stringify(test, null, 1)};`, "utf-8", (error) => {
    if (error) {
      console.error('写入文件出错:', error);
    } else {
      console.log('文件保存成功!');
    }
  });
}, { flatProperties: true });

关键修改说明

  1. 移除多余的JSON序列化/解析步骤:直接使用query-overpass返回的test对象,避免不必要的转换。
  2. 完整替换Geometry内容:不仅修改type,还替换coordinates为质心的坐标,确保GeoJSON结构合法。
  3. 正确保存文件:用JSON.stringify(test, null, 1)把对象转换成格式化的JSON字符串,再写入文件,这样才能保留所有修改。

内容的提问来源于stack exchange,提问作者Stefan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:41:23