예제 #1
0
    def clip_to_cutline(source_file: str, clip_bounds: ogr.Geometry, dest_file: str) -> Optional[np.ndarray]:
        """Clips an image to the specified geometry
        Arguments:
            source_file: the file to clip
            clip_bounds: the geometry to clip the source file
            dest_file: the destination of the clipping
        Returns:
            Returns the destination file pixels upon success and None otherwise
        """
        # Write the clipline to the CSV file
        _, cutline_csv = tempfile.mkstemp(suffix=".csv")
        logging.debug("clip_to_cutline: CSV %s", cutline_csv)
        with open(cutline_csv, 'w', encoding='utf-8') as out_file:
            logging.debug("clip_to_cutline: WKT %s", clip_bounds.ExportToWkt())
            out_file.write('id,WKT\n')
            out_file.write(','.join(['1, "%s"' % clip_bounds.ExportToWkt()]))

        # Clip to the cutline
        cmd = 'gdalwarp -crop_to_cutline -dstalpha -overwrite -cutline %s "%s" "%s"' % (cutline_csv, source_file, dest_file)
        logging.debug("clip_to_cutline: CMD: '%s'", cmd)
        with open(os.devnull, 'wb') as null_out:
            subprocess.call(cmd, shell=True, stdout=null_out)
        out_px = np.array(gdal.Open(dest_file).ReadAsArray())
        if np.count_nonzero(out_px) > 0:
            return out_px

        os.remove(dest_file)
        return None
예제 #2
0
    def find_plots_intersect_boundingbox(bounding_box: ogr.Geometry, all_plots: dict) -> dict:
        """Take a list of plots and return only those overlapping bounding box.
        Arguments:
            bounding_box: the geometry of the bounding box
            all_plots: the dictionary of all available plots
        Return:
            A dictionary of all intersecting plots
        """
        bb_sr = bounding_box.GetSpatialReference()
        intersecting_plots = {}
        logging.debug("[find_plots_intersect_boundingbox] Bounding box %s %s", str(bb_sr), str(bounding_box))

        for plot_name in all_plots:
            current_poly = all_plots[plot_name]

            # Check for a need to convert coordinate systems
            check_poly = current_poly
            if bb_sr:
                poly_sr = current_poly.GetSpatialReference()
                if poly_sr and not bb_sr.IsSame(poly_sr):
                    # We need to convert to the same coordinate system before an intersection
                    check_poly = geometries.convert_geometry(current_poly, bb_sr)

            logging.debug("[find_plots_intersect_boundingbox] Intersection with %s", str(check_poly))
            intersection_with_bounding_box = bounding_box.Intersection(check_poly)

            if intersection_with_bounding_box is not None:
                intersection = json.loads(intersection_with_bounding_box.ExportToJson())
                if 'coordinates' in intersection and len(intersection['coordinates']) > 0:
                    intersecting_plots[str(plot_name)] = current_poly

        return intersecting_plots
예제 #3
0
def geometry_to_geojson(geom: ogr.Geometry,
                        alt_coord_type: str = None,
                        alt_coord_code: str = None) -> str:
    """Converts a geometry to geojson.
    Args:
        geom: The geometry to convert to JSON
        alt_coord_type: the alternate geographic coordinate system type if geometry doesn't have one defined
        alt_coord_code: the alternate geographic coordinate system associated with the type
    Returns:
        The geojson string for the geometry
    Note:
        If the geometry doesn't have a spatial reference associated with it, both the default
        coordinate system type and code must be specified for a coordinate system to be assigned to
        the returning JSON. The original geometry is left unaltered.
    """
    ref_sys = geom.GetSpatialReference()
    geom_json = json.loads(geom.ExportToJson())
    if not ref_sys:
        if alt_coord_type and alt_coord_code:
            # No coordinate system, use what was passed in
            geom_json['crs'] = {
                'type': str(alt_coord_type),
                'properties': {
                    'code': str(alt_coord_code)
                }
            }
    else:
        # Use the existing coordinate system to inform the GeoJSON
        geom_json['crs'] = {
            'type': ref_sys.GetAttrValue("AUTHORITY", 0),
            'properties': {
                'code': ref_sys.GetAttrValue("AUTHORITY", 1)
            }
        }
    return json.dumps(geom_json)
예제 #4
0
def Make_Discre_Road_Points(road_geo:ogr.Geometry, 
                           start_points:dict, 
                           seg_length:float):
    '''
    在road_geo上每隔seg_length取一个出发点(魔改版)
    start_point将会是一个元组而不是Startpoint对象
    (离散道路点, 前点, 后点)
    '''

     
    count = road_geo.GetPointCount()
    total_length = road_geo.Length()
    
    '''如果是在递归中seg_length比路的全长还要长,那就把路的最后一个点作为出发点'''
    if seg_length >= total_length:
        start_point_coord = road_geo.GetPoint_2D(count-1)
        point_A_coord = road_geo.GetPoint_2D(count-2)
        point_B_coord = road_geo.GetPoint_2D(count-1)
        start_points[start_point_coord] = (point_A_coord, point_B_coord)
        return 
    
    first_to_current_length = 0
    temp_length = 0
    temp_x1 = None
    temp_y1 = None
    temp_x2 = None
    temp_y2 = None
    
    '''计算当前线段的长度和累计长度'''
    for index in range(count-1):
        temp_x1 = road_geo.GetX(index)              
        temp_y1 = road_geo.GetY(index)  
        temp_x2 = road_geo.GetX(index+1)
        temp_y2 = road_geo.GetY(index+1)
        temp_length = math.sqrt( (temp_x1-temp_x2)**2 + (temp_y1-temp_y2)**2 )
        first_to_current_length = first_to_current_length + temp_length
        if seg_length < first_to_current_length:
            break
    '''这时从第零个点到第index+1个点的距离大于seg_length了'''

    '''算出发点的坐标'''
    len1 = seg_length - (first_to_current_length - temp_length)
    start_point_x = (len1 / temp_length) * (temp_x2 - temp_x1) + temp_x1
    start_point_y = (len1 / temp_length) * (temp_y2 - temp_y1) + temp_y1
    if temp_x1 == 0:
        print([temp_x1, temp_y1])
    start_points[(start_point_x, start_point_y)] = ((temp_x1, temp_y1), (temp_x2, temp_y2))
    
    '''给出发点后面的点做一个线的几何体,用来进行下一个递归'''
    temp_road_geo = ogr.Geometry(ogr.wkbLineString)
    temp_road_geo.AddPoint(start_point_x, start_point_y)
    for i in range(index+1, count):
        temp_x = road_geo.GetX(i)                   
        temp_y = road_geo.GetY(i)        
        temp_road_geo.AddPoint(temp_x, temp_y)
     
    Make_Discre_Road_Points(temp_road_geo, start_points, seg_length)
