简体   繁体   English

在表中使用 ST_Distance

[英]Using ST_Distance in a table

I have a table with id, x,y value,I need to find the distance between two points using a function in posgresql.我有一个 id,x,y 值的表,我需要在 posgresql 中使用 function 找到两点之间的距离。

    CREATE OR REPLACE FUNCTION distances(lat1 float, lon1 float, lat2 float, lon2 float)
RETURNS float AS $dist$
    BEGIN
        SELECT ST_Distance(
  ST_GeogFromText('SRID=4326;POINT(lat1 lon1 )')
, ST_GeogFromText('SRID=4326;POINT(lat2 lon2)'), false);
    END;
$dist$ LANGUAGE plpgsql;

But error throws out when i pass the value:但是当我传递值时会抛出错误: 在此处输入图像描述

Kindly give me a sloution.请给我一个sloution。

There are a few things:有几件事:

  • You were trying to concatenate a variable in a string without a ||您试图在没有||的情况下连接字符串中的变量
  • The right order is lon lat , not lat lon正确的顺序是lon lat ,而不是lat lon
  • You do not need a function for this.为此,您不需要 function。 A simple query with the ST_Distance function would suffice使用ST_Distance function 的简单查询就足够了

But in case you need it for other purposes:但如果您需要它用于其他目的:

CREATE OR REPLACE FUNCTION distances(lat1 float, lon1 float, lat2 float, lon2 float)
RETURNS float AS $$
BEGIN
  RETURN (
  SELECT 
    ST_Distance(
      ST_SetSRID(ST_MakePoint(lon1,lat1),4326),
      ST_SetSRID(ST_MakePoint(lon2,lat2),4326), false));
END;
$$ LANGUAGE plpgsql;

Otherwise this SQL query would do:否则这个 SQL 查询会做:

SELECT ST_Distance(
  ST_SetSRID(ST_MakePoint(51.23,8.83),4326),
  ST_SetSRID(ST_MakePoint(51.24,8.55),4326), false);

Cheers干杯

Further reading:进一步阅读:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM