从坐标 POSTGIS 创建的线串

linestring created from coordinates 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 是我从数据库中获取的坐标。当我尝试这个时,我有一个解析错误。但是当我用数字替换这些变量时,它就起作用了。有人可以帮我吗?我想在我的代码中保留这些变量。

它不起作用,因为带有变量的 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.