Creando un servidor de OpenStreetMap en Ubuntu 10.04

Índice
1.-Introducción
2.-Empecemos
3.-Preparando la base de datos
4.-Instalando la libreria Mapnik
5.-Instalando las fronteras del mapa
6.-Renderizado del primer mapa
7.-Troubleshooting

1.-Introducción

Primeramente, me gustaria agradecer a “rw”, el autor del post en el que este post está basado. Este post está basado en un 95% en este otro (actualmente no está disponible, pero puedes verlo aquí).

Mi principal intención es divulgar este post a todos mis lectores y almacenar esta información acerca de la plataforma OSM para que al menos haya una referencia online para todos (y por supuesto, para mi). Este post no trata acerca de una introducción ni información acerca de OSM, sino que es información técnica para construir tu propio servidor OSM. También me gustaria mejorar mi conocimiento acerca de este servidor (no simplemente descargarlo, instalarlo y correrlo, estaría bien tratar de entenderlo).

No copiaré y pegaré el mismo contenido del post, porque (como una instalación grande ordinaria) tuve problemas instalando esta plataforma y los he resuelto, por lo que escribiré acerca de lo que he visto, resuelto y conclusiones personales. También iré un poco en profundidad acerca de algunos comandos y demás, cuya explicación si que la dejaré inglés.

2.-Empecemos

Actualiza tu sistema

Por razones de seguridad, está recomendado actualizar el sistema, aunque no es necesario.

sudo apt-get update
sudo apt-get upgrade

Algunas herramientas del sistema

sudo apt-get install subversion autoconf screen munin-node munin htop

Subversion: we’ll use it to donwload files from some repositories.
Autoconf: software to generate autoconfig scripts.
Screen: Screen is a full-screen window manager that multiplexes a physical terminal between several processes, typically interactive shells.
Munin-node: software to monitoring our server from the client.
Munin: client of munin-node.
Htop: software to check and monitoring the system used resources.

Organicemos el sistema de archivos un poquito

cd ~
mkdir src bin planet

  • src: source de mapnik.
  • bin: aquí tendremos los scripts para generar la imagen del mapa y cargar la base de datos.
  • planet: planeta (o una porción) de la base de datos que vamos a construir.

Obten el último fichero del planeta (OSM file)

En esta parte, vamos a descargar la base de datos del mundo entero (actualmente [20 dic 2012] pesa 24GBs) o quizás podemos descargar no el mundo entero sino una porción de éste. Simplemente para probar, elegiré descargar una porción.

cd planet
wget http://planet.openstreetmap.org/planet-latest.osm.bz2

3.-Preparando la base de datos

Aqui vamos a descargar postgresql para meter nuestra base de datos ahi, incluyendo algunas librerias para poder usarlo.

sudo apt-get install postgresql-8.4-postgis postgresql-contrib-8.4
sudo apt-get install postgresql-server-dev-8.4
sudo apt-get install build-essential libxml2-dev
sudo apt-get install libgeos-dev libpq-dev libbz2-dev proj

Build-essential: This package contains an informational list of packages which are considered essential for building Debian packages.
Libxml2-dev: Very useful if you wish to develop your own programs using the GNOME XML library.
Libgeos-dev: GEOS provides a spatial object model and fundamental geometric functions. It implements the geometry model defined in the OpenGIS Consortium Simple Features Specification for SQL.
Libpq-dev: Header files and static library for compiling C programs to link with the libpq library in order to communicate with a PostgreSQL database backend.
Libbz2-dev: Static libraries and include files for the bzip2 compressor library.
Proj: Standard Unix filter function which converts geographic longitude and latitude coordinates into cartesian coordinates, by means of a wide variety of cartographic projection functions.

Instalar osm2pgsql del repositorio

Primero descargamos osm2pgsql del repositorio, y depués, lo configuramos. osm2pgsql es un programa que convierte datos de OpenStreetMap en bases de datos para PostgreSQL

cd ~/bin
svn co http://svn.openstreetmap.org/applications/utils/export/osm2pgsql/
cd osm2pgsql
./autogen.sh (Error?)
./configure
make

Configurando la base de datos de PostGIS

Editamos /etc/postgresql/8.4/main/postgresql.conf para modificar/añadir 4 lineas. Estos cambios ayudarán a usar grandes cantidadesd e datos.

107: shared_buffers = 128MB # 16384 para versión 8.1 y anteriores
170: checkpoint_segments = 20
(nueva línea): maintenance_work_mem = 256MB # 256000 para versión 8.1 y anteriores
387: autovacuum = off

Editamos /etc/sysctl.conf

(nueva línea) kernel.shmmax=268435456

Recuerda que lo anterior solo tiene efecto después de reiniciar. Para que tenga efecto inmediatamente realizaremos lo siguiente.

sudo sysctl kernel.shmmax=268435456

Reiniciamos postgres para habilitar los cambios.

sudo /etc/init.d/postgresql-8.4 restart

Creamos una base de datos llamada “gis”. Algunas de nuestras herramientas suponen el uso de ese nombre en la base de datos, por lo que si elegis otro nombre, tenedlo en cuenta. Lo mismo para “username” con el usuario creado. Este deberia ser el nombre de usuario que va a renderizar los mapas con mapnik
Nota del autor de delanover: Tuve problemas con el nombre de usuario, por lo que decidi usar el mismo que en el ordenador.

sudo -u postgres -i
createuser username # responder ‘yes’ para que sea superusuario
createdb -E UTF8 -O username gis
createlang plpgsql gis
exit

Configuración de postgis en la base de datos postgresql

psql -f /usr/share/postgresql/8.4/contrib/postgis.sql -d gis

Deberia responder con algunas lineas y acabar en


CREATE FUNCTION
COMMIT

Sustituir tu nombre de usuario por “username” en las siguientes lineas. Este deberia ser el que va a renderizar los mapas con mapnik, como dijimos anteriormente.

echo “ALTER TABLE geometry_columns OWNER TO username; ALTER TABLE spatial_ref_sys OWNER TO username;” | psql -d gis

Deberia devolver

ALTER TABLE
ALTER TABLE

Activamos intarray

psql -f /usr/share/postgresql/8.4/contrib/_int.sql -d gis

Deberia devolver varias líneas acabadas en


CREATE FUNCTION
CREATE OPERATOR CLASS

Configuramos el Set the Spatial Reference Identifier (SRID) en la nueva base de datos.

psql -f ~/bin/osm2pgsql/900913.sql -d gis

Deberia devolver

INSERT 0 1

Cargamos el planeta en la base de datos con osm2pgsql

cd ~/bin/osm2pgsql
./osm2pgsql -S default.style –slim -d gis -C 2048 ~/planet/YourFileMap.osm.bz2 (Error?)

Nota: cargar 8.4GB lleva 30 hours, y particularme 1.4GB me llevaron 8 horas (depende de la velocidad de E/S), por lo que sé paciente.

Completed planet_osm_roads
Copying planet_osm_polygon to cluster by geometry finished
Copying planet_osm_line to cluster by geometry finished
Creating indexes on planet_osm_polygon finished
All indexes on planet_osm_polygon created in 4257s
Completed planet_osm_polygon
Creating indexes on planet_osm_line finished
All indexes on planet_osm_line created in 5053s
Completed planet_osm_line
Stopped table: planet_osm_ways in 16095s
Osm2pgsql took 29436s overall

4.-Instalando la librería Mapnik

sudo apt-get install libltdl3-dev libpng12-dev libtiff4-dev libicu-dev
sudo apt-get install libboost-python1.40-dev python-cairo-dev python-nose
sudo apt-get install libboost1.40-dev libboost-filesystem1.40-dev
sudo apt-get install libboost-iostreams1.40-dev libboost-regex1.40-dev libboost-thread1.40-dev
sudo apt-get install libboost-program-options1.40-dev libboost-python1.40-dev
sudo apt-get install libfreetype6-dev libcairo2-dev libcairomm-1.0-dev
sudo apt-get install libgeotiff-dev libtiff4 libtiff4-dev libtiffxx0c2
sudo apt-get install libsigc++-dev libsigc++0c2 libsigx-2.0-2 libsigx-2.0-dev
sudo apt-get install libgdal1-dev python-gdal
sudo apt-get install imagemagick

