Esempio n. 1
0
def set_geometria(obj):
    gd = obj.row_dict['Geometria']
    point = gd.get('Ponto')
    point_as_area = gd.get('Ponto como área')
    from_kml = gd.get(
        'Identificador do polígono (KML)') if obj.kml_dicts else None

    num_geometries = len([v for v in [point, point_as_area, from_kml] if v])
    if num_geometries == 0:
        return  # nothing to do!
    if num_geometries > 1:
        msg = 'Mais de uma geometria definida. Defina somente a coluna "Ponto",'\
              'ou "Ponto como Área", ou "Identificador do polígono (KML)"'
        obj.errors.append(msg)

    geodict = {'type': 'GeometryCollection', 'geometries': []}

    try:
        if point:
            # FIXME: correct order is lat, lng. Before fixing must adjust the
            #        both in DB and in the map.
            lng, lat = point.split(',')
            lat, lng = float(lat), float(lng)
            coords = [[lat, lng]]
            geodict['geometries'] = [{
                'type': 'MultiPoint',
                'coordinates': coords
            }]
        elif point_as_area:
            dt = 0.0005
            lat, lng = point_as_area.split(',')
            lat, lng = float(lat), float(lng)
            # FIXME: correct order is lat, lng. Before fixing must adjust the
            #        both in DB and in the map.
            aux = lng
            lng = lat
            lat = aux
            coords = [[[lat + dt, lng + dt], [lat + dt, lng - dt],
                       [lat - dt, lng - dt], [lat - dt, lng + dt],
                       [lat + dt, lng + dt]]]  # closes polygon
            geodict['geometries'] = [{
                'type': 'Polygon',
                'coordinates': coords
            }]
        elif from_kml:  # Polygon or MultiLineString
            found = False
            for kd in obj.kml_dicts:
                if from_kml == kd['Identificador do polígono']:
                    found = True
                    if 'type' in kd['Geometria'] and \
                    kd['Geometria']['type'] == 'GeometryCollection':
                        if kd['Geometria']['geometries'][0][
                                'type'] == 'LineString':
                            # we got geometry collection with some linestrings
                            # lets crate a `MultiLineString` geometry
                            coords = [geom['coordinates'] \
                                        for geom in kd['Geometria']['geometries']]
                            geodict['geometries'] = [{
                                'type': 'MultiLineString',
                                'coordinates':
                                coords  # put many linestrings together
                            }]
                        else:
                            # if we dont got linestrings, assume that this is a polygon
                            coords = [geom['coordinates'][0] \
                                        for geom in kd['Geometria']['geometries']]
                            geodict['geometries'] = [{
                                'type': 'Polygon',
                                'coordinates':
                                coords  # put many polygons together
                            }]
                    else:  # only 1 polygon
                        geodict['geometries'] = [kd['Geometria']['geometry']]

                    # FIXME: correct order is lat, lng. Before fixing must adjust
                    #        both in DB and in the map.
                    def fixcoords(data):
                        if isinstance(data, list) and isinstance(
                                data[0], float):
                            # swap coords and chomp possible z axis.
                            return [data[1], data[0]]
                        if isinstance(data, list):
                            for i in range(len(data)):
                                data[i] = fixcoords(data[i])
                        if isinstance(data, dict):
                            for k, v in data.items():
                                data[k] = fixcoords(v)
                        return data

                    geodict = fixcoords(geodict)

                    break
            if not found:
                msg = 'Identificador do polígono não encontrado: {}'.format(
                    from_kml)
                obj.errors.append(msg)
                return

        g = GeoRefModel()
        geojson = json.dumps(geodict)
        g.geometry = geojson
        obj.object_dict['geometry'] = geojson
        obj.object_dict[
            'geometry_preview'] = point or point_as_area or from_kml or ''

    except ValueError:
        msg = 'Dado de geometria não é um número válido.'
        obj.errors.append(msg)

    except OGRException as e:
        msg = 'Má formação da(s) coluna(s) de geometria.'
        obj.errors.append(msg)

    except GEOSException as e:
        msg = 'Informação geométrica inconsistente.'
        obj.errors.append(msg)
Esempio n. 2
0
def set_geometria(obj):
    gd = obj.row_dict['Geometria']
    point = gd.get('Ponto')
    point_as_area = gd.get('Ponto como área')
    polygon = gd.get('Identificador do polígono (KML)') if obj.kml_dicts else None

    num_geometries = len([v for v in [point, point_as_area, polygon] if v])
    if num_geometries == 0:
        return  # nothing to do!
    if num_geometries > 1:
        msg = 'Mais de uma geometria definida. Defina somente a coluna "Ponto",'\
              'ou "Ponto como Área", ou "Identificador do polígono (KML)"'
        obj.errors.append(msg)

    geodict = {
        'type': 'GeometryCollection',
        'geometries': []
    }

    try:
        if point:
            # FIXME: correct order is lat, lng. Before fixing must adjust the
            #        both in DB and in the map.
            lng, lat = point.split(',')
            lat, lng = float(lat), float(lng)
            coords = [[lat, lng]]
            geodict['geometries'] = [{
                'type': 'MultiPoint',
                'coordinates': coords
            }]
        elif point_as_area:
            dt = 0.0005
            lat, lng = point_as_area.split(',')
            lat, lng = float(lat), float(lng)
            # FIXME: correct order is lat, lng. Before fixing must adjust the
            #        both in DB and in the map.
            aux = lng
            lng = lat
            lat = aux
            coords = [[[lat+dt, lng+dt], [lat+dt, lng-dt],
                       [lat-dt, lng-dt], [lat-dt, lng+dt],
                       [lat+dt, lng+dt]]]  # closes polygon
            geodict['geometries'] = [{
                'type': 'Polygon',
                'coordinates': coords
            }]
        elif polygon:
            found = False
            for kd in obj.kml_dicts:
                if polygon == kd['Identificador do polígono']:
                    found = True
                    if 'type' in kd['Geometria'] and \
                    kd['Geometria']['type'] == 'GeometryCollection':
                        coords = [geom['coordinates'][0] \
                                    for geom in kd['Geometria']['geometries']]
                        geodict['geometries'] = [{
                            'type': 'Polygon',
                            'coordinates': coords  # put many polygons together
                        }]
                    else:  # only 1 polygon
                        geodict['geometries'] = [kd['Geometria']['geometry']]

                    # FIXME: correct order is lat, lng. Before fixing must adjust
                    #        both in DB and in the map.
                    for geom in geodict['geometries']:
                        for poly in geom['coordinates']:
                            for i in xrange(len(poly)):
                                # iterate by index to edit object in place
                                poly[i] = [poly[i][1], poly[i][0]]
                    break
            if not found:
                msg = 'Identificador do polígono não encontrado: {}'.format(polygon)
                obj.errors.append(msg)
                return
        
        g = GeoRefModel()
        geojson = json.dumps(geodict)
        g.geometry = geojson
        obj.object_dict['geometry'] = geojson
        obj.object_dict['geometry_preview'] = point or point_as_area or polygon or ''
        
        # obj.object_dict['tooltip_map_preview'] = {
        #     'type': 'FeatureCollection',
        #     'features': [{
        #         'type': 'Feature',
        #         'geometry': geodict['geometries'][0],
        #     }],
        # }

    except ValueError:
        msg = 'Dado de geometria não é um número válido.'
        obj.errors.append(msg)

    except OGRException as e:
        msg = 'Má formação da(s) coluna(s) de geometria.'
        obj.errors.append(msg)
