Cálculo de rotas com dados do OpenStreetMap

From Open source mapmaking technologies
Jump to: navigation, search
This page is a translated version of the page Routing with OSM data and the translation is 33% complete.

Other languages:
English • ‎português

Cálculo de rotas

Existem várias soluções open source para o cálculo de rotas, tirando partido dos dados do OpenStreetMap.

Neste exercício, vamos usar o software Routino.

Vamos começar por instalar alguns pacotes que vão ser necessários para compilar o Routino.

sudo apt-get install flex libbz2-dev libjson-pp-perl

Download routino

mkdir public_html
cd public_html
wget http://www.routino.org/download/routino-2.7.3.tgz

Compiling routino

tar xvzf routino-2.7.3.tgz
cd routino-2.7.3
make

Descarregar os dados de Portugal

Para cada região ou país, é extraído diariamente um planet, que é um arquivo que contém os dados OSM dessa mesma área.

A descarga pode demorar alguns minutos, dependendo da velocidade da sua ligação.

Depois de descarregado, o planet é usado para calcular um grafo, que é uma representação matemática de todas as ligações existentes na rede viária. O cálculo de rotas é feito sobre este grafo, usando algoritmos bem conhecidos.

O grafo demora alguns minutos a gerar.

cd web/data
wget http://download.geofabrik.de/europe/portugal-latest.osm.bz2
../bin/planetsplitter portugal-latest.osm.bz2

Testar o cálculo no terminal

Use as coordenadas de dois pontos em Portugal para testar se o cálculo de rotas está a funcionar, antes de prosseguir.

../bin/router --lon1=-8.40298 --lat1=41.54766 --lon2=-8.39764 --lat2=41.56185 --output-gpx-track --shortest

If it works, a new shortest-track.gpx is written with the result. You can open it in QGIS, for example, to make sure it has a route. Let's learn another way of adding data to QGIS: passing it as parameters when calling QGIS.

qgis shortest-track.gpx

Since the gpx format can support different layers simultaneously, when you add a gpx track, a dialog with open to choose the desired layer(s). Choose the track layer.

GPX dialog.png

A track is displayed, hopefully. If the track is shown, the routing software is working. If not, do not proceed until you solve the problem.

Now we can proceed to install a web interface on top of this routing software.

Apache configuration

Apache is a very well know web server. It is the most used web server.

Let's configure Apache to serve our web routing solution. To do so, we need to edit Apache configuration.

sudo medit /etc/apache2/sites-enabled/000-default.conf

Add the following configuration by the end of the file, but before </VirtualHost>.

        AddHandler cgi-script .cgi 
        Alias /routino/ "/home/user/public_html/routino-2.7.3/web/"
        <Directory "/home/user/public_html/routino-2.7.3/web/">
                Options +Indexes +FollowSymLinks +MultiViews +ExecCGI
                AllowOverride All
                Require all granted
        </Directory>

Save and close the editor, and restart the Apache server with:

sudo apache2ctl graceful

Não se preocupe, se for apresentado o aviso:

apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName

Open http://localhost/routino/www/routino/router.html with the browser. You should see something, but not yet the complete web interface.

Routino web configuration

Let's install some Javascript libraries.

cd ../www/openlayers/
medit install.sh

Replace the line:

wget http://openlayers.org/download/OpenLayers-$version.tar.gz

with:

wget http://github.com/openlayers/openlayers/releases/download/release-2.13.1/OpenLayers-$version.tar.gz

Save. Now we can proceed.

sh -x install.sh
cd ../leaflet
sh -x install.sh
cd ../..
chmod -R a+rw results

Check if you can open http://localhost/routino/www/routino/router.html.

OpenStreetMap opens centered in England. We need to change mapprops.js.

cd www/routino
medit mapprops.js

Replace the bounds with these values (copy and paste on top of the existing lines):

  westedge:  -9.47,          // Minimum longitude (degrees)
  eastedge:  -6.17,          // Maximum longitude (degrees)

  southedge:  36.95,          // Minimum latitude (degrees)
  northedge:  42.14,          // Maximum latitude (degrees)

  zoomout:       7,          // Minimum zoom
  zoomin:       18,          // Maximum zoom

Para saber os limites que envolvem Portugal, pode fazer:

ogrinfo -so Cont_AAD_CAOP2014.shp
Extent: (-119191.407500, -300404.804000) - (162129.081100, 276083.767400)

Como a CAOP nos dá coordenadas no sistema EPSG:3763, é preciso converter estas coordenadas para o sistema ESPSG:4326.

echo -119191.407500 -300404.804000 | cs2cs -f "%.2f" +init=epsg:3763 +to +init=epsg:4326
-9.47	36.95 0.00
echo 162129.081100 276083.767400 | cs2cs -f "%.2f" +init=epsg:3763 +to +init=epsg:4326
-6.17	42.14 0.00

Open again http://localhost/routino/www/routino/router.html

You should see the map centered in China and now you can calculate routes.

If something is falling, use the browser firebug/development tools to identify the problem. The configuration is complete.

Routino up and running.png

Update OpenStreetMap data automatically

To keep the routing update as possible, we need to download the OSM periodically.

The following script getchina.osm.sh will download the planet file and reconstruct the routing graph.

cd ~/public_html/routino-2.7.3/web/data
medit getchina.osm.sh

Contents of getchina.osm.shː

#!/bin/bash
#
cd ~/public_html/routino-2.7.3/web/data
find . -type f -mtime +7 -name '*'.osm.bz2 -exec rm -f \{\} \;
data=`date +%Y%m%d%H%M`
planeta=china-latest.$data.osm.bz2
server="download.geofabrik.de"
wget -N http://$server/asia/china-latest.osm.bz2 -O $planeta
../bin/planetsplitter --errorlog $planeta

Before we can run the script, we have grant it the execute privilege, withː

chmod +x getchina.osm.sh

Now the script can be run at any time, just by doingː

./getchina.osm.sh

To keep the data updated and to minimize the server overload, a better option is to download it and recreate the graph in in off-peak hours. crontab is used to configure repeating tasks in Lunix.

crontab -e

(crontab will ask you which editor to use. Accept the default, and go to the end of the file.)

# m h  dom mon dow   command
45 5 * * * $HOME/public_html/routino-2.7.3/web/data/getchina.osm.sh