Libltdl3-dev: A small library that aims at hiding the various difficulties of dlopening libraries from programmers. It is a system independent dlopen wrapper for GNU libtool.
Libpng12-dev: Library implementing an interface for reading and writing PNG format files.
Libtiff4-dev: Library providing support for the Tag Image File Format (TIFF), a widely used format for storing image data. This package includes the development files, static library, and header files.
Libicu-dev: ICU is a C++ and C library that provides robust and full-featured Unicode and locale support. This package contains the development files for ICU along with programs used to manipulate data files found in the ICU sources.
Libboost libraries: Boost provides free peer-reviewed portable C++ source libraries.
Python libraries: So obvious.
Libfreetype6-dev: This package contains all supplementary files (static library, headers and documentation) you need to develop your own programs using the FreeType 2 library (digital typography library).
Libcairo2-dev: Cairo is a multi-platform library providing anti-aliased vector-based rendering for multiple target backends.
Libgeotiff-dev: The GeoTIFF standard has been developed for reading, and writing geographic meta-information tags on top of TIFF raster.
Tiff libraries: So obvious, to work with tiff format.
Libsigc libraries: implement a typesafe callback system for standard C++. It allows you to define signals and to connect those signals to any callback function, either global or a member function, regardless of whether it is static or virtual.
Libgdal1-dev: GDAL is a translator library for raster geospatial data formats. As a library, it presents a single abstract data model to the calling application for all supported formats.
Imagemagick: software suite to create, edit, compose, or convert bitmap images.

Construimos la libreria de Mapnik desde el código fuente.

cd ~/src
svn co http://svn.mapnik.org/tags/release-0.7.1/ mapnik (Error? offline)
cd mapnik
python scons/scons.py configure INPUT_PLUGINS=all OPTIMIZATION=3 SYSTEM_FONTS=/usr/share/fonts/truetype/ (Error? boost version)
python scons/scons.py #be patient here
sudo python scons/scons.py install
sudo ldconfig

Confirmamos que la libreria Mapnik está instalada.

python
>>> import mapnik
>>>

Instalamos herramientas para Mapnik

cd ~/bin
svn co http://svn.openstreetmap.org/applications/rendering/mapnik

5.-Instalando las fronteras del mapa

cd ~/bin/mapnik
mkdir world_boundaries
wget http://tile.openstreetmap.org/world_boundaries-spherical.tgz
tar xvzf world_boundaries-spherical.tgz
cd world_boundaries
wget http://tile.openstreetmap.org/processed_p.tar.bz2
bunzip2 processed_p.tar.bz2
tar xvf processed_p.tar
wget http://tile.openstreetmap.org/shoreline_300.tar.bz2
bunzip2 shoreline_300.tar.bz2
tar xvf shoreline_300.tar

6.-Renderizado del primer mapa

cd ~/bin/mapnik
chmod +x generate_xml.py
./generate_xml.py –dbname gis –accept-none [NOTA IMPORTANTE]

NOTA IMPORTANTE: No se porqué no se ve bien el doble guión. Recuerda que es “–” (dos “-“) y no un solo “-“.

Include files written successfully! Pass the osm.xml file as an argument if you want to serialize a new version or test reading the XML

Finalmente generamos la imagen.

./generate_image.py (Error?)

El resultado será una imagen PNG de 10000x5000px de resolución del Reino Unido, en la carpeta de mapnik. Recuerda, sé paciente.

Espero que haya disfrutado de este tutorial!

7.-Troubleshooting

Error 1: Configurando al instalar osm2pgsql
Error al ejecutar ./configure cuando estamos instalando osm2pgsql:

