Chapter 2. Instalación de PostGIS

Table of Contents

En este capítulo se detallan los pasos necesarios para instalar PostGIS .

2.1. Versión corta

Para compilar asumiendo que tiene todas las dependencias en su ruta de búsqueda:

tar -xvzf postgis-3.5.0dev.tar.gz
cd postgis-3.5.0dev
./configure
make
make install

Una vez instalado PostGIS, es necesario habilitarlo (Section 3.3, “Creating spatial databases”) o actualizarlo (Section 3.4, “Upgrading spatial databases”) en cada base de datos individual en la que desee utilizarlo.

2.2. Compilación e instalación desde el código fuente

[Note]

Muchos Sistemas Operativos incluyen ya paquetes precompilados PostgreSQL/PostGIS. En la mayoría de casos no es necesario compilar salvo si quieres las ultimas versiones o haces mantenimiento de paquetes.

This section includes general compilation instructions, if you are compiling for Windows etc or another OS, you may find additional more detailed help at PostGIS User contributed compile guides and PostGIS Dev Wiki.

Pre-Built Packages for various OS are listed in PostGIS Pre-built Packages

Si eres usuario de Windows, puedes obtener versiones estables compiladas via Stackbuilder o el sitio de descargas de PostGIS para Windows También tenemos versiones experimentales para Windows que son publicadas normalmente una o dos veces por semana o cuando ocurre algo interesante. Puedes utilizar éstas para experimentar con las versiones de desarrollo de PostGIS

The PostGIS module is an extension to the PostgreSQL backend server. As such, PostGIS 3.5.0dev requires full PostgreSQL server headers access in order to compile. It can be built against PostgreSQL versions 12 - 17. Earlier versions of PostgreSQL are not supported.

Refer to the PostgreSQL installation guides if you haven't already installed PostgreSQL. https://www.postgresql.org .

[Note]

Para tener compatibilidad con las funcionalidades GEOS, cuando instales PostgreSQL necesitar hacer un enlace explícito con la librería estándar C++:

LDFLAGS=-lstdc++ ./configure [YOUR OPTIONS HERE]

Esta es una solución para falsas excepciones C++ con herramientas de desarrollo antiguas. Prueba este truco si experimentas problemas extraños (backend cerrado inesperadamente o cosas similares). Porc supuesto, será necesario volver a compilar PostgreSQL desde cero.

Los siguientes pasos describen la configuración y compilación del código fuente de PostGIS. Están escritas para usuarios Linux y no funcionarán con Windows o Mac.

2.2.1. Obteniendo el código fuente

Retrieve the PostGIS source archive from the downloads website https://postgis.net/stuff/postgis-3.5.0dev.tar.gz

wget https://postgis.net/stuff/postgis-3.5.0dev.tar.gz
tar -xvzf postgis-3.5.0dev.tar.gz
cd postgis-3.5.0dev

Esto creara un directorio llamado postgis-3.5.0dev en el directorio de trabajo actual.

De forma alternativa se puede obtener el código fuente del git repositorio https://git.osgeo.org/gitea/postgis/postgis/ .

git clone https://git.osgeo.org/gitea/postgis/postgis.git postgis
cd postgis
sh autogen.sh
    

Vaya al nuevo directorio postgis-3.5.0dev creado para continuar con la instalación.

./configure

2.2.2. Install Requirements

PostGIS tiene los siguientes requisitos para compilarlo y usarlo:

Requerido

  • PostgreSQL 12 - 17. A complete installation of PostgreSQL (including server headers) is required. PostgreSQL is available from https://www.postgresql.org .

    For a full PostgreSQL / PostGIS support matrix and PostGIS/GEOS support matrix refer to https://trac.osgeo.org/postgis/wiki/UsersWikiPostgreSQLPostGIS

  • compilador GNU C (gcc). Otros compiladores ANSI C pueden utilizarse para compilar PostGIS, pero encontraremos menos problemas al compilar con gcc.

  • GNU Make (gmake or make). Para muchos sistemas , GNU make es la versión por defecto de make. Para verificar la versión de make podemos ejecutar el siguiente comando make -v. Otras versiones de make pueden no procesar el fichero PostGIS Makefile de forma correcta.

  • Proj reprojection library. Proj 6.1 or above is required. The Proj library is used to provide coordinate reprojection support within PostGIS. Proj is available for download from https://proj.org/ .

  • GEOS geometry library, version 3.8.0 or greater, but GEOS 3.12+ is required to take full advantage of all the new functions and features. GEOS is available for download from https://libgeos.org .

  • LibXML2, version 2.5.x or higher. LibXML2 is currently used in some imports functions (ST_GeomFromGML and ST_GeomFromKML). LibXML2 is available for download from https://gitlab.gnome.org/GNOME/libxml2/-/releases.

  • JSON-C, version 0.9 or higher. JSON-C is currently used to import GeoJSON via the function ST_GeomFromGeoJson. JSON-C is available for download from https://github.com/json-c/json-c/releases/.

  • GDAL, version 2+ is required 3+ is preferred. This is required for raster support. https://gdal.org/download.html.

  • If compiling with PostgreSQL+JIT, LLVM version >=6 is required https://trac.osgeo.org/postgis/ticket/4125.

