Esempio n. 1
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)
Esempio n. 2
0
    def getMap():
        """
        Returns default map defined in eMonitor

        :return: :py:class:`emonitor.modules.maps.map.Map`
        """
        return Map.getDefaultMap()
Esempio n. 3
0
    def action(**kwargs):
        """
        implementation of map-message specific actions
        :param kwargs: list of parameters: action, mid and all arguments of ajax requests
        :return: results of action
        """
        if kwargs.get('action') == 'render':
            """
            render string with restructured text engine
            """
            return getreStructuredText(kwargs.get('text'))

        elif kwargs.get('action') == 'mapconfig':
            """
            open overlay map with config values
            """
            try:
                config = json.loads(kwargs.get('config', ''))
            except ValueError:
                config = {}
            if not config.get('lat'):
                config['lat'] = Settings.get('defaultLat')
            if not config.get('lng'):
                config['lng'] = Settings.get('defaultLng')
            config['map'] = Map.getDefaultMap()
            kwargs.update(**config)
            #print ">>>>>", kwargs
            return render_template("frontend.messages_map.html", **kwargs)
        return ""
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)
Esempio n. 5
0
    def action(**kwargs):
        """
        implementation of map-message specific actions
        :param kwargs: list of parameters: action, mid and all arguments of ajax requests
        :return: results of action
        """
        if kwargs.get('action') == 'render':
            """
            render string with restructured text engine
            """
            return getreStructuredText(kwargs.get('text'))

        elif kwargs.get('action') == 'mapconfig':
            """
            open overlay map with config values
            """
            try:
                config = json.loads(kwargs.get('config', ''))
            except ValueError:
                config = {}
            if not config.get('lat'):
                config['lat'] = Settings.get('defaultLat')
            if not config.get('lng'):
                config['lng'] = Settings.get('defaultLng')
            config['map'] = Map.getDefaultMap()
            kwargs.update(**config)
            #print ">>>>>", kwargs
            return render_template("frontend.messages_map.html", **kwargs)
        return ""
Esempio n. 6
0
    def getMap():
        """
        Returns default map defined in eMonitor

        :return: :py:class:`emonitor.modules.maps.map.Map`
        """
        return Map.getDefaultMap()
