如何制作一个简单的节点 API 来从 PostGIS 提供 GeoJSON 服务?

问题描述 投票:0回答:1

我正在尝试编写一个节点 API,它将提供直接的 GeoJSON,可供 Leaflet 等应用程序直接使用。我的 SQL 命令是这样的:

SELECT 
json_build_object('type', 'FeatureCollection', 'features', json_agg(ST_AsGeoJSON(t.*)::json)) 
FROM 
my_table AS t

API 代码如下所示:

router.get('/api/data', async(req, res) => {
    try {
        const data = await pool.query(
            "SELECT json_build_object('type', 'FeatureCollection', 'features', json_agg(ST_AsGeoJSON(t.*)::json)) FROM my_table AS t"
            );
        res.json(data);

API 提供的 JSON 如下所示:

{
"command":"SELECT",
"rowCount":1,
"oid":null,
"rows":[{
"json_build_object":{
"type":"FeatureCollection",
"features":[{
"type":"Feature","geometry":{
"type":"MultiPolygon",
"coordinates":
...

显然,我只希望 API 提供

{"type":"FeatureCollection" ...
服务,但它包含在
command
rows
json_build_object
中。

如何编写 API 代码来输出标准 GeoJSON 而仅此而已?

这是我昨天提出的问题的延续,它触及了我遇到的问题的核心。我已阅读 PostGIS 文档,并浏览了 SE 和 SO,但无济于事。我觉得这是一个简单的修复,我只是不知道,因为我是这种开发的新手。

node.js postgresql api express postgis
1个回答
0
投票

你就在那里,尝试这样的事情

 app.get('/geojson', async (req, res) => {
  try {
    const client = await pool.connect();
    const result = await client.query(`SELECT json_build_object('type', 'FeatureCollection', 'features', json_agg(ST_AsGeoJSON(t.*)::json)) FROM us_states AS t`);

    // Send the GeoJSON as the response
    res.json(result.rows[0].geojson);

    client.release();
  } catch (err) {
    console.error(err);
    res.status(500).send('Internal Server Error');
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.