postgis中构造geojson

论坛 期权论坛 期权     
选择匿名的用户   2021-6-2 19:26   6822   0

首先注意:

比如现在有两张表,一张population_rural表和一张sichuan表,population_rural表提供属性数据,sichuan表提供地理空间数据

population_rural表内容如下:

现在从population_rural表中查,并将结果表存在名为B的暂存表中

sichuan表内容如下:

现在从sichuan表中查,并将结果表存在名为A的暂存表中

想把geom字段命名为geometry,如下:

接着想把geometry字段中的数据改为json格式,用函数:st_asgeojson()可以实现:

现在想把A表和B表放在一块,有三种方式:

1:使用on连接

2:使用using连接

可以看到,使用USING(city),它会自动使用on A.city=B.city,而且结果只会保留一个city。

3:使用natural连接。推荐使用这个,因为这样就可以带入变量了。

NATURAL是USING 的简写形式。

注意:要合并的字段名要相同,否则自动合并后会有各自的两个字段,如下:

然后把查出的数据存到名为C 的暂存表中,如下:

接着想要添加值为Feature的type字段,并且构造properties字段

然后构造geojson外层

最后构造出geojson

最终构造geojson成功的代码:

 
  1. with A as( select name as city ,st_asgeojson(geom)::json as geometry,center from sichuan),

  2. B as (select city,sum(num) from population_rural GROUP BY city),

  3. C as(select * from A natural inner join B ),

  4. feature as( select 'Feature' as type, geometry, (select json_strip_nulls(row_to_json(fields)) from (select city,center,sum) as fields) as properties from C),

  5. features as(select 'FeatureCollection' as type, array_to_json(array_agg(feature.*)) as features from feature )

  6. select row_to_json(features.*) from features

例2:

现在有一张表,内容如下

 
  1. with a as( select name,center,st_asgeojson(geom)::json as geometry from sichuan)

  2. select * from a

把它转为geojson:

 
  1. feature as( select 'Feature' as type, geometry, (select json_strip_nulls(row_to_json(fields)) from (select name,center) as fields) as properties from a),

  2. features as(select 'FeatureCollection' as type, array_to_json(array_agg(feature.*)) as features from feature )

  3. select row_to_json(features.*) from features

综合:

 
  1. with a as( select name,center,st_asgeojson(geom)::json as geometry from sichuan),

  2. feature as( select 'Feature' as type, geometry, (select

  3. json_strip_nulls(row_to_json(fields)) from (select name,center) as fields) as

  4. properties from a),

  5. features as(select 'FeatureCollection' as type, array_to_json(array_agg(feature.*)) as

  6. features from feature )

  7. select row_to_json(features.*) as geojsondata from features

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP