コード例 #1
0
ファイル: city_utils.py プロジェクト: sambandi/eMonitor
def loadCitiesFromOsm():
    """
    Load all cities from OpenStreetMap, use bounding box for position

    :return: rendered template
    """
    global URL
    map_details = Map.getMaps()[0].getMapBox(
        tilepath=current_app.config.get('PATH_TILES'))
    SEARCHSTRING = 'rel[boundary=administrative](%s,%s,%s,%s);out;' % (
        map_details['min_latdeg'], map_details['min_lngdeg'],
        map_details['max_latdeg'], map_details['max_lngdeg']
    )  # search all cities in bounding box
    requests.session()
    r = requests.post(URL, data={'data': SEARCHSTRING})

    xmldoc = minidom.parseString(r.content)
    relations = xmldoc.getElementsByTagName('relation')

    osmids = [c.osmid for c in City.getCities()]
    cities = []
    for relation in relations:
        for tag in relation.childNodes:
            if tag.nodeName == "tag" and tag.attributes['k'].value == 'name':
                cities.append([
                    relation.attributes['id'].value, tag.attributes['v'].value,
                    int(relation.attributes['id'].value) in osmids
                ])

    cities.sort(lambda x, y: cmp(x[1], y[1]))

    return render_template('admin.streets.city_osm.html', cities=cities)
コード例 #2
0
def loadCitiesFromOsm():
    """
    Load all cities from OpenStreetMap, use bounding box for position

    :return: rendered template
    """
    global URL
    map_details = Map.getMaps()[0].getMapBox(tilepath=current_app.config.get('PATH_TILES'))
    SEARCHSTRING = 'rel[boundary=administrative](%s,%s,%s,%s);out;' % (map_details['min_latdeg'], map_details['min_lngdeg'], map_details['max_latdeg'], map_details['max_lngdeg'])  # search all cities in bounding box
    requests.session()
    r = requests.post(URL, data={'data': SEARCHSTRING})

    xmldoc = minidom.parseString(r.content)
    relations = xmldoc.getElementsByTagName('relation')
    
    osmids = [c.osmid for c in City.getCities()]
    cities = []
    for relation in relations:
        for tag in relation.childNodes:
            if tag.nodeName == "tag" and tag.attributes['k'].value == 'name':
                cities.append([relation.attributes['id'].value, tag.attributes['v'].value, int(relation.attributes['id'].value) in osmids])
    
    cities.sort(lambda x, y: cmp(x[1], y[1]))

    return render_template('admin.streets.city_osm.html', cities=cities)
コード例 #3
0
ファイル: settings.py プロジェクト: GroSte/eMonitor
 def getMapTiles(mid=0, zoom=17 or db.app.config.get('DEFAULTZOOM')):
     from emonitor.modules.maps.map import Map
     _map = Map.getMaps(mid)
     tiles = []
     try:
         for ts in [f for f in os.listdir(_map.path + str(zoom) + '/') if f.endswith('png')]:
             tiles.append(ts.replace('-', '/'))
     except:
         pass
     return tiles
コード例 #4
0
ファイル: settings.py プロジェクト: sambandi/eMonitor
 def getMapTiles(mid=0, zoom=17 or db.app.config.get('DEFAULTZOOM')):
     from emonitor.modules.maps.map import Map
     _map = Map.getMaps(mid)
     tiles = []
     try:
         for ts in [
                 f for f in os.listdir(_map.path + str(zoom) + '/')
                 if f.endswith('png')
         ]:
             tiles.append(ts.replace('-', '/'))
     except:
         pass
     return tiles
コード例 #5
0
ファイル: content_frontend.py プロジェクト: sambandi/eMonitor
def getFrontendContent(**params):
    """
    Deliver frontend content of module maps

    :return: data of maps
    """
    if 'area' not in params.keys() and request.args.get('area', '') != '':
        params['area'] = request.args.get('area')

    if 'area' in params.keys() and params['area'] in ['west', 'center', 'east']:  # select view
        tiledefs = [d for d in Settings.get('mapitemdefinition') if d['parameters']['tileserver'] == '1']

        return render_template('frontend.map.html', maps=Map.getMaps(), defaultlat=Settings.get('defaultLat'), defaultlng=Settings.get('defaultLng'), defaultzoom=Settings.get('defaultZoom'), maptype="" or Map.getDefaultMap(), tiledefs=tiledefs)
    return "default"
