使用ST_GeomFromText(PostGIS)从不一致的字符串中获取双精度值

时间:2013-10-07 09:12:11

标签: sql postgresql postgis

我有一个PostgreSQL表,其中的列包含以下格式的字符串:

    '3.985 58.934, 4.56 61.2323, 5.4 63.234355, 3.25982 59.309' 
    '3.985 58.934, 4.56 61.2323, 5.4 63.234355, 3.25982 59.309, 4.5632 58.32423'
    'and so on...'

如您所见,该列包含不同长度的坐标,一个行中的字符串。我想使用PostGIS功能:

    ST_GeomFromText('LINESTRING(3.985 58.934, 4.56 61.2323, 5.4 63.234355, 3.25982 
    59.309)', 4326)  

现在出现以下问题:

PostGIS功能需要格式正确的双精度值,如上所示。当我不知道字符串的长度和每个坐标有多少个字符时,如何从字符串生成双精度值?

提前感谢您的帮助!

Jann

1 个答案:

答案 0 :(得分:1)

According to the docsST_GeomFromText需要(text, integer),而非(double precision)

您需要做的只是CONCAT(),它应该有效。

解决方案

ST_GeomFromText(CONCAT('LINESTRING(', "YourTable"."YourString", ')'), 4326);

供您测试

SELECT
    ST_GeomFromText('LINESTRING(3.985 58.934, 4.56 61.2323, 5.4 63.234355, 3.25982 59.309)', 4326),
    CONCAT('LINESTRING(', "T1"."C1", ')'),
    ST_GeomFromText(CONCAT('LINESTRING(', "T1"."C1", ')'), 4326)
FROM
    (
        SELECT '3.985 58.934, 4.56 61.2323, 5.4 63.234355, 3.25982 59.309, 4.5632 58.32423' AS "C1"
    ) AS "T1";

只是为了好玩

我决定将你的字符串转换为最初请求的DOUBLE PRECISION,然后再转换成字符串...最终结果与上面相同,但它做了很多工作。不过,这就是你要求的。

SELECT
    ST_GeomFromText(CONCAT('LINESTRING(', (SELECT STRING_AGG(ARRAY_TO_STRING("Line"."Points", ' '), ',') FROM REGEXP_MATCHES(ARRAY_TO_STRING(REGEXP_SPLIT_TO_ARRAY("T1"."C1", E', | ')::DOUBLE PRECISION[], ' '), '(\d*\.\d*) (\d*\.\d*)', 'g') AS "Line"("Points")), ')'), 4326)
FROM
    (
        SELECT '3.985 58.934, 4.56 61.2323, 5.4 63.234355, 3.25982 59.309, 4.5632 58.32423'::TEXT AS "C1"
    ) AS "T1";