postgis 返回 geojson

GeoJSON 特征集合:

{
   "type": "FeatureCollection",
   "features": [
       {
           "type": "Feature",
           "geometry": {
               "type": "Point",
               "coordinates": [102.0, 0.5]
           },
           "properties": {
               "prop0": "value0"
           }
       },
       {
           "type": "Feature",
           "geometry": {
               "type": "LineString",
               "coordinates": [
                   [102.0, 0.0],
                   [103.0, 1.0],
                   [104.0, 0.0],
                   [105.0, 1.0]
               ]
           },
           "properties": {
               "prop0": "value0",
               "prop1": 0.0
           }
       },
       {
           "type": "Feature",
           "geometry": {
               "type": "Polygon",
               "coordinates": [
                   [
                       [100.0, 0.0],
                       [101.0, 0.0],
                       [101.0, 1.0],
                       [100.0, 1.0],
                       [100.0, 0.0]
                   ]
               ]
           },
           "properties": {
               "prop0": "value0",
               "prop1": {
                   "this": "that"
               }
           }
       }
   ]
}

ST_AsGeoJSON 函数:

SELECT
	ST_AsGeoJSON(ST_Transform(geom,4326))
FROM
	tb_base_hazard

在这里插入图片描述

可以看出 ST_AsGeoJSON 返回一个 Geometry

此为 postgis 3.x 以下方法

WITH feature AS (
	SELECT
		'Feature' AS "type",
		st_asgeojson ( geom ) :: json AS "geometry",
		(
			SELECT
				json_strip_nulls ( row_to_json ( fields ) )
			FROM
				(
					SELECT
						id, hazard_name
				) as fields
		) AS "properties" 
	FROM
		tb_base_hazard AS h 
	WHERE
		1=1
	),
	features AS ( 
		SELECT 
			'FeatureCollection' AS "type", 
			array_to_json ( ARRAY_AGG ( feature.* ) ) AS "features" 
		FROM feature 
	) 
		SELECT row_to_json ( features.* ) FROM features;

此为 postgis 3.x 方法 更快更简洁

官方文档
在这里插入图片描述
可见直接返回单个 feature

WITH features AS (
	SELECT
	( 
		SELECT 
			st_asgeojson ( fields.* ) :: json 
		FROM ( 
			SELECT 
				c.ID,c.the_geom 
			) AS fields 
	) AS feature 
	FROM
		cities AS c 
	WHERE
		1 = 1 
	) 
SELECT
	json_build_object ( 
		'type', 'FeatureCollection', 
		'features', json_agg ( features.feature ) 
	) 
FROM
	features;
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值