コード例 #6
0
def getTilePath(mappath, zoom, lat, lng):
    """ deliver filepath to seleceted tile """
    #global mappath
    if not mappath:
        mappath = Map.getMaps()[0].path
    path = "%s%s/%s/" % (current_app.config.get('PATH_TILES'), mappath, zoom)
    filename = "%s-%s.png" % (lat, lng)
    
    if not os.path.exists('%s/%s' % (path, filename)):  # deliver default tile
        #current_app.logger.error('tileserver: tile not found %s%s using default' % (path, filename))
        if current_app.config.get('TILE_MISSING') == 'load' and "osm" in path:  # load tile from url
            getTileFromURL(zoom, path + filename, lat, lng)
            return path, filename
        else:
            return current_app.config.get('PATH_DATA'), 'default.png'
    else:
        return path, filename
コード例 #7
0
def getTilePath(mappath, zoom, lat, lng):
    """ deliver filepath to seleceted tile """
    #global mappath
    if not mappath:
        mappath = Map.getMaps()[0].path
    path = "%s%s/%s/" % (current_app.config.get('PATH_TILES'), mappath, zoom)
    filename = "%s-%s.png" % (lat, lng)

    if not os.path.exists('%s/%s' % (path, filename)):  # deliver default tile
        #current_app.logger.error('tileserver: tile not found %s%s using default' % (path, filename))
        if current_app.config.get(
                'TILE_MISSING'
        ) == 'load' and "osm" in path:  # load tile from url
            getTileFromURL(zoom, path + filename, lat, lng)
            return path, filename
        else:
            return current_app.config.get('PATH_DATA'), 'default.png'
    else:
        return path, filename
コード例 #8
0
ファイル: content_admin.py プロジェクト: schopf16/eMonitor
def getAdminContent(self, **params):
    """
    Deliver admin content of module streets

    :param params: use given parameters of request
    :return: rendered template as string
    """
    module = request.view_args['module'].split('/')
    if len(module) < 2:
        if City.getDefaultCity():
            module.append(u'{}'.format(City.getDefaultCity().id))
        else:
            module.append(u'1')

    if len(module) == 2:  # cities
        if module[1] == '0':  # city list

            if request.method == 'POST':

                if request.form.get('action').startswith('detailcity_'):  # edit city
                    params.update({'city': City.getCities(id=request.form.get('action').split('_')[-1]), 'departments': Department.getDepartments(), 'maps': Map.getMaps()})
                    return render_template('admin.streets.city_edit.html', **params)

                elif request.form.get('action') == 'updatecity':  # update existing city
                    if request.form.get('city_id') != 'None':  # update city
                        city = City.getCities(id=request.form.get('city_id'))
                        city.name = request.form.get('cityname')
                        city.subcity = request.form.get('subcity')
                        city._dept = request.form.get('department')
                        city.mapname = request.form.get('citymap')
                        city.color = request.form.get('colorname')
                        city.default = request.form.get('citydefault')
                        city.osmid = request.form.get('osmid')
                        city.osmname = request.form.get('osmname')

                    else:  # add city
                        city = City(request.form.get('cityname'), request.form.get('department'),
                                    request.form.get('citymap'), request.form.get('citydefault'),
                                    request.form.get('subcity'), request.form.get('colorname'),
                                    request.form.get('osmid'), request.form.get('osmname'))
                        db.session.add(city)

                    db.session.commit()
                    cache.clear()

                elif request.form.get('action') == 'createcity':  # add city
                    params.update({'city': City('', '', '', '', '', '', 0, ''), 'departments': Department.getDepartments(), 'maps': Map.getMaps()})
                    return render_template('admin.streets.city_edit.html', **params)

                elif request.form.get('action').startswith('deletecity_'):  # delete city
                    db.session.delete(City.getCities(id=request.form.get('action').split('_')[-1]))
                    db.session.commit()
                self.updateAdminSubNavigation()
                cache.clear()

            params.update({'cities': City.getCities()})
            return render_template('admin.streets.city_list.html', **params)

        else:  # show city details
            if request.method == 'POST':
                if request.form.get('action').startswith('detailstreet_'):  # edit street
                    tileserver = {'lat': Settings.get('defaultLat'),
                                  'lng': Settings.get('defaultLng'),
                                  'zoom': Settings.get('defaultZoom'),
                                  'map': Map.getDefaultMap()}
                    params.update({'street': Street.getStreets(id=request.form.get('action').split('_')[-1]), 'cities': City.getCities(), 'maps': Map.getMaps(), 'tileserver': tileserver})
                    return render_template('admin.streets_edit.html', **params)

                elif request.form.get('action') == 'createstreet':  # add street
                    tileserver = {'lat': Settings.get('defaultLat'),
                                  'lng': Settings.get('defaultLng'),
                                  'zoom': Settings.get('defaultZoom'),
                                  'map': Map.getDefaultMap()}

                    params.update({'street': Street('', '', int(module[1]), '', '', '', '', '', ''), 'cities': City.getCities(), 'maps': Map.getMaps(), 'tileserver': tileserver})
                    return render_template('admin.streets_edit.html', **params)

                elif request.form.get('action').startswith('deletestreets_'):  # delete street
                    db.session.delete(Street.getStreets(id=request.form.get('action').split('_')[-1]))
                    db.session.commit()
                    cache.clear()

                elif request.form.get('action') == 'savestreet':  # save street
                    if request.form.get('street_id') != 'None':  # update existing street
                        street = Street.getStreets(id=request.form.get('street_id'))
                        street.name = request.form.get('edit_name')
                        street.navigation = request.form.get('edit_navigation')
                        c = request.form.get('edit_cityid').split('_')
                        if len(c) < 2:
                            c.append('')
                        street.cityid = c[0]
                        street.subcity = c[1]
                        street.lat = request.form.get('edit_lat')
                        street.lng = request.form.get('edit_lng')
                        street.zoom = request.form.get('edit_zoom')
                        street.active = request.form.get('edit_active')
                        db.session.commit()
                        #cache.delete_memoized(City.streets)

                    else:  # add street
                        c = request.form.get('edit_cityid').split('_')
                        if len(c) < 2:
                            c.append('')  # subcity
                        city = [ct for ct in City.getCities() if str(ct.id) == c[0]][0]
                        city.addStreet(Street(request.form.get('edit_name'), request.form.get('edit_navigation'), int(c[0]), c[1], request.form.get('edit_lat'), request.form.get('edit_lng'), request.form.get('edit_zoom'), request.form.get('edit_active'), ''))
                        db.session.commit()
                    cache.clear()

            try:
                streets = Street.getStreets(cityid=module[-1])
            except AttributeError:
                streets = []
            chars = {}
            for s in streets:
                chars[s.name[0].upper()] = 0
            params.update({'streets': streets, 'chars': sorted(chars.keys()), 'city': City.getCities(id=module[-1])})
            return render_template('admin.streets.html', **params)

    return "streets"
