Chapter 12. Extras de PostGIS

Table of Contents

Este capítulo documenta las características encontradas en la carpeta Extras de fuente de tarballs y fuente de repositorio de PostGIS. Estos no siempre son empaquetados con las versiones binarias de PostGIS, pero son generalmente plpgsql básicos o scripts de shell estándar que pueden ser ejectuados tal cual.

12.1. Normalizador de Direcciones

Esta es una bifurcación del estandarizador PAGC (el código original para esta parte era el estandarizador de direcciones PAGC PostgreSQL).

El normalizador de direcciones es un analizador de direcciones de una sola línea que toma una dirección de entrada y la normaliza basándose en un conjunto de reglas almacenadas en una tabla y en las tablas de lex y gaz

El código está construido en una única librería de extensiones postgresql llamada address_standardizer que puede ser instalada con CREATE EXTENSION address_standardizer;. A demás de la extensión address_standardizer, una extensión de datos de ejemplo llamada address_standardizer_data_us es construida, la cual contiene tablas de gaz, lex, y rules para datos de Estados Unidos. Estas extensiones se pueden instalar mediante CREATE EXTENSION address_standardizer_data_us;

El código para esta extensión se puede encontrar en PostGIS extensions/address_standardizer y es actualmente autocontenido.

Para instrucciones de instalación, consulte: Section 2.3, “Installing and Using the address standardizer”.

12.1.1. Cómo funciona el analizador

El analizador trabaja de derecha a izquierda localizando primero los macro elementos para el codigo postal, estado/provincia, ciudad y a continuación los micro elementos para determinar si se esta tratando con un número de casa y calle o una interterseccion de calle o un hito. Actualmente no busca por un código o nombre de país, pero podría ser introducido en el futuro.

Código de país

Se supone que es de EE. UU. o CA según: código postal de estado/provincia como EE. UU. o Canadá, como EE. UU. o Canadá más EE. UU. .

Código postal

Éstos se reconocen utilizando expresiones regulares compatibles con Perl. Estos regexs están actualmente en el parseaddress-api.c y es relativamente simple hacer cambios si es necesario.

Estado/provincia

Éstos son reconocidos utilizando expresiones regulares compatibles con Perl. Estos regexs están actualmente en el parseaddress-api.c pero podrían ser movidos e incluidos en el futuro para facilitar el mantenimiento.

12.1.2. Tipos de Address Standardizer

Abstract

Esta sección lista los tipos de datos PostgreSQL instalados por la extensión Address Standardizer. Tenga en cuenta que describimos el comportamiento de fusión de estos que es muy importante, especialmente al diseñar sus propias funciones.

  • stdaddr — Un tipo compuesto que consiste en los elementos de una dirección. Este es el tipo de retorno para la función standardize_address .

12.1.3. Tipos de Address Standardizer

Abstract

This section lists the PostgreSQL table formats used by the address_standardizer for normalizing addresses. Note that these tables do not need to be named the same as what is referenced here. You can have different lex, gaz, rules tables for each country for example or for your custom geocoder. The names of these tables get passed into the address standardizer functions.

The packaged extension address_standardizer_data_us contains data for standardizing US addresses.

  • rules table — The rules table contains a set of rules that maps address input sequence tokens to standardized output sequence. A rule is defined as a set of input tokens followed by -1 (terminator) followed by set of output tokens followed by -1 followed by number denoting kind of rule followed by ranking of rule.
  • lex table — A lex table is used to classify alphanumeric input and associate that input with (a) input tokens ( See the section called “Tokens de entrada”) and (b) standardized representations.
  • gaz table — A gaz table is used to standardize place names and associate that input with (a) input tokens ( See the section called “Tokens de entrada”) and (b) standardized representations.

12.1.4. Funciones de Address Standardizer

12.2. Geocodificador Tiger

Abstract

A plpgsql based geocoder written to work with the TIGER (Topologically Integrated Geographic Encoding and Referencing system ) / Line and Master Address database export released by the US Census Bureau.

There are four components to the geocoder: the data loader functions, the address normalizer, the address geocoder, and the reverse geocoder.

Aunque está diseñada específicamente para los EE.UU., muchos de los conceptos y funciones son aplicables y se pueden adaptar al trabajo con las direcciones y redes de carreteras de otros países.

The script builds a schema called tiger to house all the TIGER-related functions, reusable lookup data such as road type prefixes, suffixes, states, various control tables for managing data load, and skeleton base tables from which all the TIGER-loaded tables inherit.

Another schema called tiger_data is also created which houses all the census data for each state that the loader downloads from the Census site and loads into the database. In the current model, each set of state tables is prefixed with the state code e.g ma_addr, ma_edges etc with constraints to enforce only that state data. Each of these tables inherits from the tables addr, faces, edges, etc located in the tiger schema.

All the geocode functions only reference the base tables, so there is no requirement that the data schema be called tiger_data or that data can't be further partitioned into other schemas -- e.g. a different schema for each state, as long as all the tables inherit from the tables in the tiger schema.

For instructions on how to enable the extension in your database and also to load data using it, refer to Section 2.4.1, “Tiger Geocoder Enabling your PostGIS database”.

[Note]

If you are using the TIGER Geocoder (tiger_2010), you can upgrade the scripts using the accompanying upgrade_geocoder.bat / .sh scripts in extras/tiger. One major change between tiger_2010 and tiger_2011+ is that the county and state tables are no longer broken out by state. If you have data from tiger_2010 and want to replace with tiger_2015, refer to Section 2.4.4, “Upgrading your Tiger Geocoder Install and Data”

[Note]

You can install the TIGER Geocoder with the PostgreSQL extension model. Refer to Section 2.4.1, “Tiger Geocoder Enabling your PostGIS database” for details.

