PostGIS:找到最接近给定点的几何图形

时间:2012-12-27 02:38:27

标签: postgresql geolocation openlayers geospatial postgis

假设我的数据库中有许多几何图形。我想在PostgreSQL中创建一个函数,我可以传入lat / long并让它返回给定半径的距离(线性和公路)最接近的几何。

我是这个的新手,所以任何建议都表示赞赏。

我正在运行以下版本:

  • PostgreSQL:9.2
  • PostGIS:2.0

这是架构:

-- ----------------------------
--  Table structure for "cities-usa"
-- ----------------------------
DROP TABLE IF EXISTS "cities-usa";
CREATE TABLE "cities-usa" (
"gid" int4 NOT NULL DEFAULT nextval('"cities-usa_gid_seq"'::regclass),
"st_fips" varchar(4),
"sfips" varchar(2),
"county_fip" varchar(4),
"cfips" varchar(4),
"pl_fips" varchar(7),
"id" varchar(20),
"name" varchar(39),
"elevation" varchar(60),
"pop_1990" numeric,
"population" varchar(30),
"st" varchar(6),
"state" varchar(16),
"warngenlev" varchar(16),
"warngentyp" varchar(16),
"watch_warn" varchar(3),
"zwatch_war" float8,
"prog_disc" int4,
"zprog_disc" float8,
"comboflag" float8,
"land_water" varchar(16),
"recnum" float8,
"lon" float8,
"lat" float8,
"geom" "geometry"
)
WITH (OIDS=FALSE);
ALTER TABLE "cities-usa" OWNER TO "postgres";

-- ----------------------------
--  Primary key structure for table "cities-usa"
-- ----------------------------
ALTER TABLE "cities-usa" ADD CONSTRAINT "cities-usa_pkey" PRIMARY KEY ("gid") NOT DEFERRABLE INITIALLY IMMEDIATE;

1 个答案:

答案 0 :(得分:3)

逻辑可以包装到函数中,但我建议使用查询来测试逻辑。您将遇到的困难是线性距离(英里)与角度坐标(纬度和经度)相结合。此外,上面指定的几何类型没有SRID或几何类型。我猜它应该是geometry(Point,4326)

您可以尝试一些策略,例如使用geography类型,该类型会自动为米ST_DistanceST_DWithin等功能使用米。以下示例仅使用ST_Distance_Sphere,其中包含从英里到米的转换,以帮助您前进。或者,如果您需要演奏,可以尝试indexed nearest neighbour search<->功能。

您可以尝试以下方法:

CREATE OR REPLACE FUNCTION WhatAmINear(lat float8, lon float8,
                                       radius_mi float8, num int DEFAULT 10)
    RETURNS SETOF "cities-usa" AS
$body$
SELECT *
FROM "cities-usa"
WHERE ST_Distance_Sphere(geom, ST_MakePoint(lon, lat)) <= radius_mi * 1609.34
LIMIT num;
$body$
LANGUAGE sql VOLATILE;

然后:

SELECT WhatAmINear(44.9, -93.1, 100);