コード例 #9
0
def getAdminData(self, **params):
    """
    Deliver admin content of module maps (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'checkpath':
        if os.path.exists(request.args.get('path')):
            return '1'
        return '0'

    elif request.args.get('action') == 'loadmap':  # load tiles

        tile_path = request.args.get('path')

        def calcSubItems((pos)):
            return [(2 * int(pos[0]), 2 * int(pos[1])), (2 * int(pos[0]) + 1, 2 * int(pos[1])), (2 * int(pos[0]), 2 * int(pos[1]) + 1), (2 * int(pos[0]) + 1, 2 * int(pos[1]) + 1)]

        #def getTile(zoom, pos):
        #    global tile_path
        #    response = urllib2.urlopen('http://a.tile.openstreetmap.org/%s/%s/%s.png' % (zoom, pos[0], pos[1]))
        #    #fout = open(tile_path + str(zoom)+'/'+str(pos[0])+'-'+str(pos[1])+'.png', 'wb')
        #    fout = open("%s%s/%s-%s.png" % (tile_path, zoom, pos[0], pos[1]), 'wb')
        #    fout.write(response.read())
        #    fout.close()

        _items = {12: [], 13: [], 14: [], 15: [], 16: [], 17: [], 18: []}
        for t in request.args.get('tiles').split("-"):
            if t != '':
                _items[12].append(t.split(","))

        for zoom in range(13, 19):
            for i in _items[zoom - 1]:
                _items[zoom] += calcSubItems(i)

        result = map_utils.loadTiles('%s%s' % (current_app.config.get('PATH_TILES'), request.args.get('path')), _items)
        if result == 0:
            return babel.gettext('settings.map.loadinginprogress')  # loading still active
        elif result == 1:
            return babel.gettext('settings.map.loadingstarted')  # loading started
        return ""

    elif request.args.get('action') == 'stoptileload':  # stop tile download
        for i in map_utils.LOADTILES:
            signal.send('map', 'tiledownloaddone', tiles=i)
        map_utils.LOADTILES = []
        map_utils.CURRENTLOADING = []
        return {}

    elif request.args.get('action') == 'maptiles':
        _map = Map.getMaps(id=request.args.get('id'))
        if _map:
            return Map.getMapBox(tilepath=current_app.config.get('PATH_TILES'), mappath=_map.path)
        return Map.getMapBox()

    elif request.args.get('action') == 'loadosmdata':  # load all data from openstreetmap
        from emonitor.extensions import scheduler
        from emonitor.lib.osm.loaddata import parseOsmData
        #import time, datetime
        mapdata = Map.getMaps()[0].getMapBox(tilepath=current_app.config.get('PATH_TILES'))

        lat = [mapdata['min_latdeg']]
        while lat[-1] + .05 < mapdata['max_latdeg']:
            lat.append(lat[-1] + .05)
        lat.append(mapdata['max_latdeg'])

        lng = [mapdata['min_lngdeg']]
        while lng[-1] + .05 < mapdata['max_lngdeg']:
            lng.append(lng[-1] + .05)
        lng.append(mapdata['max_lngdeg'])

        scheduler.add_job(parseOsmData, kwargs={'lat': lat, 'lng': lng, 'path': current_app.config.get('PATH_DATA')})
        return {'job': 'started'}

    elif request.args.get('action') == 'findcity':  # search citystring and deliver position
        return map_utils.loadPositionOfCity(request.args.get('cityname'))

    return ""
コード例 #10
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module maps

    :param params: use given parameters of request
    :return: rendered template as string
    """
    module = request.view_args['module'].split('/')

    if len(module) > 1:
        if module[1] == 'position':
            if request.method == 'POST':
                if request.form.get('action') == 'saveposition':  # safe default map position and home position
                    Settings.set('defaultLat', request.form.get('default_lat', ''))
                    Settings.set('defaultLng', request.form.get('default_lng', ''))
                    Settings.set('defaultZoom', request.form.get('default_zoom', ''))

                    Settings.set('homeLat', request.form.get('home_lat', ''))
                    Settings.set('homeLng', request.form.get('home_lng', ''))

                    db.session.commit()

            params.update({'settings': Settings})
            return render_template('admin.map.position.html', **params)

    else:
        if request.method == 'POST':
            if request.form.get('action') == 'savemap':  # save map
                if request.form.get('map_id') != 'None':  # update
                    _map = Map.getMaps(request.form.get('map_id'))
                    _map.name = request.form.get('map_name')
                    _map.path = request.form.get('map_path')
                    _map.maptype = int(request.form.get('map_type'))
                    _map.tileserver = request.form.get('map_tileserver')
                    _map.default = request.form.get('map_default')
                else:  # add map
                    _map = Map(request.form.get('map_name'), request.form.get('map_path'), int(request.form.get('map_type')), request.form.get('map_tileserver'), int(request.form.get('map_default')))
                    db.session.add(_map)
                db.session.commit()

            elif request.form.get('action') == 'createmap':  # add map
                params.update({'map': Map('', '', 0, '', 0), 'tilebase': current_app.config.get('PATH_TILES'), 'settings': Settings})
                return render_template('admin.map_actions.html', **params)

            elif request.form.get('action').startswith('detailmap_'):  # edit map
                params.update({'map': Map.getMaps(request.form.get('action').split('_')[-1]), 'settings': Settings, 'tilebase': current_app.config.get('PATH_TILES'), 'tiles': '\', \''.join(Settings.getMapTiles(int(request.form.get('action').split('_')[-1])))})
                return render_template('admin.map_actions.html', **params)

            elif request.form.get('action').startswith('deletemap_'):  # delete map
                db.session.delete(Map.getMaps(int(request.form.get('action').split('_')[-1])))
                db.session.commit()

            elif request.form.get('action') == 'ordersetting':  # change map order
                maps = []
                for _id in request.form.getlist('mapids'):
                    _map = Map.getMaps(int(_id))
                    maps.append(dict(name=_map.__dict__['name'], path=_map.__dict__['path'], maptype=_map.__dict__['maptype'], tileserver=_map.__dict__['tileserver'], default=_map.__dict__['default']))
                Map.query.delete()  # delete all maps
                for _map in maps:  # add maps in new order
                    db.session.add(Map(_map['name'], _map['path'], _map['maptype'], _map['tileserver'], _map['default']))
                db.session.commit()

    params.update({'maps': Map.getMaps()})
    return render_template('admin.map.html', **params)
