示例#1
0
  def load_data(self):
    self.source = ogr.Open( self.config['file_name'], update = 0 )
    self.layer = self.source.GetLayer(0)
    if 'filter' in self.config and self.config['filter'] is not None:
      self.layer.SetAttributeFilter( self.config['filter'].encode('ascii') )
    self.layer_dfn = self.layer.GetLayerDefn()

    self.fields = []
    field_count = self.layer_dfn.GetFieldCount()
    for field_index in range(field_count):
      field = self.layer_dfn.GetFieldDefn( field_index )
      self.fields.append({
        'name': field.GetName(),
        'type': field.GetType(),
        'width': field.GetWidth(),
        'precision': field.GetPrecision()
      })

    self.geometries = []

    for feature in self.layer:
      geometry = feature.GetGeometryRef()
      geometry.TransformTo( self.spatialRef )
      geometry = shapely.wkb.loads( geometry.ExportToWkb() )
      if not geometry.is_valid:
        geometry = geometry.buffer(0)
      properties = {}
      for field in self.fields:
        properties[field['name']] = feature.GetFieldAsString(field['name']).decode('utf-8')
      self.geometries.append( Geometry(geometry, properties) )

    self.layer.ResetReading()

    self.create_grammar()
示例#2
0
  def load_data(self):
    self.source = ogr.Open( self.config['file_name'], update = 0 )
    self.layer = self.source.GetLayer(0)
    if 'filter' in self.config and self.config['filter'] is not None:
      self.layer.SetAttributeFilter( self.config['filter'].encode('ascii') )
    self.layer_dfn = self.layer.GetLayerDefn()

    self.fields = []
    field_count = self.layer_dfn.GetFieldCount()
    for field_index in range(field_count):
      field = self.layer_dfn.GetFieldDefn( field_index )
      self.fields.append({
        'name': field.GetName(),
        'type': field.GetType(),
        'width': field.GetWidth(),
        'precision': field.GetPrecision()
      })

    self.geometries = []

    for feature in self.layer:
      geometry = feature.GetGeometryRef()
      geometry.TransformTo( self.spatialRef )
      geometry = shapely.wkb.loads( geometry.ExportToWkb() )
      if not geometry.is_valid:
        geometry = geometry.buffer(0)
      properties = {}
      for field in self.fields:
        properties[field['name']] = feature.GetFieldAsString(field['name']).decode('utf-8')
      self.geometries.append( Geometry(geometry, properties) )

    self.layer.ResetReading()

    self.create_grammar()
示例#3
0
    def convert(cls, value: Any) -> Optional[shapely.geometry.base.BaseGeometry]:
        geometry = cls.to_geometry(value, shapely.geometry.base.BaseGeometry)

        if isinstance(geometry, shapely.geometry.Polygon) and geometry.is_valid:
            # Heal polygon, see #506 and Shapely User Manual
            geometry = geometry.buffer(0)

        return geometry
示例#4
0
    def convert(cls,
                value: Any) -> Optional[shapely.geometry.base.BaseGeometry]:
        geometry = cls.to_geometry(value, shapely.geometry.base.BaseGeometry)

        if isinstance(geometry,
                      shapely.geometry.Polygon) and geometry.is_valid:
            # Heal polygon, see #506 and Shapely User Manual
            geometry = geometry.buffer(0)

        return geometry
示例#5
0
    def renderMapInset(self, codes, left, top, width):
        envelope = []
        for code in codes:
            envelope.append(self.features[code]['geometry'].envelope)

        bbox = shapely.geometry.MultiPolygon(envelope).bounds

        scale = (bbox[2] - bbox[0]) / width

        # generate SVG paths
        for code in codes:
            feature = self.features[code]
            geometry = feature['geometry']
            if self.buffer_distance:
                geometry = geometry.buffer(self.buffer_distance * scale, 1)
            if geometry.is_empty:
                continue
            if self.simplify_tolerance:
                geometry = geometry.simplify(self.simplify_tolerance * scale,
                                             preserve_topology=True)
            if isinstance(geometry,
                          shapely.geometry.multipolygon.MultiPolygon):
                polygons = geometry.geoms
            else:
                polygons = [geometry]
            path = ''
            for polygon in polygons:
                rings = []
                rings.append(polygon.exterior)
                rings.extend(polygon.interiors)
                for ring in rings:
                    for pointIndex in range(len(ring.coords)):
                        point = ring.coords[pointIndex]
                        if pointIndex == 0:
                            path += 'M' + str(
                                round((point[0] - bbox[0]) / scale + left,
                                      self.precision))
                            path += ',' + str(
                                round((bbox[3] - point[1]) / scale + top,
                                      self.precision))
                        else:
                            path += 'l' + str(
                                round(
                                    point[0] / scale -
                                    ring.coords[pointIndex - 1][0] / scale,
                                    self.precision))
                            path += ',' + str(
                                round(
                                    ring.coords[pointIndex - 1][1] / scale -
                                    point[1] / scale, self.precision))
                    path += 'Z'
            self.map.addPath(path, feature['code'], feature['name'])
        return bbox