Opcional

  • GDAL (pseudo optional) only if you don't want raster you can leave it out. Also make sure to enable the drivers you want to use as described in Section 3.2, “Configuring raster support”.

  • GTK (GTK+2.0, 2.8+ requerida) para compilar el cargador de shapefiles shp2pgsql-gui. http://www.gtk.org/ .

  • SFCGAL, version 1.3.1 (or higher), 1.4.1 or higher is recommended and required to be able to use all functionality. SFCGAL can be used to provide additional 2D and 3D advanced analysis functions to PostGIS cf Chapter 8, SFCGAL Functions Reference. And also allow to use SFCGAL rather than GEOS for some 2D functions provided by both backends (like ST_Intersection or ST_Area, for instance). A PostgreSQL configuration variable postgis.backend allow end user to control which backend he want to use if SFCGAL is installed (GEOS by default). Nota: SFCGAL 1.2 require at least CGAL 4.3 and Boost 1.54 (cf: https://sfcgal.org) https://gitlab.com/sfcgal/SFCGAL/.

  • In order to build the Section 12.1, “Normalizador de Direcciones” you will also need PCRE http://www.pcre.org (which generally is already installed on nix systems). Section 12.1, “Normalizador de Direcciones” will automatically be built if it detects a PCRE library, or you pass in a valid --with-pcre-dir=/path/to/pcre during configure.

  • To enable ST_AsMVT protobuf-c library 1.1.0 or higher (for usage) and the protoc-c compiler (for building) are required. Also, pkg-config is required to verify the correct minimum version of protobuf-c. See protobuf-c. By default, Postgis will use Wagyu to validate MVT polygons faster which requires a c++11 compiler. It will use CXXFLAGS and the same compiler as the PostgreSQL installation. To disable this and use GEOS instead use the --without-wagyu during the configure step.

  • CUnit (CUnit). Se necesita para hacer test de regresión. http://cunit.sourceforge.net/

  • DocBook (xsltproc) es necesario para compilar la documentación. Docbook esta disponible en http://www.docbook.org/ .

  • DBLatex (dblatex) necesario para construir la documentación en formato PDF. DBLatex esta disponible en http://dblatex.sourceforge.net/ .

  • ImageMagick (convert) es necesario para generar las imágenes empleadas en la documentación. ImageMagick esta disponible en http://www.imagemagick.org/ .

2.2.3. Configuración

Como en la gran mayoría de instalaciones Linux, el primer paso es generar el Makefile que se utilizara para compilar el código fuente. Esto se hace ejecutando el script de shell.

./configure

Sin parámetros adicionales, este comando intentara localizar los componentes y librerías necesarios para construir el código fuente PostGIS de forma automática en tu sistema. Aunque este es el uso mas común de ./configure, el script acepta varios parámetros para aquellos que han instalado las librerías y programas en lugares no standard.

La siguiente lista muestra los parámetros utilizados mas comunes. Para obtener una lista completa, puedes utilizar los parámetros --help o --help=short.

--with-library-minor-version

Starting with PostGIS 3.0, the library files generated by default will no longer have the minor version as part of the file name. This means all PostGIS 3 libs will end in postgis-3. This was done to make pg_upgrade easier, with downside that you can only install one version PostGIS 3 series in your server. To get the old behavior of file including the minor version: e.g. postgis-3.0 add this switch to your configure statement.

--prefix=PREFIX

Esta es la localización donde se instalaran las librerías PostGIS y los scripts SQL. Por defecto, esta localización es la misma que la detectada para la instalación PostgreSQL.

[Caution]

Este parámetro está roto actualmente, ya que el paquete sólo se instalará en el directorio de instalación de PostgreSQL. Para seguir avence de este bug visita http://trac.osgeo.org/postgis/ticket/635

--with-pgconfig=FILE

PostgreSQL tiene una herramienta llamada pg_config para activar extensiones como PostGIS o para localizar el directorio de instalación de PostgreSQL. Utiliza este parámetro (--with-pgconfig=/path/to/pg_config) para especificar una instalación personalizada de PostgreSQL de forma manual que PostGIS utilizara para compilar.

--with-gdalconfig=FILE

GDAL, una biblioteca necesaria, proporciona la funcionalidad necesaria para el soporte de raster gdal-config para activar la instalación de software para localizar el directorio de instalación de GDAL. Utilice este parámetro ( - with-gdalconfig = / ruta /a/ gdal config-) para especificar manualmente una instalación de GDAL personalizada que PostGIS utilizara para compilar.

--with-geosconfig=FILE

GEOS, libreria de geometrías requerida, tiene una utilidad llamada geos-config para activar la localización del directorio de instalación del software GEOS. Utiliza este parametro (--with-geosconfig=/path/to/geos-config) para especificar de forma manual una instalación personalizada de GEOS que PostGIS puede utilizar para compilar.

--with-xml2config=FILE

LibXML is the library required for doing GeomFromKML/GML processes. It normally is found if you have libxml installed, but if not or you want a specific version used, you'll need to point PostGIS at a specific xml2-config confi file to enable software installations to locate the LibXML installation directory. Use this parameter (>--with-xml2config=/path/to/xml2-config) to manually specify a particular LibXML installation that PostGIS will build against.

--with-projdir=DIR

Proj4 es una libreria de reproyecciones necesaria de PostGIS. Utiliza el siguiente parametro (--with-projdir=/path/to/projdir) para definir manualmente una instalación personalizada de Proj4 para compilar PostGIS.

--with-libiconv=DIR

Directorio donde iconv esta instalado.

--with-jsondir=DIR

JSON-Ces una libreria con licencia MIT-licensed JSON necesaria para dar soporte a PostGIS ST_GeomFromJSON. Utiliza este parametro (--with-jsondir=/path/to/jsondir) para especificar de forma manual el directorio de instalación personalizado de instalación de JSON-C que PostGIS utilizara para compilar.

--with-pcredir=DIR

PCRE is an BSD-licensed Perl Compatible Regular Expression library required by address_standardizer extension. Use this parameter (--with-pcredir=/path/to/pcredir) to manually specify a particular PCRE installation directory that PostGIS will build against.

--with-gui

Compilar la GUI de importar datos (necesita GTK+2.0). Esto creara una interfaz gráfica shp2pgsql-gui para el comando shp2pgsql.

--without-raster

Compile without raster support.

--without-topology

Disable topology support. There is no corresponding library as all logic needed for topology is in postgis-3.5.0dev library.

--with-gettext=no

PostGIS intentara detectar soporte gettext y compilar con el por defecto, de todas formas si existen incompatibilidades que causan errores de carga, se puede desactivar por completo con este comando. Para ver un ejemplo de resolución de problemas configurando en gettext puedes ver el siguiente enlace http://trac.osgeo.org/postgis/ticket/748. NOTA: No te pierdes mucho si desactivas esta opción. Se utiliza principalmente para soporte de ayuda/etiquetas internacionales en la GUI de carga, que actualmente no esta documentada y sigue siendo experimental.

--with-sfcgal=PATH

By default PostGIS will not install with sfcgal support without this switch. PATH is an optional argument that allows to specify an alternate PATH to sfcgal-config.

--without-phony-revision

Disable updating postgis_revision.h to match current HEAD of the git repository.

[Note]

If you obtained PostGIS from the code repository , the first step is really to run the script

./autogen.sh

Este Script generara el script configure que a su vez se utiliza para personalizar la instalación de PostGIS.

Si, por el contrario, as obtenido PostGIS como tarball, ejecutar ./autogen.sh no es necesario ya que ya se ha generado configure.

2.2.4. Compilando

Una vez generado el Makefile, compilar PostGIS es tan simple como ejecutar

make

La ultima linea de salida del terminal debe ser "PostGIS copilado con éxito. Listo para instalar."

As of PostGIS v1.4.0, all the functions have comments generated from the documentation. If you wish to install these comments into your spatial databases later, run the command which requires docbook. The postgis_comments.sql and other package comments files raster_comments.sql, topology_comments.sql are also packaged in the tar.gz distribution in the doc folder so no need to make comments if installing from the tar ball. Comments are also included as part of the CREATE EXTENSION install.

make comments

Introducido en la version PostGIS 2.0. Esto genera hojas de referencia html para una referencia rápida o para los folletos. Esto requiere xsltproc para compilar y generará 4 ficheros en la carpeta doc topology_cheatsheet.html, tiger_geocoder_cheatsheet.html, raster_cheatsheet.html, postgis_cheatsheet.html

Puedes descargar algunos ya compilados en formato html o pdf en Guias de Estudio PostGIS / PostgreSQL

make cheatsheets

2.2.5. Compilando e Instalando Extensiones de PostGIS

Las extensiones de PosGIS son compiladas e instaladas de forma automatica si estas utilizando la version 9.1+ de PostgreSQL

Si estas compilando desde el repositorio de código fuente, necesitas compilar primero la función descriptions. Si tienes instaldo docbook ya esta compilado. También puedes compilarla manualmente con la sentencia:

make comments

Compilar los comentarios no es necesario si estas compilando desde un tar ya que están en el paquete pre-compilados con el tar.

Si estas compilando para PostgreSQL 9.1, la extension debería compilarse de forma automática como parte del proceso del comando make install. Si lo necesitas, puedes compilar la extensión desde las carpetas de la extensión o copiar los ficheros en un servidor diferente.

cd extensions
cd postgis
make clean
make
export PGUSER=postgres #overwrite psql variables
make check #to test before install
make install
# to test extensions
make check RUNTESTFLAGS=--extension
[Note]

make check uses psql to run tests and as such can use psql environment variables. Common ones useful to override are PGUSER,PGPORT, and PGHOST. Refer to psql environment variables

Los ficheros de la extension serán siempre los mismos para la misma versión de PostgreSQL independientemente del Sistema Operativo, así que se pueden copiar los ficheros de la extensión de un Sistema Operativo a otro si ya tienes los binarios de PostGIS ya instalados en tus servidores.

Si quieres instalar la extensión de forma manual en un servidor separado de tu servidor de desarrollo, necesitas copiar los siguientes archivos de la carpeta de la extensión en la carpeta PostgreSQL / share / extension de la instalación de PostgreSQL y los binarios normales para PostGIS si no los tienes instalados en el servidor.

  • Estos son los ficheros de control que contienen información como la versión de la extensión a instalar si no lo has especificado. postgis.control, postgis_topology.control.

  • Todos los ficheros en la carpeta /sql de la extension. Estos ficheros deben ser copiados en la raiz de PostgreSQL en la carpeta share/extension extensions/postgis/sql/*.sql, extensions/postgis_topology/sql/*.sql

Once you do that, you should see postgis, postgis_topology as available extensions in PgAdmin -> extensions.

Si estas utilizando psql, puedes verificar que las extensiones están instaladas ejecutando la siguiente sentencia:

SELECT name, default_version,installed_version
FROM pg_available_extensions WHERE name LIKE 'postgis%' or name LIKE 'address%';

             name             | default_version | installed_version
------------------------------+-----------------+-------------------
 address_standardizer         | 3.5.0dev         | 3.5.0dev
 address_standardizer_data_us | 3.5.0dev         | 3.5.0dev
 postgis                      | 3.5.0dev         | 3.5.0dev
 postgis_raster               | 3.5.0dev         | 3.5.0dev
 postgis_sfcgal               | 3.5.0dev         |
 postgis_tiger_geocoder       | 3.5.0dev         | 3.5.0dev
 postgis_topology             | 3.5.0dev         |
(6 rows)

Si tienes instalada una extension en la base de datos que estas consultando, deberías verla mencionada la columna installed_version. Si la consulta no devuelve ningún registro, significa que no tienes la extension PostGIS instalada en el servidor. PgAdmin III 1.14+ muestra esta información en la sección extensiones en el navegador de bases de datos y permite actualizar o instalar haciendo click derecho.

Si la extension esta disponible, puedes instalar la extension postgis en la base de datos de tu elección utilizando la interfaz de extensiones de pgAdmin o ejecutando la siguiente sentencia:

CREATE EXTENSION postgis;
CREATE EXTENSION postgis_raster;
CREATE EXTENSION postgis_sfcgal;
CREATE EXTENSION fuzzystrmatch; --needed for postgis_tiger_geocoder
--optional used by postgis_tiger_geocoder, or can be used standalone
CREATE EXTENSION address_standardizer;
CREATE EXTENSION address_standardizer_data_us;
CREATE EXTENSION postgis_tiger_geocoder;
CREATE EXTENSION postgis_topology;

In psql you can use to see what versions you have installed and also what schema they are installed.

\connect mygisdb
\x
\dx postgis*
List of installed extensions
-[ RECORD 1 ]-------------------------------------------------
Name        | postgis
Version     | 3.5.0dev
Schema      | public
Description | PostGIS geometry, geography, and raster spat..
-[ RECORD 2 ]-------------------------------------------------
Name        | postgis_raster
Version     | 3.0.0dev
Schema      | public
Description | PostGIS raster types and functions
-[ RECORD 3 ]-------------------------------------------------
Name        | postgis_tiger_geocoder
Version     | 3.5.0dev
Schema      | tiger
Description | PostGIS tiger geocoder and reverse geocoder
-[ RECORD 4 ]-------------------------------------------------
Name        | postgis_topology
Version     | 3.5.0dev
Schema      | topology
Description | PostGIS topology spatial types and functions
[Warning]

No se pueden hacer copias de seguridad explicitas de las tablas de las extensiones spatial_ref_sys, layer, topology. Solo se pueden hacer copias de seguridad explicitas cuando cuando se hacen copias de seguridad de sus respectivas extensiones postgis or postgis_topology, lo que al parecer ocurre cuando haces una copia de seguridad de la base de datos completa. Con PostGIS 2.0.1, solo los srid no incluidos en PostGIS son guardados cuando se hace una copia de seguridad de la base de datos, así que no esperes que al cambiar alguno de los srid que incluye PostGIS este en tu copia de seguridad. Envia un ticket si encuentras algún problema. La estructura de las tabals de extensiones no se guardan en copias de seguridad si son creadas con CREATE EXTENSION y son la misma estructura para una version dada de una extension. Estos comportamientos están incorporados en el modelo de extensiones PostgreSQL actual, así que nada podemos hacer al respecto.

If you installed 3.5.0dev, without using our wonderful extension system, you can change it to be extension based by running the below commands to package the functions in their respective extension. Installing using `unpackaged` was removed in PostgreSQL 13, so you are advised to switch to an extension build before upgrading to PostgreSQL 13.

CREATE EXTENSION postgis FROM unpackaged;
CREATE EXTENSION postgis_raster FROM unpackaged;
CREATE EXTENSION postgis_topology FROM unpackaged;
CREATE EXTENSION postgis_tiger_geocoder FROM unpackaged;

2.2.6. Tests

Si quieres hacer un test en la compilación de PostGIS, ejecuta

make check

El comando anterior ejecutará varias comprobaciones y tests de regresión utilizando la librería generada para la version de base de datos PostgreSQL actual.

[Note]

Si ha configurado PostGIS utilizando ubicaciones no estándar de PostgreSQL, GEOS o Proj, puede que necesite añadir sus ubicaciones de biblioteca a la variable de entorno LD_LIBRARY_PATH.

[Caution]

Actualmente, el comando make check une las variables de entorno PATH y PGPORT cundo ejecuta las comprobaciones - no utiliza la version de PostgreSQL especificada utilizando el parametro de configuración --with-pgconfig. Así que hay que estar seguros de modificar la variable de entorno PATH para que apunte a la instalación de PostgreSQL detectada durante la configuración o estar preparado para tener algún que otro dolor de cabeza.

If successful, make check will produce the output of almost 500 tests. The results will look similar to the following (numerous lines omitted below):

CUnit - A unit testing framework for C - Version 2.1-3
     http://cunit.sourceforge.net/

        .
        .
        .

Run Summary:    Type  Total    Ran Passed Failed Inactive
              suites     44     44    n/a      0        0
               tests    300    300    300      0        0
             asserts   4215   4215   4215      0      n/a
Elapsed time =    0.229 seconds

        .
        .
        .

Running tests

        .
        .
        .

Run tests: 134
Failed: 0


-- if you build with SFCGAL

        .
        .
        .

Running tests

        .
        .
        .

Run tests: 13
Failed: 0

-- if you built with raster support

        .
        .
        .

Run Summary:    Type  Total    Ran Passed Failed Inactive
              suites     12     12    n/a      0        0
               tests     65     65     65      0        0
             asserts  45896  45896  45896      0      n/a


        .
        .
        .

Running tests

        .
        .
        .

Run tests: 101
Failed: 0

-- topology regress

.
.
.

Running tests

        .
        .
        .

Run tests: 51
Failed: 0

-- if you built --with-gui, you should see this too

     CUnit - A unit testing framework for C - Version 2.1-2
     http://cunit.sourceforge.net/

        .
        .
        .

Run Summary:    Type  Total    Ran Passed Failed Inactive
              suites      2      2    n/a      0        0
               tests      4      4      4      0        0
             asserts      4      4      4      0      n/a

The postgis_tiger_geocoder and address_standardizer extensions, currently only support the standard PostgreSQL installcheck. To test these use the below. Note: the make install is not necessary if you already did make install at root of PostGIS code folder.

For address_standardizer:

cd extensions/address_standardizer
make install
make installcheck
          

Output should look like:

============== dropping database "contrib_regression" ==============
DROP DATABASE
============== creating database "contrib_regression" ==============
CREATE DATABASE
ALTER DATABASE
============== running regression test queries        ==============
test test-init-extensions     ... ok
test test-parseaddress        ... ok
test test-standardize_address_1 ... ok
test test-standardize_address_2 ... ok

=====================
 All 4 tests passed.
=====================

For tiger geocoder, make sure you have postgis and fuzzystrmatch extensions available in your PostgreSQL instance. The address_standardizer tests will also kick in if you built postgis with address_standardizer support:

cd extensions/postgis_tiger_geocoder
make install
make installcheck
          

output should look like:

============== dropping database "contrib_regression" ==============
DROP DATABASE
============== creating database "contrib_regression" ==============
CREATE DATABASE
ALTER DATABASE
============== installing fuzzystrmatch               ==============
CREATE EXTENSION
============== installing postgis                     ==============
CREATE EXTENSION
============== installing postgis_tiger_geocoder      ==============
CREATE EXTENSION
============== installing address_standardizer        ==============
CREATE EXTENSION
============== running regression test queries        ==============
test test-normalize_address   ... ok
test test-pagc_normalize_address ... ok

=====================
All 2 tests passed.
=====================

2.2.7. Instalación

Para instalar PostGIS entre

make install

Esto copiará los ficheros de instalación de PostGIS en el subdirectorio especificado por el parámetro de configuración --prefix del comando . En particular:

  • Los archivos binarios de carga y dumper estarán instalados en [prefix]/bin.

  • Los archivos SQL, tal como postgis.sql, están instalados en [prefix]/share/contrib.

  • Las librerías de PostGIS estarán instaladas en [prefix]/lib.

Si has ejecutado el comando make comments previamente para generar los ficheros postgis_comments.sql, raster_comments.sql, instala los ficheros sql ejecutando:

make comments-install

[Note]

postgis_comments.sql, raster_comments.sql, topology_comments.sql han sido separados de la compilación y de la instalación típicos ya que tienen una dependencia extra de la librería xsltproc.

2.3. Installing and Using the address standardizer

The address_standardizer extension used to be a separate package that required separate download. From PostGIS 2.2 on, it is now bundled in. For more information about the address_standardize, what it does, and how to configure it for your needs, refer to Section 12.1, “Normalizador de Direcciones”.

This standardizer can be used in conjunction with the PostGIS packaged tiger geocoder extension as a replacement for the Normalize_Address discussed. To use as replacement refer to Section 2.4.2, “Using Address Standardizer Extension with Tiger geocoder”. You can also use it as a building block for your own geocoder or use it to standardize your addresses for easier compare of addresses.

The address standardizer relies on PCRE which is usually already installed on many Nix systems, but you can download the latest at: http://www.pcre.org. If during Section 2.2.3, “Configuración”, PCRE is found, then the address standardizer extension will automatically be built. If you have a custom pcre install you want to use instead, pass to configure --with-pcredir=/path/to/pcre where /path/to/pcre is the root folder for your pcre include and lib directories.

For Windows users, the PostGIS 2.1+ bundle is packaged with the address_standardizer already so no need to compile and can move straight to CREATE EXTENSION step.

Once you have installed, you can connect to your database and run the SQL:

CREATE EXTENSION address_standardizer;

The following test requires no rules, gaz, or lex tables

SELECT num, street, city, state, zip
 FROM parse_address('1 Devonshire Place PH301, Boston, MA 02109');

Output should be

num |         street         |  city  | state |  zip
-----+------------------------+--------+-------+-------
 1   | Devonshire Place PH301 | Boston | MA    | 02109

2.4. Installing, Upgrading Tiger Geocoder, and loading data

Extras like Tiger geocoder may not be packaged in your PostGIS distribution. If you are missing the tiger geocoder extension or want a newer version than what your install comes with, then use the share/extension/postgis_tiger_geocoder.* files from the packages in Windows Unreleased Versions section for your version of PostgreSQL. Although these packages are for windows, the postgis_tiger_geocoder extension files will work on any OS since the extension is an SQL/plpgsql only extension.

2.4.1. Tiger Geocoder Enabling your PostGIS database

  1. These directions assume your PostgreSQL installation already has the postgis_tiger_geocoder extension installed.

  2. Connect to your database via psql or pgAdmin or some other tool and run the following SQL commands. Note that if you are installing in a database that already has postgis, you don't need to do the first step. If you have fuzzystrmatch extension already installed, you don't need to do the second step either.

    CREATE EXTENSION postgis;
    CREATE EXTENSION fuzzystrmatch;
    CREATE EXTENSION postgis_tiger_geocoder;
    --this one is optional if you want to use the rules based standardizer (pagc_normalize_address)
    CREATE EXTENSION address_standardizer;

    If you already have postgis_tiger_geocoder extension installed, and just want to update to the latest run:

    ALTER EXTENSION postgis UPDATE;
    ALTER EXTENSION postgis_tiger_geocoder UPDATE;

    If you made custom entries or changes to tiger.loader_platform and tiger.loader_variables you may need to update these.

  3. To confirm your install is working correctly, run this sql in your database:

    SELECT na.address, na.streetname,na.streettypeabbrev, na.zip
            FROM normalize_address('1 Devonshire Place, Boston, MA 02109') AS na;

    Which should output

    address | streetname | streettypeabbrev |  zip
    ---------+------------+------------------+-------
               1 | Devonshire | Pl               | 02109
  4. Create a new record in tiger.loader_platform table with the paths of your executables and server.

    So for example to create a profile called debbie that follows sh convention. You would do:

    INSERT INTO tiger.loader_platform(os, declare_sect, pgbin, wget, unzip_command, psql, path_sep,
                       loader, environ_set_command, county_process_command)
    SELECT 'debbie', declare_sect, pgbin, wget, unzip_command, psql, path_sep,
               loader, environ_set_command, county_process_command
      FROM tiger.loader_platform
      WHERE os = 'sh';

    And then edit the paths in the declare_sect column to those that fit Debbie's pg, unzip,shp2pgsql, psql, etc path locations.

    If you don't edit this loader_platform table, it will just contain common case locations of items and you'll have to edit the generated script after the script is generated.

  5. As of PostGIS 2.4.1 the Zip code-5 digit tabulation area zcta5 load step was revised to load current zcta5 data and is part of the Loader_Generate_Nation_Script when enabled. It is turned off by default because it takes quite a bit of time to load (20 to 60 minutes), takes up quite a bit of disk space, and is not used that often.

    To enable it, do the following:

    UPDATE tiger.loader_lookuptables SET load = true WHERE table_name = 'zcta520';

    If present the Geocode function can use it if a boundary filter is added to limit to just zips in that boundary. The Reverse_Geocode function uses it if the returned address is missing a zip, which often happens with highway reverse geocoding.

  6. Create a folder called gisdata on root of server or your local pc if you have a fast network connection to the server. This folder is where the tiger files will be downloaded to and processed. If you are not happy with having the folder on the root of the server, or simply want to change to a different folder for staging, then edit the field staging_fold in the tiger.loader_variables table.

  7. Create a folder called temp in the gisdata folder or wherever you designated the staging_fold to be. This will be the folder where the loader extracts the downloaded tiger data.

  8. Then run the Loader_Generate_Nation_Script SQL function make sure to use the name of your custom profile and copy the script to a .sh or .bat file. So for example to build the nation load:

    psql -c "SELECT Loader_Generate_Nation_Script('debbie')" -d geocoder -tA > /gisdata/nation_script_load.sh
  9. Run the generated nation load commandline scripts.

    cd /gisdata
    sh nation_script_load.sh
  10. After you are done running the nation script, you should have three tables in your tiger_data schema and they should be filled with data. Confirm you do by doing the following queries from psql or pgAdmin

    SELECT count(*) FROM tiger_data.county_all;
    count
    -------
      3235
    (1 row)
    SELECT count(*) FROM tiger_data.state_all;
    count
    -------
        56
    (1 row)
    

    This will only have data if you marked zcta5 to be loaded

    SELECT count(*) FROM tiger_data.zcta5_all;
    count
    -------
      33931
    (1 row)
    
  11. By default the tables corresponding to bg, tract, tabblock20 are not loaded. These tables are not used by the geocoder but are used by folks for population statistics. If you wish to load them as part of your state loads, run the following statement to enable them.

    UPDATE tiger.loader_lookuptables SET load = true WHERE load = false AND lookup_name IN('tract', 'bg', 'tabblock20');

    Alternatively you can load just these tables after loading state data using the Loader_Generate_Census_Script

  12. For each state you want to load data for, generate a state script Loader_Generate_Script.

    [Warning]

    DO NOT Generate the state script until you have already loaded the nation data, because the state script utilizes county list loaded by nation script.

  13. psql -c "SELECT Loader_Generate_Script(ARRAY['MA'], 'debbie')" -d geocoder -tA > /gisdata/ma_load.sh
  14. Run the generated commandline scripts.

    cd /gisdata
    sh ma_load.sh
  15. After you are done loading all data or at a stopping point, it's a good idea to analyze all the tiger tables to update the stats (include inherited stats)

    SELECT install_missing_indexes();
    vacuum (analyze, verbose) tiger.addr;
    vacuum (analyze, verbose) tiger.edges;
    vacuum (analyze, verbose) tiger.faces;
    vacuum (analyze, verbose) tiger.featnames;
    vacuum (analyze, verbose) tiger.place;
    vacuum (analyze, verbose) tiger.cousub;
    vacuum (analyze, verbose) tiger.county;
    vacuum (analyze, verbose) tiger.state;
    vacuum (analyze, verbose) tiger.zcta5;
    vacuum (analyze, verbose) tiger.zip_lookup_base;
    vacuum (analyze, verbose) tiger.zip_state;
    vacuum (analyze, verbose) tiger.zip_state_loc;

2.4.2. Using Address Standardizer Extension with Tiger geocoder

One of the many complaints of folks is the address normalizer function Normalize_Address function that normalizes an address for prepping before geocoding. The normalizer is far from perfect and trying to patch its imperfectness takes a vast amount of resources. As such we have integrated with another project that has a much better address standardizer engine. To use this new address_standardizer, you compile the extension as described in Section 2.3, “Installing and Using the address standardizer” and install as an extension in your database.

Once you install this extension in the same database as you have installed postgis_tiger_geocoder, then the Pagc_Normalize_Address can be used instead of Normalize_Address. This extension is tiger agnostic, so can be used with other data sources such as international addresses. The tiger geocoder extension does come packaged with its own custom versions of rules table ( tiger.pagc_rules) , gaz table (tiger.pagc_gaz), and lex table (tiger.pagc_lex). These you can add and update to improve your standardizing experience for your own needs.

2.4.3. Required tools for tiger data loading

El proceso de carga, descarga datos desde el sitio web del censo de las respectivas naciones de los estados pedidos, extrae los ficheros, y carga cada estado en un conjunto separado por estados en su propia tabla. Cada tabla de estado hereda el esquema de tablas definido en tiger así que basta con hacer una consulta a estas tablas para acceder a todos los datos de la tabla de estados en cualquier momento utilizando Drop_State_Tables_Generate_Script si necesita volver a cargar un estado o si ya no lo necesitas mas.

Para poder cargar los datos necesitarás las siguientes herramientas:

  • Una herramienta para descomprimir ficheros zip de la pagina web del censo.

    Para sistemas Unix: el ejecutable unzip que normalmente esta instalado en la mayoría de sistemas Unix.

    Para windows, 7-zip es una herramienta libre de compresión/descompresión que puedes descargar en http://www.7-zip.org/

  • El comando shp2pgsql que se instala por defecto cuando instalas PostGIS.

  • wget que es una herramienta de captura web, normalmente instalado en los sistemas Unix/Linux.

    Si estas en windows, puedes obtener ejecutables precompilados en http://gnuwin32.sourceforge.net/packages/wget.htm

If you are upgrading from tiger_2010, you'll need to first generate and run Drop_Nation_Tables_Generate_Script. Before you load any state data, you need to load the nation wide data which you do with Loader_Generate_Nation_Script. Which will generate a loader script for you. Loader_Generate_Nation_Script is a one-time step that should be done for upgrading (from a prior year tiger census data) and for new installs.

To load state data refer to Loader_Generate_Script to generate a data load script for your platform for the states you desire. Note that you can install these piecemeal. You don't have to load all the states you want all at once. You can load them as you need them.

Una vez que los estados que quieres han sido cargados, asegurare de ejecutar:

SELECT install_missing_indexes();

como se explica en Install_Missing_Indexes.

Para probar que las cosas han funcionado como deberían, intenta ejecutar una geocodificacion en una dirección del estado descargado utilizando Geocode

2.4.4. Upgrading your Tiger Geocoder Install and Data

First upgrade your postgis_tiger_geocoder extension as follows:

ALTER EXTENSION postgis_tiger_geocoder UPDATE;

Después, elimina todas las tabals de naciones y carga las nuevas. Genera un script drop con esta sentencia SQL como se detalla en Drop_Nation_Tables_Generate_Script

SELECT drop_nation_tables_generate_script();

Ejecuta la sentencia SQL drop

Genera un script de carga de naciones con esta sentencia SELECT como se detalla en Loader_Generate_Nation_Script

Para windows

SELECT loader_generate_nation_script('windows'); 

Para unix/linux

SELECT loader_generate_nation_script('sh');

Refer to Section 2.4.1, “Tiger Geocoder Enabling your PostGIS database” for instructions on how to run the generate script. This only needs to be done once.

[Note]

You can have a mix of different year state tables and can upgrade each state separately. Before you upgrade a state you first need to drop the prior year state tables for that state using Drop_State_Tables_Generate_Script.

2.5. Common Problems during installation

Hay varias cosas a comprobar cuando la instalación o actualización no han fusionado como se esperaba.

  1. Comprueba que tienes instalado PostgreSQL 12 o posterior, y que estas compilando para esta version de PostgreSQL que estas utilizando. Se pueden producir confusiones cuando tu distribución (Linux)ya tiene instalada PostgreSQL, o has instalado antes PostgreSQL y lo has olvidado. PostGIS solo funcionará con PostgreSQL 12 o superior, y errores inesperados o extraños pueden ocurrir si utilizas una version mas antigua. Para comprobar la version de PostgreSQL que esta instalada y ejecutándose, conectare a la base de datos utilizando psql y ejecuta la siguiente consulta:

    SELECT version();

    Si estas ejecutando una version basada en una distribución RPM, puedes comprobar si existen paquetes pre-instalados utilizando el comando rpm como sigue: rpm -qa | grep postgresql

  2. Si tienes errores en la actualización, asegúrate de que estas restaurando tu base de datos en una que tenga instalada PostGIS.

    SELECT postgis_full_version();

Comprueba que tu configuración detecta la ubicación y la version correctas de PostgreSQL, la librería Proj4 y la librería GEOS.

  1. La salida de configure se utiliza para generar el fichero postgis_config.h. Comprueba que la variables POSTGIS_PGSQL_VERSION, POSTGIS_PROJ_VERSION y POSTGIS_GEOS_VERSION, han sido bien configuradas.