从坐标POSTGIS创建的线串

时间:2015-08-17 22:59:32

标签: database postgresql postgis

有人可以帮忙吗?

以下是我的代码(sql)中不起作用的部分:

SELECT ST_LENGTH(geom) into distance FROM
     SELECT ST_GeographyFromText('srid=4326;linestring(lon_bus lat_bus, lon_stop lat_stop)') AS geom)
     AS dis;

lon_buslat_buslon_stoplat_stop是我从数据库中获得的坐标。当我尝试这个时,我有一个解析错误。但是当我用数字替换这些变量时,它可以工作。有人可以帮我吗?我想将这些变量保存在我的代码中。

1 个答案:

答案 0 :(得分:0)

它不起作用,因为带变量的WKT无效。请记住,WKT is just regular text,所以不要将WKT与SQL混淆。

您可以从两个点几何中make a LineString,然后将其转换为::geography

SELECT ST_MakeLine(ST_MakePoint(lon_bus, lat_bus),
                   ST_MakePoint(lon_stop, lat_stop))::geography AS geog
FROM (
  SELECT 1 AS lon_bus, 2 AS lat_bus, 3 AS lon_stop, 4 AS lat_stop
) AS data;

要获得测地长度,请在地理位置使用ST_Length。

根据用法,问题不在于如何制作线串,而在于如何计算两个地理位置之间的距离。有几种方法可以做到这一点:

SELECT
  ST_Distance(bus, stop) AS cartesian_distance,
  ST_Distance_Sphere(bus, stop) AS sphere_distance,
  ST_Distance(bus::geography, stop::geography) AS geography_distance,
  ST_Length(ST_MakeLine(bus, stop)::geography) AS geography_length
FROM (
  SELECT ST_MakePoint(lon_bus, lat_bus) AS bus, ST_MakePoint(lon_stop, lat_stop) AS stop
  FROM (SELECT 1 AS lon_bus, 2 AS lat_bus, 3 AS lon_stop, 4 AS lat_stop) AS data
) AS data;
-[ RECORD 1 ]------+-----------------
cartesian_distance | 2.82842712474619
sphere_distance    | 314283.687770102
geography_distance | 313588.397192902
geography_length   | 313588.397192902

最后两个得到相同的结果。如果您不需要线串(例如在地图上绘制),则最简单的方法用于geography_distance