From baf0898dfda49d2222ba5a29d8918a0ff5bb37bb Mon Sep 17 00:00:00 2001 From: Guilhem Moulin Date: Tue, 11 Jun 2024 04:19:47 +0200 Subject: webmap-import: Add geometry conversion support. --- webmap-import | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/webmap-import b/webmap-import index 3242b3a..adfc0cf 100755 --- a/webmap-import +++ b/webmap-import @@ -960,13 +960,15 @@ def importSource2(lyr_dst, path, args={}, basedir=None, extent=None): defn_dst = lyr_dst.GetLayerDefn() eGType_dst = defn_dst.GetGeomType() + eGType_dst_HasZ = ogr.GT_HasZ(eGType_dst) + eGType_dst_HasM = ogr.GT_HasM(eGType_dst) + dGeomIsUnknown = ogr.GT_Flatten(eGType_dst) == ogr.wkbUnknown n = 0 - #mismatch = 0 + mismatch = {} feature = lyr.GetNextFeature() while feature is not None: feature2 = ogr.Feature(defn_dst) - # TODO MakeValid, force geometry, dimension feature2.SetFromWithMap(feature, False, fieldMap) geom = feature2.GetGeometryRef() @@ -974,22 +976,37 @@ def importSource2(lyr_dst, path, args={}, basedir=None, extent=None): raise Exception('Could not apply coordinate transformation') eGType = geom.GetGeometryType() - if eGType != eGType_dst: - if eGType == ogr.wkbPolygon and eGType_dst == ogr.wkbMultiPolygon: - geom = ogr.ForceToMultiPolygon(geom) + if eGType != eGType_dst and not dGeomIsUnknown: + # Promote to multi, cf. apps/ogr2ogr_lib.cpp:ConvertType() + eGType2 = eGType + if eGType == ogr.wkbTriangle or eGType == ogr.wkbTIN or eGType == ogr.wkbPolyhedralSurface: + eGType2 = ogr.wkbMultiPolygon + elif not ogr.GT_IsSubClassOf(eGType, ogr.wkbGeometryCollection): + eGType2 = ogr.GT_GetCollection(eGType) + + eGType2 = ogr.GT_SetModifier(eGType2, eGType_dst_HasZ, eGType_dst_HasM) + if eGType2 == eGType_dst: + mismatch[eGType] = mismatch.get(eGType, 0) + 1 + geom = ogr.ForceTo(geom, eGType_dst) + # TODO call MakeValid()? else: - raise Exception('Not implemented') + raise Exception(f'Conversion from {ogr.GeometryTypeToName(eGType)} ' + f'to {ogr.GeometryTypeToName(eGType_dst)} not implemented') feature2.SetGeometryDirectly(geom) - #mismatch += 1 lyr_dst.CreateFeature(feature2) n += 1 feature = lyr.GetNextFeature() - #print(mismatch) lyr = None logging.info('Imported %d features from source layer "%s"', n, layername) + if len(mismatch) > 0: + mismatches = [ ogr.GeometryTypeToName(t) + ' (×' + str(n) + ')' + for t,n in sorted(mismatch.items(), key=lambda x: x[1]) ] + logging.info('Forced conversion to %s: %s', + ogr.GeometryTypeToName(eGType_dst), ', '.join(mismatches)) + if __name__ == '__main__': logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO) -- cgit v1.2.3