Can’t exec “libtoolize”: No such file or directory at /usr/bin/autoreconf line 189.
Use of uninitialized value in pattern match (m//) at /usr/bin/autoreconf line 189.
autoreconf: Entering directory `.’
autoreconf: configure.ac: not using Gettext
autoreconf: running: aclocal –force -I m4
configure.ac:41: warning: macro `AM_PROG_LIBTOOL’ not found in library
autoreconf: configure.ac: tracing
autoreconf: configure.ac: not using Libtool
autoreconf: running: /usr/bin/autoconf –force
configure.ac:41: error: possibly undefined macro: AM_PROG_LIBTOOL
If this token and others are legitimate, please use m4_pattern_allow.
See the Autoconf documentation.
autoreconf: /usr/bin/autoconf failed with exit status: 1

Solution
No puedes ejecutar libtoolize, por lo que debes instalar libtool antes de continar, escribe:

sudo apt-get install libtool

Error 2: Cargando un planeta en la base de datos
Quizás tengas un error mientras estés cargando los datos del planeta:

The target database has the intarray contrib module loaded.
While required for earlier versions of osm2pgsql, intarray
is now unnecessary and will interfere with osm2pgsql’s array
handling. Please use a database without intarray.

Error occurred, cleaning up

Para arreglarlo, realizaremos un arreglo que aparece en la documentación oficial

sudo -u postgres -i -H
dropdb ptgis
### here the old database is dropped
createdb -E UTF8 -O ptuser ptgis
createlang plpgsql ptgis

# for Ubuntu <=9.10: # psql -d ptgis -f /usr/share/postgresql/8.3/contrib/_int.sql ### (do not execute this line) psql -d ptgis -f /usr/share/postgresql-8.3-postgis/lwpostgis.sql # for Ubuntu >=10.04:
#psql -d ptgis -f /usr/share/postgresql/8.4/contrib/_int.sql ### (do not execute this line)
psql -d ptgis -f /usr/share/postgresql/8.4/contrib/postgis.sql
psql ptgis -c “ALTER TABLE geometry_columns OWNER TO ptuser”
psql ptgis -c “ALTER TABLE spatial_ref_sys OWNER TO ptuser”
exit

# for Ubuntu <=9.10: sudo /etc/init.d/postgresql-8.3 reload # for Ubuntu >=10.04:
sudo /etc/init.d/postgresql-8.4 reload

psql ptgis ptuser -f osm2pgsql/900913.sql

Ahora, intentaremos cargar los datos de nuevo.

Error 3: Repositorio de Mapnik offline
Establezco esto como un error porque, quien sabe, igual algún dia vuelva a estar online. Pero ahora no lo está, por lo que debemos encontrar otro sitio para descargarlo.
Necesitamos descargar el software de git para poder descargar desde un repositorio git, y despues de eso, podremos descargar mapnik desde aquí

sudo apt-get install git-core
git clone https://github.com/mapnik/mapnik.git

Error 4: Boost version >= 1.47 required
Podemos comprobar nuestra versión de boost actual mirando en la línea 30 en el fichero /usr/include/boost/version.hpp para darnos cuenta de que no tenemos la versión 1.47 o superior, por lo que, tenemos que actualizarla. Esto no es tan sencillo como un simple apt-get install, pero es tan sencillo como: descargar e instalarlo.

Necesitamos descargar la última versión (http://www.boost.org/) (a dia de hoy, la 1.52, desde http://sourceforge.net/projects/boost/files/boost/1.52.0/). Seleccionamos el fichero tar.bz2, lo descomprimimos, configuramos y demás.

bunzip2 boost_1_52_0.tar.bz2
tar xvf boost_1_52_0.tar
./bootstrap.sh
./b2
sudo ./b2 install

Error 5: No existen algunos archivos necesarios!
Después de intentar generar la imagen (vaya suerte, justo fallando en el último paso…) se nos podria devolver el siguiente error.

RuntimeError: Shape Plugin: shapefile ‘/home/lipman/bin/mapnik/world_boundaries/110m_admin_0_boundary_lines_land.shp’ does not exist encountered during parsing of layer ‘necountries’ in Layer at line 58 of ‘osm.xml’

El único problema aquí es que necesitamos algunos archivos que no tenemos, por tanto, descarguémoslos y movámoslos a la carpeta world_boundaries para arreglarlo.

Encontré los archivos aquí. Tenemos que descargar los siguientes:

  • 110m_admin_0_boundary_lines_land.shp
  • 110m_admin_0_boundary_lines_land.dbf
  • 10m_populated_places.shp (*)
  • 10m_populated_places.dbf (*)

(*): Tenemos que renombrarlos a “ne_10m…”

One Reply to “Creando un servidor de OpenStreetMap en Ubuntu 10.04”

Leave a Reply

Your email address will not be published. Required fields are marked *