コード例 #11
0
def getAdminData(self, **params):
    """
    Deliver admin content of module maps (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'checkpath':
        if os.path.exists(request.args.get('path')):
            return '1'
        return '0'

    elif request.args.get('action') == 'loadmap':  # load tiles

        tile_path = request.args.get('path')

        def calcSubItems((pos)):
            return [(2 * int(pos[0]), 2 * int(pos[1])),
                    (2 * int(pos[0]) + 1, 2 * int(pos[1])),
                    (2 * int(pos[0]), 2 * int(pos[1]) + 1),
                    (2 * int(pos[0]) + 1, 2 * int(pos[1]) + 1)]

        #def getTile(zoom, pos):
        #    global tile_path
        #    response = urllib2.urlopen('http://a.tile.openstreetmap.org/%s/%s/%s.png' % (zoom, pos[0], pos[1]))
        #    #fout = open(tile_path + str(zoom)+'/'+str(pos[0])+'-'+str(pos[1])+'.png', 'wb')
        #    fout = open("%s%s/%s-%s.png" % (tile_path, zoom, pos[0], pos[1]), 'wb')
        #    fout.write(response.read())
        #    fout.close()

        _items = {12: [], 13: [], 14: [], 15: [], 16: [], 17: [], 18: []}
        for t in request.args.get('tiles').split("-"):
            if t != '':
                _items[12].append(t.split(","))

        for zoom in range(13, 19):
            for i in _items[zoom - 1]:
                _items[zoom] += calcSubItems(i)

        result = map_utils.loadTiles(
            '%s%s' %
            (current_app.config.get('PATH_TILES'), request.args.get('path')),
            _items)
        if result == 0:
            return babel.gettext(
                'settings.map.loadinginprogress')  # loading still active
        elif result == 1:
            return babel.gettext(
                'settings.map.loadingstarted')  # loading started
        return ""

    elif request.args.get('action') == 'stoptileload':  # stop tile download
        for i in map_utils.LOADTILES:
            signal.send('map', 'tiledownloaddone', tiles=i)
        map_utils.LOADTILES = []
        map_utils.CURRENTLOADING = []
        return {}

    elif request.args.get('action') == 'maptiles':
        _map = Map.getMaps(id=request.args.get('id'))
        if _map:
            return Map.getMapBox(tilepath=current_app.config.get('PATH_TILES'),
                                 mappath=_map.path)
        return Map.getMapBox()

    elif request.args.get(
            'action') == 'loadosmdata':  # load all data from openstreetmap
        from emonitor.extensions import scheduler
        from emonitor.lib.osm.loaddata import parseOsmData
        #import time, datetime
        mapdata = Map.getMaps()[0].getMapBox(
            tilepath=current_app.config.get('PATH_TILES'))

        lat = [mapdata['min_latdeg']]
        while lat[-1] + .05 < mapdata['max_latdeg']:
            lat.append(lat[-1] + .05)
        lat.append(mapdata['max_latdeg'])

        lng = [mapdata['min_lngdeg']]
        while lng[-1] + .05 < mapdata['max_lngdeg']:
            lng.append(lng[-1] + .05)
        lng.append(mapdata['max_lngdeg'])

        scheduler.add_job(parseOsmData,
                          kwargs={
                              'lat': lat,
                              'lng': lng,
                              'path': current_app.config.get('PATH_DATA')
                          })
        return {'job': 'started'}

    elif request.args.get(
            'action') == 'findcity':  # search citystring and deliver position
        return map_utils.loadPositionOfCity(request.args.get('cityname'))

    return ""
コード例 #12
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module maps

    :param params: use given parameters of request
    :return: rendered template as string
    """
    module = request.view_args['module'].split('/')

    if len(module) > 1:
        if module[1] == 'position':
            if request.method == 'POST':
                if request.form.get(
                        'action'
                ) == 'saveposition':  # safe default map position and home position
                    Settings.set('defaultLat',
                                 request.form.get('default_lat', ''))
                    Settings.set('defaultLng',
                                 request.form.get('default_lng', ''))
                    Settings.set('defaultZoom',
                                 request.form.get('default_zoom', ''))

                    Settings.set('homeLat', request.form.get('home_lat', ''))
                    Settings.set('homeLng', request.form.get('home_lng', ''))

                    db.session.commit()

            params.update({'settings': Settings})
            return render_template('admin.map.position.html', **params)

    else:
        if request.method == 'POST':
            if request.form.get('action') == 'savemap':  # save map
                if request.form.get('map_id') != 'None':  # update
                    _map = Map.getMaps(request.form.get('map_id'))
                    _map.name = request.form.get('map_name')
                    _map.path = request.form.get('map_path')
                    _map.maptype = int(request.form.get('map_type'))
                    _map.tileserver = request.form.get('map_tileserver')
                    _map.default = request.form.get('map_default')
                else:  # add map
                    _map = Map(request.form.get('map_name'),
                               request.form.get('map_path'),
                               int(request.form.get('map_type')),
                               request.form.get('map_tileserver'),
                               int(request.form.get('map_default')))
                    db.session.add(_map)
                db.session.commit()

            elif request.form.get('action') == 'createmap':  # add map
                params.update({
                    'map': Map('', '', 0, '', 0),
                    'tilebase': current_app.config.get('PATH_TILES'),
                    'settings': Settings
                })
                return render_template('admin.map_actions.html', **params)

            elif request.form.get('action').startswith(
                    'detailmap_'):  # edit map
                params.update({
                    'map':
                    Map.getMaps(request.form.get('action').split('_')[-1]),
                    'settings':
                    Settings,
                    'tilebase':
                    current_app.config.get('PATH_TILES'),
                    'tiles':
                    '\', \''.join(
                        Settings.getMapTiles(
                            int(request.form.get('action').split('_')[-1])))
                })
                return render_template('admin.map_actions.html', **params)

            elif request.form.get('action').startswith(
                    'deletemap_'):  # delete map
                db.session.delete(
                    Map.getMaps(int(
                        request.form.get('action').split('_')[-1])))
                db.session.commit()

            elif request.form.get(
                    'action') == 'ordersetting':  # change map order
                maps = []
                for _id in request.form.getlist('mapids'):
                    _map = Map.getMaps(int(_id))
                    maps.append(
                        dict(name=_map.__dict__['name'],
                             path=_map.__dict__['path'],
                             maptype=_map.__dict__['maptype'],
                             tileserver=_map.__dict__['tileserver'],
                             default=_map.__dict__['default']))
                Map.query.delete()  # delete all maps
                for _map in maps:  # add maps in new order
                    db.session.add(
                        Map(_map['name'], _map['path'], _map['maptype'],
                            _map['tileserver'], _map['default']))
                db.session.commit()

    params.update({'maps': Map.getMaps()})
    return render_template('admin.map.html', **params)