예제 #5
0
def point_intersects_roi(point: PointData, region_of_interest: ogr.Geometry):
    for i in range(region_of_interest.GetGeometryCount()):
        sub_geom = region_of_interest.GetGeometryRef(i)
        intersects = sub_geom.Intersects(point.geometry)
        if intersects:
            result = True
            break
    else:
        result = False
    return result
예제 #6
0
def get_vertices_for_geom(geom: ogr.Geometry) -> List[List[float]]:
    """
    Gets a list of the vertices for the given geometry.

    :param geom: The geomery from which points are to be extracted.
    :type geom: :py:class:`ogr.Geometry`
    :return: A list of points that compose the geometry.
    :rtype: ``[[int, int]]``
    """
    vertices = []
    geom_name = geom.GetGeometryName()
    if geom_name == 'POINT':
        vertices.append([geom.GetPoint()[0], geom.GetPoint()[1]])
    elif geom_name == 'LINEARRING':
        num_vertices = geom.GetPointCount()
        for i in range(0, geom.GetPointCount()):
            point = geom.GetPoint(i)
            vertices.append([point[0], point[1]])
    else:
        geom_count = geom.GetGeometryCount()
        for i in range(0, geom_count):
            geom_ref = geom.GetGeometryRef(i)
            verts = get_vertices_for_geom(geom_ref)
            vertices.append(verts)

    return vertices
예제 #7
0
def reproject_geom(geom: ogr.Geometry, source_srid: int, target_srid: int) -> ogr.Geometry:
    """
    Reproject the given geometry from one SR to another.

    :param geom: The geometry to reproject.
    :type geom: :py:class:`Geometry`
    :param source_srid: The source SRID (projection the geometry is in currently).
    :type source_srid: ``int``
    :param target_srid: the target SRID.
    :type target_srid: ``int``
    :return: The reprojected geometry.
    :rtype: :py:class:'Geometry'
    """
    # Source spatial reference in which the input geometry is projected
    source = osr.SpatialReference()
    source.ImportFromEPSG(source_srid)

    # Target spatial reference to which we want to project
    target = osr.SpatialReference()
    target.ImportFromEPSG(target_srid)

    # Set up the transform.
    transform = osr.CoordinateTransformation(source, target)

    # transform it
    geom.Transform(transform)

    return geom
예제 #8
0
def convert_sr(geom: ogr.Geometry,
               epsg_source: int = 4326,
               epsg_target: int = 3044) -> ogr.Geometry:
    """converts reference systems of ogr Geometries
    
    Arguments:
        geom {ogr.Geometry} -- geometry where the RS should be changed
    
    Keyword Arguments:
        epsg_source {int} -- epsg code of current reference system (default: {4326})
        epsg_target {int} -- epsg code of target reference system (default: {3044})
    
    Returns:
        ogr.Geometry -- Geometry with transformed reference system
    """
    source = osr.SpatialReference()
    source.ImportFromEPSG(epsg_source)

    target = osr.SpatialReference()
    target.ImportFromEPSG(epsg_target)

    transform = osr.CoordinateTransformation(source, target)

    geom.Transform(transform)

    return geom
예제 #9
0
    def project(self,
                geometry: ogr.Geometry,
                srs: int or ogr.osr.SpatialReference,
                copy: bool = True) -> ogr.Geometry:
        """
        Project a geometry to a spatial reference.

        :param geometry: the geometry to project
        :type geometry:  :py:class:`ogr.Geometry`
        :param srs: the spatial reference (or SRID) to which we're going to project
        :type srs:  :py:class:`ogr.osr.SpatialReference` or ``int``
        :param copy: Make a copy of the geometry or modify the current one?
        :type copy:  ``bool``
        :return: the projected geometry
        :rtype:  :py:class:`ogr.Geometry`
        """
        # The incoming spatial reference argument might be spatial reference, or it might be an SRID.  Figure out
        # which one we're dealing with and make sure we end up with a spatial reference.
        _srs = srs if isinstance(
            srs, ogr.osr.SpatialReference) else self.get_spatial_reference(
                srid=srs)
        # The object we ultimately transform depends on the 'copy' parameter.
        _geometry = geometry if not copy else geometry.Clone()
        # Perform the transformation.
        _geometry.TransformTo(_srs)
        # Return whatever we have.
        return _geometry
예제 #10
0
 def fill_points(shape: GeometryShape, geom: ogr.Geometry, dims: int):
     for i in range(0, len(shape.coordinates), dims):
         x = shape.coordinates[i + 0]
         y = shape.coordinates[i + 1]
         z = 0
         if dims > 2:
             z = shape.coordinates[i + 2]
         geom.AddPoint(x, y, z)
예제 #11
0
파일: objects.py 프로젝트: Stratifyd/geo
 def create_from_coordinates(longitude_latitude_coordinates):
     ring = Geometry(wkbLinearRing)
     for longitude, latitude in longitude_latitude_coordinates:
         ring.AddPoint(longitude, latitude)
     ring.CloseRings()
     poly = Geometry(wkbPolygon)
     poly.AddGeometry(ring)
     return poly
예제 #12
0
def geometry_to_tuples(geom: ogr.Geometry) -> tuple:
    """Returns the bounds of the shape
    Arguments:
        geom: the geometry to return the bounds of
    Return:
        A tuple containing the bounds in (min Y, max Y, min X, max X) order
    """
    current_env = geom.GetEnvelope()

    return current_env[2], current_env[3], current_env[0], current_env[1]
예제 #13
0
    def ogr_to_shapely(self, ogr_geometry: ogr.Geometry) -> BaseGeometry:
        """
        Convert an OGR geometry to a Shapely geometry.

        :param ogr_geometry: the OGR geometry
        :type ogr_geometry:  :py:class:`ogr.Geometry`
        :return: the base geometry
        :rtype:  :py:class:`BaseGeometry`
        """
        wkb = ogr_geometry.ExportToWkb()
        shapely_geometry = shapely.wkb.loads(wkb)
        return shapely_geometry