The Pagc_Normalize_Address function as a drop in replacement for in-built Normalize_Address. Refer to Section 2.3, “Installing and Using the address standardizer” for compile and installation instructions.

Diseño:

El objetivo de este proyecto es construir un geocodificador totalmente funcional que pueda procesar un texto arbitrario de una dirección de los Estados Unidos y usando datos del censo TIGER normalizados, producir una geometría de punto y una puntuación que refleje la localización de la dirección dada y su concordancia. Cuanto más alta sea la puntuación peor es el resultado.

The reverse_geocode function is useful for deriving the street address and cross streets of a GPS location.

El geocodificador debería ser sencillo de instalar y usar para cualquiera familiriarizado con PostGIS, y debería ser fácilmente instalable y utilizable en todas las plataformas soportadas por PostGIS.

Debería ser suficientemente robusto como para funcionar adecuadamente a pesar de errores de formato o de escritura.

Debería ser lo bastante extensible como para ser usado con futuras actualizaciones de datos, o alternar orígenes de datos con unos cambios de código mínimos.

[Note]

Para que las funciones trabajen adecuadamente debe agregarse el esquema tiger a la ruta de búsqueda de la base de datos.

  • Drop_Indexes_Generate_Script — Generates a script that drops all non-primary key and non-unique indexes on tiger schema and user specified schema. Defaults schema to tiger_data if no schema is specified.
  • Drop_Nation_Tables_Generate_Script — Generates a script that drops all tables in the specified schema that start with county_all, state_all or state code followed by county or state.
  • Drop_State_Tables_Generate_Script — Generates a script that drops all tables in the specified schema that are prefixed with the state abbreviation. Defaults schema to tiger_data if no schema is specified.
  • Geocode — Takes in an address as a string (or other normalized address) and outputs a set of possible locations which include a point geometry in NAD 83 long lat, a normalized address for each, and the rating. The lower the rating the more likely the match. Results are sorted by lowest rating first. Can optionally pass in maximum results, defaults to 10, and restrict_region (defaults to NULL)
  • Geocode_Intersection — Takes in 2 streets that intersect and a state, city, zip, and outputs a set of possible locations on the first cross street that is at the intersection, also includes a geomout as the point location in NAD 83 long lat, a normalized_address (addy) for each location, and the rating. The lower the rating the more likely the match. Results are sorted by lowest rating first. Can optionally pass in maximum results, defaults to 10. Uses Tiger data (edges, faces, addr), PostgreSQL fuzzy string matching (soundex, levenshtein).
  • Get_Geocode_Setting — Returns value of specific setting stored in tiger.geocode_settings table.
  • Get_Tract — Returns census tract or field from tract table of where the geometry is located. Default to returning short name of tract.
  • Install_Missing_Indexes — Finds all tables with key columns used in geocoder joins and filter conditions that are missing used indexes on those columns and will add them.
  • Loader_Generate_Census_Script — Generates a shell script for the specified platform for the specified states that will download Tiger census state tract, bg, and tabblocks data tables, stage and load into tiger_data schema. Each state script is returned as a separate record.
  • Loader_Generate_Script — Generates a shell script for the specified platform for the specified states that will download Tiger data, stage and load into tiger_data schema. Each state script is returned as a separate record. Latest version supports Tiger 2010 structural changes and also loads census tract, block groups, and blocks tables.
  • Loader_Generate_Nation_Script — Generates a shell script for the specified platform that loads in the county and state lookup tables.
  • Missing_Indexes_Generate_Script — Finds all tables with key columns used in geocoder joins that are missing indexes on those columns and will output the SQL DDL to define the index for those tables.
  • Normalize_Address — Given a textual street address, returns a composite norm_addy type that has road suffix, prefix and type standardized, street, streetname etc. broken into separate fields. This function will work with just the lookup data packaged with the tiger_geocoder (no need for tiger census data).
  • Pagc_Normalize_Address — Given a textual street address, returns a composite norm_addy type that has road suffix, prefix and type standardized, street, streetname etc. broken into separate fields. This function will work with just the lookup data packaged with the tiger_geocoder (no need for tiger census data). Requires address_standardizer extension.
  • Pprint_Addy — Given a norm_addy composite type object, returns a pretty print representation of it. Usually used in conjunction with normalize_address.
  • Reverse_Geocode — Takes a geometry point in a known spatial ref sys and returns a record containing an array of theoretically possible addresses and an array of cross streets. If include_strnum_range = true, includes the street range in the cross streets.
  • Topology_Load_Tiger — Loads a defined region of tiger data into a PostGIS Topology and transforming the tiger data to spatial reference of the topology and snapping to the precision tolerance of the topology.
  • Set_Geocode_Setting — Sets a setting that affects behavior of geocoder functions.

There are a couple other open source geocoders for PostGIS, that unlike the TIGER Geocoder have the advantage of multi-country geocoding support

  • Nominatim uses OpenStreetMap gazeteer formatted data. It requires osm2pgsql for loading the data together with PostgreSQL and PostGIS. It is packaged as a webservice interface and seems designed to be called as a webservice. Just like the TIGER Geocoder, it has both a geocoder and a reverse geocoder component. From the documentation, it is unclear if it has a pure SQL interface like the TIGER Geocoder, or if a good deal of the logic is implemented in the web interface.

  • GIS Graphy can utilize PostGIS and like Nominatim uses OpenStreetMap (OSM) data along with some other sources. It comes with a loader to load OSM data and similar to Nominatim is capable of geocoding not just US. Much like Nominatim, it runs as a webservice and relies on Java 1.5, Servlet apps, Solr. GisGraphy is cross-platform and also has a reverse geocoder among some other neat features.