整理一下postgresql的扩展功能postgis和pgrouting的使用

postgis windows的下的安装使用postgresql的bin目录下的stackbuiler

Ubuntu14.04下的安装:

apt-get install postgresql-9.3-postgis-2.1(也可以用apt-cache search postgresql postgis查找最新的版本)

postgis:

1.建表语句:

create table NODES (ID SERIAL not null,geometry geography(POINTZ, 4326) null); 字段geometry表示的是三维空间的点,二维的点将POINTZ改为POINT即可
create table EDGES (ID SERIAL not null,geometry geography(LINESTRINGZ, 4326) null);  字段geometry表示的是三维空间的线,同理,二维的将LINESTRINGZ改为LINESTRING即可

2.插入语句:

insert into nodes(geometry) values(ST_GeographyFromText('SRID=4326; POINT(-110 30 40)'));
insert into edges(geometry) values(ST_GeographyFromText('SRID=4326; LINESTRING(-110 30 40,11 22 33)'));

3.修改字段类型:

alter table public.nodes alter column geometry set data type geography(PointZ,4326);

4.查询语句:

select ST_AsText(geometry) from nodes;
select ST_AsText(geometry) from edges;

有关pgrouting:

1.Windows下的安装:  

  在官网下载和本机PostgreSQL对应版本的PGRouting,我这里的版本的PostgreSQL 9.2,这个版本可以使用的PGRouting对应版本是2.0。

  下载PGRouing之后,可以看到里面有3个文件夹(bin、lib、share)和5个文件,以后可能会有变动,将这三个文件夹拷贝到PostgreSQL的安装目录下,和同名文件夹合并。

2.Ubuntu14.04下的安装:

sudo apt-get install postgresql-9.3-pgrouting(如果出现package not found的情况,则需要添加pgrouting的repository)
add pgrouting repository:

sudo
apt-add-repository -y ppa:ubuntugis/ppa sudo apt-add-repository -y ppa:georepublic/pgrouting sudo apt-get update sudo apt-get install postgresql-9.3-pgrouting

3.让数据库支持pgrouting:

  CREATE EXTENSION pgrouting;

4.pgrouting需要在edges中加入一些基本的字段

  columns 'source', 'target' must be of type int4, 'cost' must be of type float8(也可以使用其他的字段名,使用内置函数查询的时候注意点就好了)

5.查询两个node之间的最短路径:

  

select * from pgr_dijkstra('select id as id,source::integer,target::integer,length::double precision as cost from edges',30,60,false,false);

 该查询语句表示的是得到ID为30和60的node之间的最短路径,第四个参数指的是是否限制方向

注意!!!注意!!!

非常抱歉关于上面的字段geometry的数据类型的错误,需要将 geography 改为 geometry,同时需要将插入语句的 ST_GeographyFromText 改为 ST_GeomFromEWKT 或 GeomFromEWKT (geography 主要表示经纬度,x的范围是(-180,180),y的范围是(-90,90)),其他的不变

原文地址:https://www.cnblogs.com/lwmp/p/6871690.html