summaryrefslogtreecommitdiff
path: root/chimere/route.py
blob: bc08a3986fbb9e561edbc3e980e6e74371af9b33 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2012  Étienne Loks  <etienne.loks_AT_peacefrogsDOTnet>
#

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# See the file COPYING for details.

"""
Routing management
"""

import os, re, shutil, tempfile
from BeautifulSoup import BeautifulSoup
from subprocess import Popen, PIPE
from django.contrib.gis.gdal import DataSource

from django.conf import settings

class Router:
    def route(self, lon1, lat1, lon2, lat2, transport='foot'):
        '''
        Get a list of geojson polylines
        '''
        return []

class RoutinoRouter(Router):
    re_desc = [re.compile("<tr class='n'>"), re.compile("<tr class='s'>"),
               re.compile("<tr class='t'>")]
    def route(self, lon1, lat1, lon2, lat2, steps=[], transport='foot'):
        '''
        Get a list of geojson polylines and route description
        '''
        language = settings.LANGUAGE_CODE.split('-')[0]
        args = [settings.CHIMERE_ROUTING_ENGINE['PATH'],
                "--dir=%s" % settings.CHIMERE_ROUTING_ENGINE['DB_PATH'],
                "--transport=%s" % transport,
                "--language=%s" % language,
                "--shortest",
                "--output-html",
                "--output-gpx-track",
                "--lat1=%0.15f" % lat1,
                "--lon1=%0.15f" % lon1,
                ]
        lonlat_index = 1
        for lon, lat in steps:
            lonlat_index += 1
            args += ["--lat%d=%0.15f" % (lonlat_index, lat),
                     "--lon%d=%0.15f" % (lonlat_index, lon)]
        lonlat_index += 1
        args += ["--lat%d=%0.15f" % (lonlat_index, lat2),
                 "--lon%d=%0.15f" % (lonlat_index, lon2)]
        tmp_dir = tempfile.mkdtemp(prefix='chimere_') + os.sep
        p = Popen(args, stdout=PIPE, cwd=tmp_dir)
        p.communicate()
        ds = DataSource(tmp_dir + 'shortest-track.gpx')
        if not ds:
            return [], None
        layer = ds[0]
        trk_layer = None
        for layer in ds:
            if layer.name == 'tracks':
                trk_layer = layer
                break
        multilines = trk_layer.get_geoms()
        res = []
        for multiline in multilines:
            res += [geom.geojson for geom in multiline]
        desc = []
        # only keeping interessant lines of the desc
        for line in open(tmp_dir + 'shortest.html').readlines():
            if [True for r in self.re_desc if r.match(line)]:
                desc.append(BeautifulSoup(line).prettify())
        desc = ['<table>'] + desc[1:-2] + [desc[-1], '</table>']
        desc = BeautifulSoup('\n'.join(desc)).prettify()
        shutil.rmtree(tmp_dir)
        return res, desc
router = None
if settings.CHIMERE_ROUTING_ENGINE['ENGINE'] == 'routino':
    router = RoutinoRouter()