postgis中构造geojson

首先注意:

比如现在有两张表,一张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.  
  3. 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.  
  3. features as(select  'FeatureCollection' as type, array_to_json(array_agg(feature.*)) as features from feature )

  4.  
  5. select row_to_json(features.*) from features

综合:

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

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

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

  5. properties from a),

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

  8. features from feature )

  9.  
  10. select row_to_json(features.*) as geojsondata from features

 

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值