예제 #14
0
    def calculate_overlap_percent(check_bounds: ogr.Geometry, other_bounds: ogr.Geometry) -> float:
        """Calculates and returns the percentage overlap between the two boundaries.
           The calculation determines the overlap shape between the two parameters and
           then calculates the percentage by dividing the overlap area by the checking
           bounds area, and returns that value.
        Args:
            check_bounds: geometry of boundary to check
            other_bounds: geometry of boundary to check against
        Return:
            The calculated overlap percent (0.0 - 1.0) or 0.0 if there is no overlap.
            If an exception is detected, a warning message is logged and 0.0 is returned.
        """
        try:
            if check_bounds and other_bounds:
                intersection = other_bounds.Intersection(check_bounds)
                if intersection:
                    return intersection.Area() / check_bounds.Area()
        except Exception as ex:
            logging.warning("Exception caught while calculating shape overlap: %s", str(ex))

        return 0.0
예제 #15
0
def larger_area(larger_network_area: ogr.Geometry,
                project_area: ogr.Geometry) -> ogr.Geometry:
    """
    The area in which the network will only cover main roads,
    defaults to the project area, if no larger_network_area is given
    """
    dummy_geom = dummy_polygon()
    # compare the geometry to the default dummy_area
    if larger_network_area.SymmetricDifference(dummy_geom).Area():
        #  if its different, the area of the symmetric difference is > 0
        return larger_network_area
    #  otherwise, use the project_area instead
    return project_area
예제 #16
0
def detailed_area(detailed_network_area: ogr.Geometry,
                  project_area: ogr.Geometry) -> ogr.Geometry:
    """
    The area in which the network will be detailed,
    defaults to the project area, if no detailed_network_area is given
    """
    dummy_geom = dummy_polygon()
    # compare the geometry to the default dummy_area
    if detailed_network_area.SymmetricDifference(dummy_geom).Area():
        #  if its different, the area of the symmetric difference is > 0
        return detailed_network_area
    #  otherwise, use the project_area instead
    return project_area
예제 #17
0
    def get_parallel_offset(self, linestring: ogr.Geometry, side: Sides,
                            distance: Distance) -> ogr.Geometry:
        """
        Get a linestring geometry that is parallel to a given linestring.

        :param linestring: the linestring for which you want a parallel linestring
        :type linestring:  :py:class:`ogr.Geometry`
        :param side: Which side of the line should the parallel line fall on?
        :type side:  :py:class:`Sides`
        :param distance: How far should the parallel linestring be from the original linestring?
        :type distance:  :py:class:`Distance`
        :return: the parallel linestring
        :rtype:  :py:class:`ogr.Geometry`
        """
        # TODO: This method is a target for performance improvements.  Right now we are switching back and forth between OGR and Shapely geometries a couple of times.
        # Make not of the geometry argument's SRID.  (We'll need it a few times below.)
        _original_srid = self.get_srid(geometry=linestring)
        # If the incoming geometry is in a projected coordinate system that uses meters, we can use it directly.
        # Otherwise, we need to make a copy and transform the copy.
        _linestring = (linestring if _original_srid == self._projected_srid
                       else self.project(geometry=linestring,
                                         srs=self._projected_srs,
                                         copy=True))
        # Now we need to convert the distance to the units of the projected coordinate system.
        # (See http://python-measurement.readthedocs.io/en/latest/topics/measures.html#distance)
        offset_distance_in_meters = distance.m
        # For our next trick, we'll need a Shapely geometry.
        shapely_linestring: LineString = self.ogr_to_shapely(_linestring)
        # The shapely call takes string values for the 'side' parameter.  Let's figure out what we're going to use.
        side_arg = 'left' if side == Sides.LEFT else 'right'
        # Now we have enough information to use the Shapely parallel_offset() function.
        # (http://toblerity.org/shapely/shapely.geometry.html)
        shapely_linestring_offset = shapely_linestring.parallel_offset(
            distance=offset_distance_in_meters,
            side=side_arg,
            resolution=16,
            join_style=1,
            mitre_limit=1.0)
        # Now we convert back to an OGR geometry.
        ogr_linestring_offset = self.shapely_to_ogr(
            shapely_geometry=shapely_linestring_offset,
            srs=self._projected_srs)
        # If we projected the original geometry, we need to project it back to the original coordinate system.
        if _original_srid != self._projected_srid:
            ogr_linestring_offset = self.project(
                geometry=ogr_linestring_offset,
                srs=linestring.GetSpatialReference(),
                copy=False)
        # OK.  That's that.
        return ogr_linestring_offset
예제 #18
0
def convert_geometry(
        geometry: ogr.Geometry,
        new_spatialreference: osr.SpatialReference) -> ogr.Geometry:
    """Converts the geometry to the new spatial reference if possible
    Arguments:
        geometry - The geometry to transform
        new_spatialreference - The spatial reference to change to
    Returns:
        The transformed geometry or the original geometry. If either the
        new Spatial Reference parameter is None, or the geometry doesn't
        have a spatial reference, then the original geometry is returned.
    """
    if not new_spatialreference or not geometry:
        return geometry

    return_geometry = geometry
    try:
        geom_sr = geometry.GetSpatialReference()
        if int(osgeo.__version__[0]) >= 3:
            # GDAL 3 changes axis order: https://github.com/OSGeo/gdal/issues/1546
            # pylint: disable=no-member
            geom_sr.SetAxisMappingStrategy(
                osgeo.osr.OAMS_TRADITIONAL_GIS_ORDER)
        if geom_sr and not new_spatialreference.IsSame(geom_sr):
            transform = osr.CreateCoordinateTransformation(
                geom_sr, new_spatialreference)
            new_geom = geometry.Clone()
            if new_geom:
                new_geom.Transform(transform)
                return_geometry = new_geom
    except Exception as ex:
        logging.warning("Exception caught while transforming geometries: %s",
                        str(ex))
        logging.warning("    Returning original geometry")

    return return_geometry