コード例 #13
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module streets

    :param params: use given parameters of request
    :return: rendered template as string
    """
    module = request.view_args['module'].split('/')
    if len(module) < 2:
        if City.getDefaultCity():
            module.append(u'{}'.format(City.getDefaultCity().id))
        else:
            module.append(u'1')

    if len(module) == 2:  # cities
        if module[1] == '0':  # city list

            if request.method == 'POST':

                if request.form.get('action').startswith('detailcity_'):  # edit city
                    params.update({'city': City.getCities(id=request.form.get('action').split('_')[-1]), 'departments': Department.getDepartments(), 'maps': Map.getMaps()})
                    return render_template('admin.streets.city_edit.html', **params)

                elif request.form.get('action') == 'updatecity':  # update existing city
                    if request.form.get('city_id') != 'None':  # update city
                        city = City.getCities(id=request.form.get('city_id'))
                        city.name = request.form.get('cityname')
                        city.subcity = request.form.get('subcity')
                        city.dept = request.form.get('department')
                        city.mapname = request.form.get('citymap')
                        city.color = request.form.get('colorname')
                        city.default = request.form.get('citydefault')
                        city.osmid = request.form.get('osmid')
                        city.osmname = request.form.get('osmname')

                    else:  # add city
                        city = City(request.form.get('cityname'), request.form.get('department'),
                                    request.form.get('citymap'), request.form.get('citydefault'),
                                    request.form.get('subcity'), request.form.get('colorname'),
                                    request.form.get('osmid'), request.form.get('osmname'))
                        db.session.add(city)

                    db.session.commit()
                    cache.clear()

                elif request.form.get('action') == 'createcity':  # add city
                    params.update({'city': City('', '', '', '', '', '', 0, ''), 'departments': Department.getDepartments(), 'maps': Map.getMaps()})
                    return render_template('admin.streets.city_edit.html', **params)

                elif request.form.get('action').startswith('deletecity_'):  # delete city
                    db.session.delete(City.getCities(id=request.form.get('action').split('_')[-1]))
                    db.session.commit()
                self.updateAdminSubNavigation()
                cache.clear()

            params.update({'cities': City.getCities()})
            return render_template('admin.streets.city_list.html', **params)

        else:  # show city details
            if request.method == 'POST':
                if request.form.get('action').startswith('detailstreet_'):  # edit street
                    tileserver = {'lat': Settings.get('defaultLat'),
                                  'lng': Settings.get('defaultLng'),
                                  'zoom': Settings.get('defaultZoom'),
                                  'map': Map.getDefaultMap()}
                    params.update({'street': Street.getStreets(id=request.form.get('action').split('_')[-1]), 'cities': City.getCities(), 'maps': Map.getMaps(), 'tileserver': tileserver})
                    return render_template('admin.streets_edit.html', **params)

                elif request.form.get('action') == 'createstreet':  # add street
                    tileserver = {'lat': Settings.get('defaultLat'),
                                  'lng': Settings.get('defaultLng'),
                                  'zoom': Settings.get('defaultZoom'),
                                  'map': Map.getDefaultMap()}

                    params.update({'street': Street('', '', int(module[1]), '', '', '', '', '', ''), 'cities': City.getCities(), 'maps': Map.getMaps(), 'tileserver': tileserver})
                    return render_template('admin.streets_edit.html', **params)

                elif request.form.get('action').startswith('deletestreets_'):  # delete street
                    db.session.delete(Street.getStreets(id=request.form.get('action').split('_')[-1]))
                    db.session.commit()
                    cache.clear()

                elif request.form.get('action', '').startswith('deleteallsteets_'):
                    print "delete all streets of", request.form.get('action').split('_')[-1]
                    for s in Street.getStreets(cityid=request.form.get('action').split('_')[-1]):
                        db.session.delete(s)
                    db.session.commit()
                    cache.clear()

                elif request.form.get('action') == 'savestreet':  # save street
                    if request.form.get('street_id') != 'None':  # update existing street
                        street = Street.getStreets(id=request.form.get('street_id'))
                        street.name = request.form.get('edit_name')
                        street.navigation = request.form.get('edit_navigation')
                        c = request.form.get('edit_cityid').split('_')
                        if len(c) < 2:
                            c.append('')
                        street.cityid = c[0]
                        street.subcity = c[1]
                        street.lat = request.form.get('edit_lat')
                        street.lng = request.form.get('edit_lng')
                        street.zoom = request.form.get('edit_zoom')
                        street.active = request.form.get('edit_active')
                        db.session.commit()
                        #cache.delete_memoized(City.streets)

                    else:  # add street
                        c = request.form.get('edit_cityid').split('_')
                        if len(c) < 2:
                            c.append('')  # subcity
                        city = [ct for ct in City.getCities() if str(ct.id) == c[0]][0]
                        city.addStreet(Street(request.form.get('edit_name'), request.form.get('edit_navigation'), int(c[0]), c[1], request.form.get('edit_lat'), request.form.get('edit_lng'), request.form.get('edit_zoom'), request.form.get('edit_active'), 0))
                        db.session.commit()
                    cache.clear()

            try:
                streets = Street.getStreets(cityid=module[-1])
            except AttributeError:
                streets = []
            chars = {}
            for s in streets:
                chars[s.name[0].upper()] = 0
            params.update({'streets': streets, 'chars': sorted(chars.keys()), 'city': City.getCities(id=module[-1])})
            return render_template('admin.streets.html', **params)

    return "streets"