示例#6
0
def prepare_feature_collection_coverage(feature_collection):
    """
    Loads GeoJSON string of a FeatureCollection, validates and fixes
    all geometries and returns a GeoJSON string back.
    """
    feature_collection = json.loads(feature_collection)
    for feature in feature_collection['features']:
        geometry = shapely.geometry.asShape(feature['geometry'])
        if not geometry.is_valid:
            geometry = geometry.buffer(0)
            feature['geometry'] = shapely.geometry.mapping(geometry)
    return json.dumps(feature_collection)
示例#7
0
def prepare_feature_collection_coverage(feature_collection):
    """
    Loads GeoJSON string of a FeatureCollection, validates and fixes
    all geometries and returns a GeoJSON string back.
    """
    feature_collection = json.loads(feature_collection)
    for feature in feature_collection['features']:
        geometry = shapely.geometry.asShape(feature['geometry'])
        if not geometry.is_valid:
            geometry = geometry.buffer(0)
            feature['geometry'] = shapely.geometry.mapping(geometry)
    return json.dumps(feature_collection)
    def createGeometryDict(self, geom, size):
        geometry = shapely.wkt.loads(geom)
        if (size == 'part'):
            minVal = min(
                np.max(geometry.geoms[0].exterior.xy[0]) -
                np.min(geometry.geoms[0].exterior.xy[0]),
                np.max(geometry.geoms[0].exterior.xy[1]) -
                np.min(geometry.geoms[0].exterior.xy[1]))

            bufferVal = -0.22 * minVal

            geometry = geometry.buffer(bufferVal)
        return geometry.__geo_interface__
    def getGeom(self, geom, size):
        geometry = shapely.wkt.loads(geom)

        buffPercentage = -0.22
        if (size == 'part'):
            minVal = min(
                np.max(geometry.geoms[0].exterior.xy[0]) -
                np.min(geometry.geoms[0].exterior.xy[0]),
                np.max(geometry.geoms[0].exterior.xy[1]) -
                np.min(geometry.geoms[0].exterior.xy[1]))

            bufferVal = buffPercentage * minVal

            newGeom = geometry.buffer(bufferVal)
            while (newGeom.is_empty or newGeom.area < (0.25 * geometry.area)):

                buffPercentage *= 0.95

                bufferVal = buffPercentage * minVal
                newGeom = geometry.buffer(bufferVal)
        else:
            newGeom = geometry

        return newGeom
示例#10
0
    def renderMapInset(self, codes, left, top, width):
        envelope = []
        for code in codes:
            envelope.append(self.features[code]['geometry'].envelope)

        bbox = shapely.geometry.MultiPolygon(envelope).bounds

        scale = (bbox[2] - bbox[0]) / width

        # generate SVG paths
        for code in codes:
            feature = self.features[code]
            geometry = feature['geometry']
            if self.buffer_distance:
                geometry = geometry.buffer(self.buffer_distance * scale, 1)
            if geometry.is_empty:
                continue
            if self.simplify_tolerance:
                geometry = geometry.simplify(self.simplify_tolerance, preserve_topology=True)
            if isinstance(geometry, shapely.geometry.multipolygon.MultiPolygon):
                polygons = geometry.geoms
            else:
                polygons = [geometry]
            path = ''
            for polygon in polygons:
                rings = []
                rings.append(polygon.exterior)
                rings.extend(polygon.interiors)
                for ring in rings:
                    for pointIndex in range(len(ring.coords)):
                        point = ring.coords[pointIndex]
                        if pointIndex == 0:
                            path += 'M' + str(round((point[0] - bbox[0]) / scale + left, self.precision))
                            path += ',' + str(round((bbox[3] - point[1]) / scale + top, self.precision))
                        else:
                            path += 'l' + str(
                                round(point[0] / scale - ring.coords[pointIndex - 1][0] / scale, self.precision))
                            path += ',' + str(
                                round(ring.coords[pointIndex - 1][1] / scale - point[1] / scale, self.precision))
                    path += 'Z'
            self.map.addPath(path, feature['code'], feature['name'])
        return bbox
示例#11
0
fd = ogr.FieldDefn( 'code', 4 )
fd.SetWidth( 5 )
shp_layer.CreateField( fd )

fd = ogr.FieldDefn( 'name', 4 )
fd.SetWidth( 254 )
shp_layer.CreateField( fd )

for region in regions:
  in_layer.SetAttributeFilter( region['where'] )
  geometries = []
  for feature in in_layer:
    geometry = feature.GetGeometryRef()
    if geometry.GetGeometryType() == ogr.wkbPolygon or geometry.GetGeometryType() == ogr.wkbMultiPolygon:
      geometry = shapely.wkb.loads( geometry.ExportToWkb() )
      geometry = geometry.buffer(0.000000001, 1)
      geometries.append( geometry )
  region['geometry'] = shapely.ops.cascaded_union( geometries )
  region['geometry'] = region['geometry'].buffer(-0.000000001, 1)
  in_layer.ResetReading()

for region in regions:
  out_feat = ogr.Feature( feature_def = shp_layer.GetLayerDefn() )
  out_feat.SetField(0, region['code'])
  out_feat.SetField(1, region['name'])
  out_feat.SetGeometryDirectly(
    ogr.CreateGeometryFromWkb(
      shapely.wkb.dumps(
        region['geometry']
      )
    )