예제 #19
0
def get_segment_intersection_point(segment: List[PointData],
                                   region_of_interest: ogr.Geometry):
    geographic_geom, projected_geom = get_segment_geometry(segment)
    boundary = region_of_interest.GetBoundary()
    intersection = geographic_geom.Intersection(boundary)
    # `intersection` might be single or multi, convert to multi to make uniform
    multi_intersection = ogr.ForceToMultiPoint(intersection)
    first_intersection_geom = multi_intersection.GetGeometryRef(0)
    if first_intersection_geom is None:
        result = None
    else:
        intersection_coords = first_intersection_geom.GetPoint()
        result = PointData(
            acceleration_x=segment[1].acceleration_x,
            acceleration_y=segment[1].acceleration_y,
            acceleration_z=segment[1].acceleration_z,
            accuracy=segment[1].accuracy,
            battery_consumption_per_hour=segment[1].
            battery_consumption_per_hour,
            battery_level=segment[1].battery_level,
            device_bearing=segment[1].device_bearing,
            device_pitch=segment[1].device_pitch,
            device_roll=segment[1].device_roll,
            elevation=segment[1].elevation,
            gps_bearing=segment[1].gps_bearing,
            humidity=segment[1].humidity,
            lumen=segment[1].lumen,
            pressure=segment[1].pressure,
            proximity=segment[1].proximity,
            serial_version_uid=segment[1].serial_version_uid,
            session_id=segment[1].session_id,
            speed=segment[1].speed,
            temperature=segment[1].temperature,
            timestamp=segment[1].timestamp,
            vehicle_type=segment[1].vehicle_type,
            latitude=intersection_coords[1],
            longitude=intersection_coords[0],
        )
        # now adjust the timestamp
        new_segment = [segment[0], result]
        new_segment_projected_geom = get_segment_geometry(new_segment)[1]
        length_factor = (new_segment_projected_geom.Length() /
                         projected_geom.Length())
        segment_duration = get_segment_duration(segment)
        new_segment_duration = segment_duration * length_factor
        result.timestamp = segment[0].timestamp + dt.timedelta(
            seconds=new_segment_duration)
    return result
예제 #20
0
    def get_srid(self, geometry: ogr.Geometry) -> int or None:
        """
        Get the SRID of an OGR geometry's spatial reference

        :param geometry: the geometry
        :type geometry:  :py:class:`ogr.Geometry`
        :return: the SRID (or ``None`` if the geometry has no spatial reference)
        :rtype:  ``int`` or ``None``
        """
        # Get the spatial reference.
        srs: ogr.osr.SpatialReference = geometry.GetSpatialReference()
        # If the geometry has no spatial reference, return None to the caller.
        if srs is None:
            return None
        else:
            # Dig out the SRID.
            # https://gis.stackexchange.com/questions/20298/is-it-possible-to-get-the-epsg-value-from-an-osr-spatialreference-class-using-th
            srid = int(srs.GetAttrValue('AUTHORITY', 1))
            return srid
예제 #21
0
def decode_geom(encoded_polyline):
    """
    Function decoding an encoded polyline (with 'encoded polyline
    algorithm') and returning an ogr.Geometry object

    Parameters
    ----------
    encoded_polyline : str
        The encoded string to decode.

    Returns
    -------
    line : ogr.Geometry
        The line geometry, as an ogr.Geometry instance.
    """
    ma_ligne = Geometry(2)
    lineAddPts = ma_ligne.AddPoint_2D
    for coord in PolylineCodec().decode(encoded_polyline):
        lineAddPts(coord[1], coord[0])
    return ma_ligne
예제 #22
0
def clip_raster_intersection(file_path: str, file_bounds: ogr.Geometry, plot_bounds: ogr.Geometry, out_file: str) ->\
        Optional[int]:
    """Clips the raster to the intersection of the file bounds and plot bounds
    Arguments:
        file_path: the path to the source file
        file_bounds: the geometric boundary of the source file
        plot_bounds: the geometric boundary of the plot to clip to
        out_file: the path to store the clipped image
    Return:
        The number of pixels in the new image, or None if no pixels were saved
    Notes:
        Assumes the boundaries are in the same coordinate system
    Exceptions:
        Raises RuntimeError if the polygons are invalid
    """
    logging.debug("Clip to intersect of plot boundary: File: '%s' '%s' Plot: '%s'", file_path, str(file_bounds), str(plot_bounds))
    try:
        if not file_bounds or not plot_bounds:
            logging.error("Invalid polygon specified for clip_raster_intersection: File: '%s' plot: '%s'",
                          str(file_bounds), str(plot_bounds))
            raise RuntimeError("One or more invalid polygons specified when clipping raster")

        intersection = file_bounds.Intersection(plot_bounds)
        if not intersection or not intersection.Area():
            logging.info("File does not intersect plot boundary: %s", file_path)
            return None

        # Make sure we pass a multipolygon down to the tuple converter
        if intersection.GetGeometryName().startswith('MULTI'):
            multi_polygon = intersection
        else:
            multi_polygon = ogr.Geometry(ogr.wkbMultiPolygon)
            multi_polygon.AddGeometry(intersection)

        # Proceed to clip to the intersection
        tuples = geometries.geometry_to_tuples(multi_polygon)
        return clip_raster(file_path, tuples, out_path=out_file, compress=True)

    except Exception as ex:
        logging.exception("Exception caught while clipping image to plot intersection")
        raise ex
예제 #23
0
파일: objects.py 프로젝트: Stratifyd/geo
 def Point(longitude, latitude, altitude=0.0):
     point = Geometry(wkbPoint)
     point.AddPoint(longitude, latitude, altitude)
     return point
예제 #24
0
def write_foglio(foglio,
                 destination,
                 point_borders=False,
                 format_name='ESRI Shapefile'):

    cassini_soldener = ''
    #Imposto alcune variabile a seconda del codice_comune:
    #ATTENZIONE: Prima di modificare qui lo SRID controllare che su Postgres le tavole siano impostate adeguatamente nella tavola geometry_columns!!!
    #ATTENZIONE: se nella definizione della cassini_soldener si inseriscono dei valori fissi di x_0 e y_0 ricordarsi di definire successivamente la local_cassini_soldener in maniera adeguata, cioe' togliendo il riferimento al vettore shift_cassini prima definito. In pratica aggiungere il codice_comune nell'array del primo "if" (verso rigo 103...)
    if foglio['CODICE COMUNE'] == 'G087':
        cassini_soldener = '+proj=cass +lat_0=45.007336 +lon_0=7.53725 +x_0=%f +y_0=%f +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'B305':
        cassini_soldener = '+proj=cass +lat_0=45.067618 +lon_0=7.436827 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'I785':
        cassini_soldener = '+proj=cass +lat_0=37.267029 +lon_0=14.692473 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'G535':
        cassini_soldener = '+proj=cass +lat_0=44.759075 +lon_0=9.917936 +x_0=-15.5 +y_0=10.5 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'G476':
        cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'L380':
        cassini_soldener = '+proj=tmerc +lat_0=0 +lon_0=9 +k=0.9996 +x_0=1500000 +y_0=0 +ellps=intl +towgs84=-104.1,-49.1,-9.9,0.971,-2.917,0.714,-11.68 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'I258':
        cassini_soldener = '+proj=cass +lat_0=45.099116 +lon_0=7.356182 +x_0=-1.5 +y_0=0.5 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'C261':
        cassini_soldener = '+proj=cass +lat_0=45.31413 +lon_0=9.502994 +x_0=1 +y_0=1 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'C722':
        cassini_soldener = "+proj=cass +lat_0=45.235812 +lon_0=7.602194 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs +wktext"
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'A484':
        cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'G793':
        cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'I089':
        cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'I143':
        cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'I307':
        cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'G226':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'B266':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'B868':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'F618':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'F625':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'H683':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'I410':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'I451':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'C370':
        cassini_soldener = '+proj=cass +lat_0=45.558239 +lon_0=10.76357 +x_0=+0.45 +y_0=-1.90 +ellps=intl +units=m +no_defs'
        t_srs = '4326'
    elif foglio['CODICE COMUNE'] == 'D292':
        cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs'
    target_srs = SpatialReference()
    try:
        target_srs.ImportFromEPSG(int(t_srs))
    except TypeError:
        raise
        target_srs.ImportFromProj4(t_srs)

    shifts = ((0., 0.), (0., 0.))
    shifts = comuni_shift.get(foglio['CODICE COMUNE'], shifts)
    shifts = comuni_shift.get(
        (foglio['CODICE COMUNE'], foglio['NUMERO FOGLIO']), shifts)

    shift_cassini, shift_gauss_boaga = shifts
    ##### Parte eventualmente da MODIFICARE:
    if foglio['CODICE COMUNE'] in [
            'G535', 'I258', 'L380', 'G476', 'C261', 'A484', 'B266', 'B868',
            'F618', 'F625', 'G226', 'G793', 'I307', 'I410', 'I451', 'D292',
            'I143', 'I089', 'H683', 'C722', 'B305', 'I785', 'C370'
    ]:
        local_cassini_soldener = cassini_soldener
    else:
        local_cassini_soldener = cassini_soldener % (-shift_cassini[0],
                                                     -shift_cassini[1])

    source_srs = SpatialReference()
    source_srs.ImportFromProj4(local_cassini_soldener)

    trasformation = CoordinateTransformation(source_srs, target_srs)

    f_comune = FieldDefn('COMUNE', OFTString)
    f_comune.SetWidth(4)
    f_foglio = FieldDefn('FOGLIO', OFTString)
    f_foglio.SetWidth(11)
    f_tipo = FieldDefn('tipo', OFTString)
    f_tipo.SetWidth(11)
    f_part = FieldDefn('PARTICELLA', OFTString)
    f_part.SetWidth(8)
    f_numero = FieldDefn('NUMERO', OFTString)
    f_part.SetWidth(8)
    f_dimensione = FieldDefn('DIMENSIONE', OFTInteger)
    f_area = FieldDefn('AREA', OFTInteger)
    f_angolo = FieldDefn('ANGOLO', OFTReal)
    f_pos_x = FieldDefn('POSIZIONEX', OFTReal)
    f_pos_y = FieldDefn('POSIZIONEY', OFTReal)
    f_interno_x = FieldDefn('P_INTERNOX', OFTReal)
    f_interno_y = FieldDefn('P_INTERNOY', OFTReal)
    f_simbolo = FieldDefn('SIMBOLO', OFTInteger)
    f_etichetta = FieldDefn('etichetta', OFTString)
    f_etichetta.SetWidth(32)
    f_testo = FieldDefn('TESTO', OFTString)
    f_testo.SetWidth(256)

    create_options = []
    if format_name == 'PostgreSQL':
        #Per passare i parametri del driver nella forma "parametro=valore". Sfortunatamente NON POSSO PASSARE "-APPEND"!!!!
        #vedi anche: http://www.gdal.org/gdal_tutorial.html
        papszOptions = ['OVERWRITE=yes']
    elif format_name == 'SQLite':  #IN SVILUPPO!
        #per maggiori info vedere: http://www.gdal.org/drv_sqlite.html
        create_options = [
            'SPATIALITE=YES', 'INIT_WITH_EPSG=YES',
            'OGR_SQLITE_SYNCHRONOUS=OFF', 'OVERWRITE=yes'
        ]
        #l'opzione Overwrite sul DB non funziona: ho messo una IF oltre
        papszOptions = ['FORMAT=SPATIALITE', 'OVERWRITE=yes']  #default
    else:
        papszOptions = []

    if (format_name == 'SQLite') and (os.path.exists(destination)):
        ds = GetDriverByName(format_name).Open(destination, update=1)
    #Pensavo in questo modo di ovviare all'errore che mi restituisce lo script nel caso di DB:
    #ERROR 1: PostgreSQL driver doesn't currently support database creation. Please create database with the `createdb' command.
    #ma non ho risolto niente... Invece aggiungendo "PG:" il plugin genera le tabelle!
    elif (format_name == 'PostgreSQL'):
        #    ds = GetDriverByName(format_name).Open(destination)
        #destination = "PG:%s" % (destination)
        ds = GetDriverByName(format_name).CreateDataSource(
            destination, options=create_options)
    else:
        ds = GetDriverByName(format_name).CreateDataSource(
            destination, options=create_options)
    #per evitare sovrascritture aggiungo anche l'allegato
    pedice = "%s_%s_%s_%s" % (foglio['CODICE COMUNE'], foglio['NUMERO FOGLIO'],
                              foglio['CODICE ALLEGATO'],
                              foglio['CODICE SVILUPPO'])

    #PLUGIN QGIS:
    #Decodifico alcuni campi in modo tale che vengano riconosciuti corretti anche dalle librerie interne di QGis:
    comune_decode = remove_accents(foglio['CODICE COMUNE'])
    #oppure potrebbe essere:
    #comune_decode = foglio['CODICE COMUNE'].encode('utf-8')
    codice_foglioXX = foglio['CODICE FOGLIO'][5:
                                              9]  #cosi' dovrebbe essere "0036"
    foglio_intero = int(codice_foglioXX.lstrip('0'))

    # tipo BORDO
    #bordi = ds.CreateLayer('CATASTO_BORDI', target_srs, wkbPolygon)
    nome_layer_not_utf = "CATASTO_BORDI_%s" % (pedice)
    nome_layer = nome_layer_not_utf.encode('utf-8')  #serve per plugin QGis
    bordi = ds.CreateLayer(nome_layer, target_srs, wkbPolygon25D, papszOptions)

    bordi.CreateField(f_comune)
    bordi.CreateField(f_foglio)
    bordi.CreateField(f_tipo)
    bordi.CreateField(f_part)
    bordi.CreateField(f_dimensione)
    bordi.CreateField(f_angolo)
    bordi.CreateField(f_pos_x)
    bordi.CreateField(f_pos_y)
    bordi.CreateField(f_interno_x)
    bordi.CreateField(f_interno_y)
    bordi.CreateField(f_area)
    bordi.CreateField(f_etichetta)

    for oggetto in foglio['oggetti']['BORDO']:
        poly = Geometry(wkbPolygon)
        tabisole = map(int, oggetto['TABISOLE'])

        # contorno esterno
        vertici_contorno = int(oggetto['NUMEROVERTICI']) - sum(tabisole)
        ring = Geometry(wkbLinearRing)
        for vertice in range(vertici_contorno):
            x, y = map(float, oggetto['VERTICI'][vertice])
            if True:
                x, y = trasformation.TransformPoint(x, y)[:2]
            ring.AddPoint(x + shift_gauss_boaga[0], y + shift_gauss_boaga[1])
        ring.CloseRings()
        poly.AddGeometry(ring)

        # isole
        for isola in range(int(oggetto['NUMEROISOLE'])):
            ring = Geometry(wkbLinearRing)
            for vertice in range(vertice + 1, vertice + 1 + tabisole[isola]):
                x, y = map(float, oggetto['VERTICI'][vertice])
                if True:
                    x, y = trasformation.TransformPoint(x, y)[:2]
                ring.AddPoint(x + shift_gauss_boaga[0],
                              y + shift_gauss_boaga[1])
            ring.CloseRings()
            poly.AddGeometry(ring)

        etichetta = oggetto['CODICE IDENTIFICATIVO']
        if oggetto['CODICE IDENTIFICATIVO'][-1] == '+':
            etichetta = ''

        feat = Feature(bordi.GetLayerDefn())
        feat.SetField('COMUNE',
                      comune_decode)  #plugin in QGis necessita di decodifica
        #codice_foglioXX = foglio['CODICE FOGLIO'][5:9] #cosi' dovrebbe essere "0036"
        #feat.SetField('FOGLIO', codice_foglioXX.lstrip('0'))
        feat.SetField('FOGLIO',
                      foglio_intero)  #plugin in QGis necessita di decodifica
        feat.SetField('tipo', oggetto['tipo'])
        #feat.SetField('PARTICELLA', oggetto['CODICE IDENTIFICATIVO']) #voglio togliere il "+"
        feat.SetField('PARTICELLA',
                      oggetto['CODICE IDENTIFICATIVO'].rstrip('+'))
        feat.SetField('DIMENSIONE', int(oggetto['DIMENSIONE']))
        feat.SetField('ANGOLO', float(oggetto['ANGOLO']))
        pos_x, pos_y = map(float,
                           (oggetto['POSIZIONEX'], oggetto['POSIZIONEY']))
        interno_x, interno_y = map(
            float, (oggetto['PUNTOINTERNOX'], oggetto['PUNTOINTERNOY']))
        if True:
            pos_x, pos_y = trasformation.TransformPoint(pos_x, pos_y)[:2]
            interno_x, interno_y = trasformation.TransformPoint(
                interno_x, interno_y)[:2]
        feat.SetField('POSIZIONEX', pos_x + shift_gauss_boaga[0])
        feat.SetField('POSIZIONEY', pos_y + shift_gauss_boaga[1])
        feat.SetField('P_INTERNOX', interno_x + shift_gauss_boaga[0])
        feat.SetField('P_INTERNOY', interno_y + shift_gauss_boaga[1])
        feat.SetField('AREA', oggetto.get('AREA', -1))
        feat.SetField('etichetta', etichetta.encode('utf-8'))
        feat.SetGeometry(poly)
        bordi.CreateFeature(feat)
        feat.Destroy()

    if point_borders:
        # tipo BORDO_PUNTO
        #bordi = ds.CreateLayer('CATASTO_PARTICELLE', target_srs, wkbPoint)
        #nome_layer = "CATASTO_PARTICELLE_%s" % (pedice)
        nome_layer_not_utf = "CATASTO_PARTICELLE_%s" % (pedice)
        nome_layer = nome_layer_not_utf.encode('utf-8')  #serve per plugin QGis
        bordi = ds.CreateLayer(nome_layer, target_srs, wkbPoint, papszOptions)

        bordi.CreateField(f_comune)
        bordi.CreateField(f_foglio)
        bordi.CreateField(f_tipo)
        bordi.CreateField(f_part)
        bordi.CreateField(f_dimensione)
        bordi.CreateField(f_angolo)
        bordi.CreateField(f_area)
        bordi.CreateField(f_etichetta)

        for oggetto in foglio['oggetti']['BORDO']:
            etichetta = oggetto['CODICE IDENTIFICATIVO']
            if oggetto['CODICE IDENTIFICATIVO'][-1] == '+':
                etichetta = ''

            feat = Feature(bordi.GetLayerDefn())
            #feat.SetField('COMUNE', foglio['CODICE COMUNE'])
            feat.SetField(
                'COMUNE',
                comune_decode)  #plugin in QGis necessita di decodifica
            #feat.SetField('FOGLIO', foglio['CODICE FOGLIO'])
            feat.SetField(
                'FOGLIO',
                foglio_intero)  #plugin in QGis necessita di decodifica
            feat.SetField('tipo', oggetto['tipo'])
            feat.SetField('PARTICELLA', oggetto['CODICE IDENTIFICATIVO'])
            feat.SetField('DIMENSIONE', int(oggetto['DIMENSIONE']))
            feat.SetField('ANGOLO', float(oggetto['ANGOLO']))
            pos_x, pos_y = map(
                float, (oggetto['PUNTOINTERNOX'], oggetto['PUNTOINTERNOY']))
            if True:
                pos_x, pos_y = trasformation.TransformPoint(pos_x, pos_y)[:2]
            feat.SetField('AREA', oggetto.get('AREA', -1))
            feat.SetField('etichetta', etichetta.encode('utf-8'))
            pt = Geometry(wkbPoint)
            pt.SetPoint_2D(0, pos_x + shift_gauss_boaga[0],
                           pos_y + shift_gauss_boaga[1])
            feat.SetGeometry(pt)
            bordi.CreateFeature(feat)
            feat.Destroy()

    # tipo TESTO
    #testi = ds.CreateLayer('CATASTO_TESTI', target_srs, wkbPoint)
    #nome_layer = "CATASTO_TESTI_%s" % (pedice)
    nome_layer_not_utf = "CATASTO_TESTI_%s" % (pedice)
    nome_layer = nome_layer_not_utf.encode('utf-8')  #serve per plugin QGis
    testi = ds.CreateLayer(nome_layer, target_srs, wkbPoint, papszOptions)

    testi.CreateField(f_comune)
    testi.CreateField(f_foglio)
    testi.CreateField(f_testo)
    testi.CreateField(f_dimensione)
    testi.CreateField(f_angolo)
    testi.CreateField(f_etichetta)

    for oggetto in foglio['oggetti']['TESTO']:
        x, y = map(float, (oggetto['POSIZIONEX'], oggetto['POSIZIONEY']))
        if True:
            x, y = trasformation.TransformPoint(x, y)[:2]
        # FIXME: many texts are useless, prun them from etichetta
        etichetta = remove_accents(oggetto['TESTO'])

        feat = Feature(testi.GetLayerDefn())
        #feat.SetField('COMUNE', foglio['CODICE COMUNE'])
        feat.SetField('COMUNE',
                      comune_decode)  #plugin in QGis necessita di decodifica
        #feat.SetField('FOGLIO', foglio['CODICE FOGLIO'])
        feat.SetField('FOGLIO',
                      foglio_intero)  #plugin in QGis necessita di decodifica
        #feat.SetField('TESTO', oggetto['TESTO'])
        feat.SetField('TESTO', etichetta)
        feat.SetField('DIMENSIONE', int(oggetto['DIMENSIONE']))
        feat.SetField('ANGOLO', float(oggetto['ANGOLO']))
        feat.SetField('etichetta', etichetta.encode('utf-8'))
        pt = Geometry(wkbPoint)
        pt.SetPoint_2D(0, x + shift_gauss_boaga[0], y + shift_gauss_boaga[1])
        feat.SetGeometry(pt)
        testi.CreateFeature(feat)

    # tipo SIMBOLO
    #simboli = ds.CreateLayer('CATASTO_SIMBOLI', target_srs, wkbPoint)
    #nome_layer = "CATASTO_SIMBOLI_%s" % (pedice)
    nome_layer_not_utf = "CATASTO_SIMBOLI_%s" % (pedice)
    nome_layer = nome_layer_not_utf.encode('utf-8')  #serve per plugin QGis
    simboli = ds.CreateLayer(nome_layer, target_srs, wkbPoint, papszOptions)

    simboli.CreateField(f_comune)
    simboli.CreateField(f_foglio)
    simboli.CreateField(f_simbolo)
    simboli.CreateField(f_angolo)

    for oggetto in foglio['oggetti']['SIMBOLO']:
        x, y = map(float, (oggetto['POSIZIONEX'], oggetto['POSIZIONEY']))
        if True:
            x, y = trasformation.TransformPoint(x, y)[:2]

        feat = Feature(simboli.GetLayerDefn())
        #feat.SetField('COMUNE', foglio['CODICE COMUNE'])
        feat.SetField('COMUNE',
                      comune_decode)  #plugin in QGis necessita di decodifica
        #feat.SetField('FOGLIO', foglio['CODICE FOGLIO'])
        feat.SetField('FOGLIO',
                      foglio_intero)  #plugin in QGis necessita di decodifica
        feat.SetField('SIMBOLO', oggetto['CODICE SIMBOLO'])
        feat.SetField('ANGOLO', float(oggetto['ANGOLO']))
        pt = Geometry(wkbPoint)
        pt.SetPoint_2D(0, x + shift_gauss_boaga[0], y + shift_gauss_boaga[1])
        feat.SetGeometry(pt)
        simboli.CreateFeature(feat)

    # tipo FIDUCIALE
    #fiduciali = ds.CreateLayer('CATASTO_FIDUCIALI', target_srs, wkbPoint)
    #nome_layer = "CATASTO_FIDUCIALI_%s" % (pedice)
    nome_layer_not_utf = "CATASTO_FIDUCIALI_%s" % (pedice)
    nome_layer = nome_layer_not_utf.encode('utf-8')  #serve per plugin QGis
    fiduciali = ds.CreateLayer(nome_layer, target_srs, wkbPoint, papszOptions)

    fiduciali.CreateField(f_comune)
    fiduciali.CreateField(f_foglio)
    fiduciali.CreateField(f_numero)
    fiduciali.CreateField(f_simbolo)
    fiduciali.CreateField(f_pos_x)
    fiduciali.CreateField(f_pos_y)
    fiduciali.CreateField(f_etichetta)

    print 'corrections', shift_cassini, shift_gauss_boaga
    for oggetto in foglio['oggetti']['FIDUCIALE']:
        x, y = map(float, (oggetto['POSIZIONEX'], oggetto['POSIZIONEY']))
        pos_x, pos_y = map(float, (oggetto['PUNTORAPPRESENTAZIONEX'],
                                   oggetto['PUNTORAPPRESENTAZIONEY']))
        if True:
            x, y = trasformation.TransformPoint(x, y)[:2]
            pos_x, pos_y = trasformation.TransformPoint(pos_x, pos_y)[:2]
        etichetta = 'PF%02d/%s%s/%s' % (int(oggetto['NUMERO IDENTIFICATIVO']),
                                        foglio['CODICE NUMERO FOGLIO'][1:],
                                        foglio['CODICE ALLEGATO'],
                                        foglio['CODICE COMUNE'])

        feat = Feature(fiduciali.GetLayerDefn())
        #feat.SetField('COMUNE', foglio['CODICE COMUNE'])
        feat.SetField('COMUNE',
                      comune_decode)  #plugin in QGis necessita di decodifica
        #feat.SetField('FOGLIO', foglio['CODICE FOGLIO'])
        feat.SetField('FOGLIO',
                      foglio_intero)  #plugin in QGis necessita di decodifica
        feat.SetField('NUMERO', oggetto['NUMERO IDENTIFICATIVO'])
        feat.SetField('SIMBOLO', oggetto['CODICE SIMBOLO'])
        feat.SetField('POSIZIONEX', pos_x + shift_gauss_boaga[0])
        feat.SetField('POSIZIONEY', pos_y + shift_gauss_boaga[1])
        feat.SetField('etichetta', etichetta.encode('utf-8'))
        pt = Geometry(wkbPoint)
        pt.SetPoint_2D(0, x + shift_gauss_boaga[0], y + shift_gauss_boaga[1])
        feat.SetGeometry(pt)
        fiduciali.CreateFeature(feat)

        print etichetta, oggetto['CODICE SIMBOLO'], \
            float(oggetto['POSIZIONEX']) + shift_cassini[0], float(oggetto['POSIZIONEY']) + shift_cassini[1], \
            x + shift_gauss_boaga[0], y + shift_gauss_boaga[1]

    # tipo LINEA
    #linee = ds.CreateLayer('CATASTO_LINEE', target_srs, wkbLineString)
    #nome_layer = "CATASTO_LINEE_%s" % (pedice)
    nome_layer_not_utf = "CATASTO_LINEE_%s" % (pedice)
    nome_layer = nome_layer_not_utf.encode('utf-8')  #serve per plugin QGis
    linee = ds.CreateLayer(nome_layer, target_srs, wkbLineString25D,
                           papszOptions)

    linee.CreateField(f_comune)
    linee.CreateField(f_foglio)
    linee.CreateField(f_simbolo)

    for oggetto in foglio['oggetti']['LINEA']:
        # contorno esterno
        vertici = int(oggetto['NUMEROVERTICI'])
        linea = Geometry(wkbLineString)
        for vertice in range(vertici):
            x, y = map(float, oggetto['VERTICI'][vertice])
            if True:
                x, y = trasformation.TransformPoint(x, y)[:2]
            linea.AddPoint(x + shift_gauss_boaga[0], y + shift_gauss_boaga[1])

        feat = Feature(linee.GetLayerDefn())
        #feat.SetField('COMUNE', foglio['CODICE COMUNE'])
        feat.SetField('COMUNE',
                      comune_decode)  #plugin in QGis necessita di decodifica
        #feat.SetField('FOGLIO', foglio['CODICE FOGLIO'])
        feat.SetField('FOGLIO',
                      foglio_intero)  #plugin in QGis necessita di decodifica
        feat.SetField('SIMBOLO', oggetto['CODICE TIPO DI TRATTO'])
        feat.SetGeometry(linea)
        linee.CreateFeature(feat)
        feat.Destroy()

    ds.Destroy()