Esempio n. 3
0
def set_geometria(obj):
    gd = obj.row_dict['Geometria']
    point = gd.get('Ponto')
    point_as_area = gd.get('Ponto como área')
    from_kml = gd.get('Identificador do polígono (KML)') if obj.kml_dicts else None

    num_geometries = len([v for v in [point, point_as_area, from_kml] if v])
    if num_geometries == 0:
        return  # nothing to do!
    if num_geometries > 1:
        msg = 'Mais de uma geometria definida. Defina somente a coluna "Ponto",'\
              'ou "Ponto como Área", ou "Identificador do polígono (KML)"'
        obj.errors.append(msg)

    geodict = {
        'type': 'GeometryCollection',
        'geometries': []
    }

    try:
        if point:
            # FIXME: correct order is lat, lng. Before fixing must adjust the
            #        both in DB and in the map.
            lng, lat = point.split(',')
            lat, lng = float(lat), float(lng)
            coords = [[lat, lng]]
            geodict['geometries'] = [{
                'type': 'MultiPoint',
                'coordinates': coords
            }]
        elif point_as_area:
            dt = 0.0005
            lat, lng = point_as_area.split(',')
            lat, lng = float(lat), float(lng)
            # FIXME: correct order is lat, lng. Before fixing must adjust the
            #        both in DB and in the map.
            aux = lng
            lng = lat
            lat = aux
            coords = [[[lat+dt, lng+dt], [lat+dt, lng-dt],
                       [lat-dt, lng-dt], [lat-dt, lng+dt],
                       [lat+dt, lng+dt]]]  # closes polygon
            geodict['geometries'] = [{
                'type': 'Polygon',
                'coordinates': coords
            }]
        elif from_kml: # Polygon or MultiLineString
            found = False
            for kd in obj.kml_dicts:
                if from_kml == kd['Identificador do polígono']:
                    found = True
                    if 'type' in kd['Geometria'] and \
                    kd['Geometria']['type'] == 'GeometryCollection':
                        if kd['Geometria']['geometries'][0]['type'] == 'LineString':
                            # we got geometry collection with some linestrings
                            # lets crate a `MultiLineString` geometry
                            coords = [geom['coordinates'] \
                                        for geom in kd['Geometria']['geometries']]
                            geodict['geometries'] = [{
                                'type': 'MultiLineString',
                                'coordinates': coords  # put many linestrings together
                            }]
                        else:
                            # if we dont got linestrings, assume that this is a polygon
                            coords = [geom['coordinates'][0] \
                                        for geom in kd['Geometria']['geometries']]
                            geodict['geometries'] = [{
                                'type': 'Polygon',
                                'coordinates': coords  # put many polygons together
                            }]
                    else:  # only 1 polygon
                        geodict['geometries'] = [kd['Geometria']['geometry']]

                    # FIXME: correct order is lat, lng. Before fixing must adjust
                    #        both in DB and in the map.
                    def fixcoords(data):
                        if isinstance(data, list) and isinstance(data[0], float):
                            # swap coords and chomp possible z axis.
                            return [data[1], data[0]]
                        if isinstance(data, list):
                            for i in range(len(data)):
                                data[i] = fixcoords(data[i])
                        if isinstance(data, dict):
                            for k, v in data.items():
                                data[k] = fixcoords(v)
                        return data

                    geodict = fixcoords(geodict)

                    break
            if not found:
                msg = 'Identificador do polígono não encontrado: {}'.format(from_kml)
                obj.errors.append(msg)
                return

        g = GeoRefModel()
        geojson = json.dumps(geodict)
        g.geometry = geojson
        obj.object_dict['geometry'] = geojson
        obj.object_dict['geometry_preview'] = point or point_as_area or from_kml or ''

    except ValueError:
        msg = 'Dado de geometria não é um número válido.'
        obj.errors.append(msg)

    except OGRException as e:
        msg = 'Má formação da(s) coluna(s) de geometria.'
        obj.errors.append(msg)

    except GEOSException as e:
        msg = 'Informação geométrica inconsistente.'
        obj.errors.append(msg)