首页 > 解决方案 > 如何格式化 PostgreSQL 查询以干净地返回 geojson?

问题描述

我遇到了与这篇文章类似的问题,其中使用 pg_fetch_all 返回我想要隐藏在关联数组中的数据。当我在 PgAdmin 中运行查询时,我得到了我期望作为特征集合的结果,那么格式化我的查询和 PHP 以将结果作为 geojson 对象返回的正确方法是什么?我的目标是为 Leaflet 地图获取 geojson。我正在查询我想要关联一些属性的单个位置的 shapefile。

这是我的查询和代码片段:

$query = "SELECT row_to_json(fc)
FROM ( SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As features
FROM (SELECT 'Feature' As type
   , ST_AsGeoJSON(lg.geom)::json As geometry
   , row_to_json((SELECT l FROM (SELECT id, photo, type) As l
     )) As properties
  FROM public.\"Peng\" As lg   ) As f )  As fc;";

$result = pg_query($query) or die('Query failed: ' . pg_last_error());
$geodata = pg_fetch_all($result);
print_r($geodata);

虽然我确信我可以深入研究对象,但必须有一种更简洁的方法来将 geojson 字符串发送给客户端。

标签: phppostgresqlleafletpostgisshapefile

解决方案


因此,在这种情况下,只需正确访问数组中的值$geodata[0]['row_to_json']


推荐阅读