예제 #25
0
 def ogrPoint(self):
     '''returns the current point as an ogr.Geometry wkbPoint
     '''
     p1 = Geometry(wkbPoint)
     p1.AddPoint_2D(self.lat, self.lon)
     return p1
예제 #26
0
def get_length(linestring_geom: ogr.Geometry, coordinate_transformer):
    cloned_geom = linestring_geom.Clone()
    cloned_geom.Transform(coordinate_transformer)
    return cloned_geom.Length()
예제 #27
0
def Make_Start_Points_Road(road_geo:ogr.Geometry, 
                           start_points:dict, 
                           seg_length:float):
    '''在road_geo上每隔seg_length取一个出发点'''

     
    count = road_geo.GetPointCount()
    total_length = road_geo.Length()

    '''如果是在递归中seg_length比路的全长还要长,那就把路的最后一个点作为出发点'''
    if seg_length >= total_length:
        start_point = road_geo.GetPoint_2D(count-1)        
        start_points[start_point] = [road_geo.GetPoint_2D(count-2), road_geo.GetPoint_2D(count-1)] 
        #start_points = {出发点: [前驱点, 后继点]}
        return 
    
    first_to_current_length = 0
    temp_length = 0
    temp_x1 = 0
    temp_y1 = 0
    temp_x2 = 0
    temp_y2 = 0
    
    '''计算当前线段的长度和累计长度'''
    for index in range(count-1):
        temp_x1 = road_geo.GetX(index)              
        temp_y1 = road_geo.GetY(index)  
        temp_x2 = road_geo.GetX(index+1)
        temp_y2 = road_geo.GetY(index+1)
        temp_length = math.sqrt( (temp_x1-temp_x2)**2 + (temp_y1-temp_y2)**2 )
        first_to_current_length = first_to_current_length + temp_length
        if seg_length < first_to_current_length:
            pre_point = (temp_x1, temp_y1)
            nex_point = (temp_x2, temp_y2)
            break
    '''这时从第零个点到第index+1个点的距离大于seg_length了'''

    '''算出发点的坐标'''
    len1 = seg_length - (first_to_current_length - temp_length)
    start_point_x = (len1 / temp_length) * (temp_x2 - temp_x1) + temp_x1
    start_point_y = (len1 / temp_length) * (temp_y2 - temp_y1) + temp_y1
    start_points[(start_point_x, start_point_y)] = [pre_point, nex_point]
    
    '''给出发点后面的点做一个线的几何体,用来进行下一个递归'''
    temp_road_geo = ogr.Geometry(ogr.wkbLineString)
    temp_road_geo.AddPoint(start_point_x, start_point_y)
    for i in range(index+1, count):
        temp_x = road_geo.GetX(i)                   
        temp_y = road_geo.GetY(i)        
        temp_road_geo.AddPoint(temp_x, temp_y)
      
    Make_Start_Points_Road(temp_road_geo, start_points, seg_length)