def getFrontendData(self):
    """
    Deliver frontend content of module streets (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'streetcoords':  # get map parameter for given streetid

        if request.args.get('id') not in ['', 'None']:
            street = Street.getStreets(id=request.args.get('id'))
            return {'lat': street.lat, 'lng': street.lng, 'zoom': street.zoom, 'way': street.navigation,
                    'cityid': street.cityid, 'cityname': street.city.name}

    elif request.args.get('action') == 'housecoords':  # deliver center of housenumbers
        if request.args.get('streetid') != '' and request.args.get('housenumber') != '':
            street = Street.getStreet(id=request.args.get('streetid'))
            hnumber = street.getHouseNumber(number=request.args.get('housenumber').split()[0])
            if hnumber:
                return hnumber.getPosition(0)

            return {'lat': street.lat, 'lng': street.lng}
        return {}

    elif request.args.get('action') == 'defaultposition':

        return {'defaultlat': float(Settings.get('defaultLat')),
                'defaultlng': float(Settings.get('defaultLng')),
                'defaultzoom': int(Settings.get('defaultZoom'))}

    elif request.args.get('action') == 'alarmposition':
        alarm = Alarm.getAlarms(id=request.args.get('alarmid'))
        if alarm:
            return {'id': request.args.get('alarmid'), 'alarmlat': alarm.lat, 'alarmlng': alarm.lng,
                    'alarmzoom': alarm.zoom, 'marker': alarm.marker, 'alarmprio': alarm.priority,
                    'alarmstreet': alarm.street.name, 'alarmstreetno': alarm.get('streetno'),
                    'alarmstreet2': alarm.get('address2'), 'alarmcity': alarm.city.name,
                    'alarmsubcity': alarm.street.subcity}
        else:
            return {'id': '0'}

    elif request.args.get('action') == 'streetslookup':
        streets = {}
        cities = {}
        for c in City.getCities():
            cities[c.id] = c.name
            for k, street in c.streets.iteritems():
                if street.active:
                    try:
                        streets[str(street.id)] = '%s (%s)' % (street.name, c.name)
                    except:
                        streets[str(street.id)] = '%s (-%s-)' % (street.name, street.cityid)
        return streets

    elif request.args.get('action') == 'defaultmap':
        dmap = Map.getDefaultMap()
        return {'tileserver': dmap.tileserver, 'name': dmap.name}

    return ""
Esempio n. 8
0
 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
Esempio n. 9
0
 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
Esempio n. 10
0
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"
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
Esempio n. 12
0
    def addParameters(self, **kwargs):
        """
        Add special parameters for map widget *messages.map.\**
        :param kwargs: list of parameters for update
        """
        if 'message' in kwargs:
            text = kwargs['message'].get('text')
            template = kwargs['message'].get('template')  # todo: define templates
            mapconfig = kwargs['message'].get('mapconfig')
            map = Map.getDefaultMap()
        else:
            text = ""
            template = ""  # todo define templates
            mapconfig = ""
            map = None

        kwargs.update({'map': map, 'text': text, 'mapconfig': mapconfig, 'template': template})
        self.params = kwargs
Esempio n. 13
0
    def addParameters(self, **kwargs):
        """
        Add special parameters for map widget *messages.map.\**
        :param kwargs: list of parameters for update
        """
        if 'message' in kwargs:
            text = kwargs['message'].get('text')
            template = kwargs['message'].get('template')  # todo: define templates
            mapconfig = kwargs['message'].get('mapconfig')
            map = Map.getDefaultMap()
        else:
            text = ""
            template = ""  # todo define templates
            mapconfig = ""
            map = None

        kwargs.update({'map': map, 'text': text, 'mapconfig': mapconfig, 'template': template})
        self.params = kwargs
Esempio n. 14
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
Esempio n. 15
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 ""
def loadStreetsFromOsm(city=None, format="html"):
    """
    Load all Streets from OpenStreetMap

    :param optional city: :py:class:`emonitor.modules.streets.city.City`
    :param optional format: return format, *html*=rendered template, streets as OrderedDict
    :return: rendered template or dict
    """
    global URL

    if not city:
        city = City.getDefaultCity()

    map_details = Map.getDefaultMap().getMapBox(tilepath=current_app.config.get("PATH_TILES"))

    SEARCHSTRING = 'area[name~"%s"];way(%s,%s,%s,%s)(area)[highway][name];(._;>;);out;' % (
        city.name,
        map_details["min_latdeg"],
        map_details["min_lngdeg"],
        map_details["max_latdeg"],
        map_details["max_lngdeg"],
    )  # search all streets for given city
    r = requests.post(URL, data={"data": SEARCHSTRING})
    xmldoc = minidom.parseString(r.content)
    nodes = xmldoc.getElementsByTagName("node")
    ways = xmldoc.getElementsByTagName("way")

    dbosmids = [int(s.osmid or 0) for s in city.getCities()]

    streets = OrderedDict()
    n = {}

    for node in nodes:
        n[int(node.attributes["id"].value)] = (float(node.attributes["lat"].value), float(node.attributes["lon"].value))

    for way in ways:
        nds = []
        osmids = []
        name = ""
        for tag in way.childNodes:

            if tag.nodeName == "tag" and tag.attributes["k"].value == "name":
                name = tag.attributes["v"].value
                osmids.append(int(way.attributes["id"].value))

            if tag.nodeName == "nd":
                _nid = int(tag.attributes["ref"].value)
                if _nid in n.keys():
                    nds.append(n[_nid])

        if name not in streets.keys():
            streets[name] = {"osmids": osmids, "nodes": nds, "indb": False}
        else:
            streets[name]["osmids"].extend(osmids)
            streets[name]["nodes"].extend(nds)

        if len(set(osmids).intersection(set(dbosmids))) > 0:
            streets[name]["indb"] = True

    streets = OrderedDict(sorted(streets.items(), key=lambda t: t[0]))
    if format == "html":  # html output
        return render_template("admin.streets_osm.html", streets=streets, city=city)
    else:  # data output
        for name in streets:
            points = streets[name]["nodes"]
            if len(points) > 2:
                cent = centroid_of_polygon(points)
                streets[name]["center"] = cent
            elif len(points) == 2:
                streets[name]["center"] = (((points[0][0] + points[1][0]) / 2), ((points[0][1] + points[1][1]) / 2))
            else:
                streets[name]["center"] = (0.0, 0.0)
        return streets
Esempio n. 17
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') == '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"
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 ""
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)
Esempio n. 20
0
 def fixDefinition(self, id):
     if id == 1:  # add default values
         if Map.query.count() == 0:  # add default map
             db.session.add(Map('Bing (online)', '', maptype=2, tileserver="//ak.t2.tiles.virtualearth.net/tiles/a{q}?g=1236", default=1))
             db.session.commit()
Esempio n. 21
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)
Esempio n. 22
0
def getFrontendData(self):
    """
    Deliver frontend content of module streets (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get(
            'action'
    ) == 'streetcoords':  # get map parameter for given streetid

        if request.args.get('id') not in ['', 'None']:
            street = Street.getStreets(id=request.args.get('id'))
            return {
                'lat': street.lat,
                'lng': street.lng,
                'zoom': street.zoom,
                'way': street.navigation,
                'cityid': street.cityid,
                'cityname': street.city.name
            }

    elif request.args.get(
            'action') == 'housecoords':  # deliver center of housenumbers
        if request.args.get('streetid') != '' and request.args.get(
                'housenumber') != '':
            street = Street.getStreet(id=request.args.get('streetid'))
            hnumber = street.getHouseNumber(
                number=request.args.get('housenumber').split()[0])
            if hnumber:
                return hnumber.getPosition(0)

            return {'lat': street.lat, 'lng': street.lng}
        return {}

    elif request.args.get('action') == 'defaultposition':

        return {
            'defaultlat': float(Settings.get('defaultLat')),
            'defaultlng': float(Settings.get('defaultLng')),
            'defaultzoom': int(Settings.get('defaultZoom'))
        }

    elif request.args.get('action') == 'alarmposition':
        alarm = Alarm.getAlarms(id=request.args.get('alarmid'))
        if alarm:
            return {
                'id': request.args.get('alarmid'),
                'alarmlat': alarm.lat,
                'alarmlng': alarm.lng,
                'alarmzoom': alarm.zoom,
                'marker': alarm.marker,
                'alarmprio': alarm.priority,
                'alarmstreet': alarm.street.name,
                'alarmstreetno': alarm.get('streetno'),
                'alarmstreet2': alarm.get('address2'),
                'alarmcity': alarm.city.name,
                'alarmsubcity': alarm.street.subcity
            }
        else:
            return {'id': '0'}

    elif request.args.get('action') == 'streetslookup':
        streets = {}
        cities = {}
        for c in City.getCities():
            cities[c.id] = c.name
            for k, street in c.streets.iteritems():
                if street.active:
                    try:
                        streets[str(
                            street.id)] = '%s (%s)' % (street.name, c.name)
                    except:
                        streets[str(street.id)] = '%s (-%s-)' % (street.name,
                                                                 street.cityid)
        return streets

    elif request.args.get('action') == 'defaultmap':
        dmap = Map.getDefaultMap()
        return {'tileserver': dmap.tileserver, 'name': dmap.name}

    return ""
Esempio n. 23
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"
Esempio n. 24
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module alarmobjects

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

    def chunks(l, n):
        return [l[i:i + n] for i in range(0, len(l), n)]

    if len(module) > 1:  # type definition
        if module[1] == 'types':
            if request.method == 'POST':
                if request.form.get(
                        'action') == 'createalarmobjecttype':  # add type
                    params.update({'alarmobjecttype': AlarmObjectType('', '')})
                    return render_template(
                        'admin.alarmobjects.types_action.html', **params)

                elif request.form.get(
                        'action') == 'savealarmobjecttype':  # save type
                    if request.form.get(
                            'alarmobjecttype_id') == 'None':  # add new type
                        alarmobjecttype = AlarmObjectType('', '')
                        db.session.add(alarmobjecttype)
                    else:  # update existing
                        alarmobjecttype = AlarmObjectType.getAlarmObjectTypes(
                            id=int(request.form.get('alarmobjecttype_id')))
                    alarmobjecttype.name = request.form.get(
                        'alarmobjecttype_name')
                    alarmobjecttype.remark = request.form.get(
                        'alarmobjecttype_remark')
                    db.session.commit()

                elif request.form.get('action').startswith(
                        'detailobjecttype'):  # edit type
                    alarmobjecttype = AlarmObjectType.getAlarmObjectTypes(
                        id=int(request.form.get('action').split('_')[-1]))
                    params.update({'alarmobjecttype': alarmobjecttype})
                    return render_template(
                        'admin.alarmobjects.types_action.html', **params)

                elif request.form.get('action').startswith(
                        'deleteobjecttype_'):  # delete type
                    db.session.delete(
                        AlarmObjectType.getAlarmObjectTypes(
                            id=int(request.form.get('action').split('_')[-1])))
                    db.session.commit()

            params.update(
                {'alarmobjecttypes': AlarmObjectType.getAlarmObjectTypes()})
            return render_template('admin.alarmobjects.types.html', **params)

        elif module[1] == 'fields':
            if request.method == 'POST':
                if request.form.get(
                        'action') == 'updatefield':  # update fields
                    Settings.set('alarmobjectfields', [
                        i for i in chunks(request.form.getlist('fieldname'), 2)
                        if i[0] != ''
                    ])
                    db.session.commit()

            params.update({'fields': Settings.get('alarmobjectfields', [])})
            return render_template('admin.alarmobjects.fields.html', **params)

    else:  # base view
        if request.method == 'POST':
            streets = Street.getStreets()
            if request.form.get(
                    'action') == 'createalarmobject':  # add alarmobject
                params.update({
                    'alarmobject':
                    AlarmObject('', 0, '', Settings.get('defaultLat'),
                                Settings.get('defaultLng'),
                                Settings.get('defaultZoom'), '', '', '', 0, 0),
                    'streets':
                    streets,
                    'selectedstreet':
                    '',
                    'map':
                    Map.getDefaultMap(),
                    'alarmobjecttypes':
                    AlarmObjectType.getAlarmObjectTypes()
                })
                return render_template('admin.alarmobjects_actions.html',
                                       **params)

            elif request.form.get('action') == 'savealarmobject':  # save
                if request.form.get('alarmobject_id') == 'None':  # add new
                    alarmobject = AlarmObject('', 0, '', 0, 0, 0, '', '', '',
                                              0, 0)
                    db.session.add(alarmobject)
                else:  # update existing
                    alarmobject = AlarmObject.getAlarmObjects(
                        id=request.form.get('alarmobject_id'))
                alarmobject.name = request.form.get('edit_name')
                alarmobject._streetid = request.form.get('streetid')
                alarmobject._objecttype = int(
                    request.form.get('edit_objecttype'))
                alarmobject.remark = request.form.get('edit_remark')
                if request.form.get('edit_position') == '1':
                    alarmobject.lat = request.form.get('edit_lat')
                    alarmobject.lng = request.form.get('edit_lng')
                    alarmobject.zoom = request.form.get('edit_zoom')
                alarmobject.streetno = request.form.get('edit_streetno')
                alarmobject.alarmplan = request.form.get('edit_alarmplan')
                alarmobject.bma = request.form.get('edit_bma')
                alarmobject.active = int(request.form.get('edit_active', '0'))
                db.session.commit()

            elif request.form.get(
                    'action'
            ) == 'savealarmobjectattributes':  # save attributes
                alarmobject = AlarmObject.getAlarmObjects(
                    id=request.form.get('alarmobject_id'))
                for field in Settings.get('alarmobjectfields',
                                          []):  # store attributes
                    if 'edit_%s' % field[0] in request.form:
                        alarmobject.set(field[0],
                                        request.form.get('edit_%s' % field[0]))
                db.session.commit()

            elif request.form.get(
                    'action') == 'savealarmobjectaao':  # save aao
                alarmobject = AlarmObject.getAlarmObjects(
                    id=request.form.get('alarmobject_id'))
                if alarmobject:
                    alarmobject.set('cars1', [
                        c for c in request.form.get('cars1').split(';')
                        if c != ''
                    ])
                    alarmobject.set('cars2', [
                        c for c in request.form.get('cars2').split(';')
                        if c != ''
                    ])
                    alarmobject.set('material', [
                        c for c in request.form.get('material').split(';')
                        if c != ''
                    ])
                    db.session.commit()

            elif request.form.get('action').startswith(
                    'editalarmobject_'):  # edit alarmobject
                alarmobject = AlarmObject.getAlarmObjects(
                    id=int(request.form.get('action').split('_')[-1]))
                params.update({
                    'alarmobject':
                    alarmobject,
                    'streets':
                    streets,
                    'selectedstreet':
                    '%s (%s)' %
                    (alarmobject.street.name, alarmobject.street.city.name),
                    'map':
                    Map.getDefaultMap(),
                    'alarmobjecttypes':
                    AlarmObjectType.getAlarmObjectTypes(),
                    'fields':
                    Settings.get('alarmobjectfields', []),
                    'cars':
                    Car.getCars(deptid=Department.getDefaultDepartment().id)
                })
                return render_template('admin.alarmobjects_actions.html',
                                       **params)

            elif request.form.get('action').startswith(
                    'deletealarmobject_'):  # delete alarmobject
                db.session.delete(
                    AlarmObject.getAlarmObjects(
                        id=int(request.form.get('action').split('_')[-1])))
                db.session.commit()

        params.update({
            'alarmobjects': AlarmObject.getAlarmObjects(active=0),
            'alarmobjecttypes': AlarmObjectType.getAlarmObjectTypes()
        })
        return render_template('admin.alarmobjects.html', **params)
def getAdminContent(self, **params):
    """
    Deliver admin content of module alarmobjects

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

    def chunks(l, n):
        return [l[i:i + n] for i in range(0, len(l), n)]

    if len(module) > 1:  # type definition
        if module[1] == 'types':
            if request.method == 'POST':
                if request.form.get('action') == 'createalarmobjecttype':  # add type
                    params.update({'alarmobjecttype': AlarmObjectType('', '')})
                    return render_template('admin.alarmobjects.types_action.html', **params)

                elif request.form.get('action') == 'savealarmobjecttype':  # save type
                    if request.form.get('alarmobjecttype_id') == 'None':  # add new type
                        alarmobjecttype = AlarmObjectType('', '')
                        db.session.add(alarmobjecttype)
                    else:  # update existing
                        alarmobjecttype = AlarmObjectType.getAlarmObjectTypes(id=int(request.form.get('alarmobjecttype_id')))
                    alarmobjecttype.name = request.form.get('alarmobjecttype_name')
                    alarmobjecttype.remark = request.form.get('alarmobjecttype_remark')
                    db.session.commit()

                elif request.form.get('action').startswith('detailobjecttype'):  # edit type
                    alarmobjecttype = AlarmObjectType.getAlarmObjectTypes(id=int(request.form.get('action').split('_')[-1]))
                    params.update({'alarmobjecttype': alarmobjecttype})
                    return render_template('admin.alarmobjects.types_action.html', **params)

                elif request.form.get('action').startswith('deleteobjecttype_'):  # delete type
                    db.session.delete(AlarmObjectType.getAlarmObjectTypes(id=int(request.form.get('action').split('_')[-1])))
                    db.session.commit()

            params.update({'alarmobjecttypes': AlarmObjectType.getAlarmObjectTypes()})
            return render_template('admin.alarmobjects.types.html', **params)

        elif module[1] == 'fields':
            if request.method == 'POST':
                if request.form.get('action') == 'updatefield':  # update fields
                    Settings.set('alarmobjectfields', [i for i in chunks(request.form.getlist('fieldname'), 2) if i[0] != ''])
                    db.session.commit()

            params.update({'fields': Settings.get('alarmobjectfields', [])})
            return render_template('admin.alarmobjects.fields.html', **params)

    else:  # base view
        if request.method == 'POST':
            streets = Street.getStreets()
            if request.form.get('action') == 'createalarmobject':  # add alarmobject
                params.update({'alarmobject': AlarmObject('', 0, '', Settings.get('defaultLat'), Settings.get('defaultLng'), Settings.get('defaultZoom'), '', '', '', 0, 0), 'streets': streets, 'selectedstreet': '', 'map': Map.getDefaultMap(), 'alarmobjecttypes': AlarmObjectType.getAlarmObjectTypes()})
                return render_template('admin.alarmobjects_actions.html', **params)

            elif request.form.get('action') == 'savealarmobject':  # save
                if request.form.get('alarmobject_id') == 'None':  # add new
                    alarmobject = AlarmObject('', 0, '', 0, 0, 0, '', '', '', 0, 0)
                    db.session.add(alarmobject)
                else:  # update existing
                    alarmobject = AlarmObject.getAlarmObjects(id=request.form.get('alarmobject_id'))
                alarmobject.name = request.form.get('edit_name')
                alarmobject._streetid = request.form.get('streetid')
                alarmobject._objecttype = int(request.form.get('edit_objecttype'))
                alarmobject.remark = request.form.get('edit_remark')
                if request.form.get('edit_position') == '1':
                    alarmobject.lat = request.form.get('edit_lat')
                    alarmobject.lng = request.form.get('edit_lng')
                    alarmobject.zoom = request.form.get('edit_zoom')
                alarmobject.streetno = request.form.get('edit_streetno')
                alarmobject.alarmplan = request.form.get('edit_alarmplan')
                alarmobject.bma = request.form.get('edit_bma')
                alarmobject.active = int(request.form.get('edit_active', '0'))
                db.session.commit()

            elif request.form.get('action') == 'savealarmobjectattributes':  # save attributes
                alarmobject = AlarmObject.getAlarmObjects(id=request.form.get('alarmobject_id'))
                for field in Settings.get('alarmobjectfields', []):  # store attributes
                    if 'edit_%s' % field[0] in request.form:
                        alarmobject.set(field[0], request.form.get('edit_%s' % field[0]))
                db.session.commit()

            elif request.form.get('action') == 'savealarmobjectaao':  # save aao
                alarmobject = AlarmObject.getAlarmObjects(id=request.form.get('alarmobject_id'))
                if alarmobject:
                    alarmobject.set('cars1', [c for c in request.form.get('cars1').split(';') if c != ''])
                    alarmobject.set('cars2', [c for c in request.form.get('cars2').split(';') if c != ''])
                    alarmobject.set('material', [c for c in request.form.get('material').split(';') if c != ''])
                    db.session.commit()

            elif request.form.get('action').startswith('editalarmobject_'):  # edit alarmobject
                alarmobject = AlarmObject.getAlarmObjects(id=int(request.form.get('action').split('_')[-1]))
                params.update({'alarmobject': alarmobject, 'streets': streets, 'selectedstreet': '%s (%s)' % (alarmobject.street.name, alarmobject.street.city.name), 'map': Map.getDefaultMap(), 'alarmobjecttypes': AlarmObjectType.getAlarmObjectTypes(), 'fields': Settings.get('alarmobjectfields', []), 'cars': Car.getCars(deptid=Department.getDefaultDepartment().id)})
                return render_template('admin.alarmobjects_actions.html', **params)

            elif request.form.get('action').startswith('deletealarmobject_'):  # delete alarmobject
                db.session.delete(AlarmObject.getAlarmObjects(id=int(request.form.get('action').split('_')[-1])))
                db.session.commit()

        params.update({'alarmobjects': AlarmObject.getAlarmObjects(active=0), 'alarmobjecttypes': AlarmObjectType.getAlarmObjectTypes()})
        return render_template('admin.alarmobjects.html', **params)