예제 #28
0
from osgeo.ogr import Geometry, wkbPoint
# Only one OGR point needs to be created,
# since each call to `OGR_POINT.AddPoint`
# in the `check_point_in_area` function
# will reset the variable
OGR_POINT = Geometry(wkbPoint)


def coarse_geo_filter(df, AREA):
    """
	Perform an initial coarse filter on the dataframe
	based on the extent (bounding box) of the specified area
	"""
    # Get longitude values from index
    lons = df.index.get_level_values('lon_0')
    # Map longitude range from (0 to 360) into (-180 to 180)
    maplon = lambda lon: (lon - 360) if (lon > 180) else lon
    # Create new longitude and latitude columns in the dataframe
    df['longitude'] = lons.map(maplon)
    df['latitude'] = df.index.get_level_values('lat_0')
    # Get the area's bounding box
    extent = AREA.GetExtent()
    minlon = extent[0]
    maxlon = extent[1]
    minlat = extent[2]
    maxlat = extent[3]
    # Perform an initial coarse filter on the global dataframe
    # by limiting the data to the area's bounding box,
    # thereby reducing the total processing time of the `area_filter`
    latfilter = ((df['latitude'] >= minlat) & (df['latitude'] <= maxlat))
    lonfilter = ((df['longitude'] >= minlon) & (df['longitude'] <= maxlon))