Select to view content in your preferred language

# Best way to coerce multi-geometry to single for WKT use

516
1
06-07-2022 10:43 AM
Occasional Contributor III

Not sure if "what's the best way" questions are frowned on, but before I burn a bunch of cycles fixing this, I figured there might be a capability buried in ArcPy that I'm missing.

I'm attempting to get WKT of what appears to be a simple line feature in ArcGIS Pro.

When I use the SHAPE@WKT token to call it, it returns as

MULTILINESTRING Z ((10.0 20.0 0, 11.0 21.0 0,...))

I would like to return the feature as

LINESTRING((10.0 20.0,11.0 21.0,12.0 22.0,...))

as I am issuing these geometries as query criteria to various web services that are looking for simple OGC WKT.

Is there preprocessing available to me to ensure the SHAPE@WKT returns as a LINESTRING or POLYGON without Z, vs. MULTILINESTRING or MULTIPOLYGON?  I can brute force this with re patterns and a dictionary of replacements, but I was hoping for something slicker and more idiomatically "esri."

Tags (1)
Occasional Contributor III

Here's the super duct tapey way I handle this now, by the way:

``````import arcpy
import re

def get_wkts(self, lyr):
# This is part of a larger python toolbox class
wkts = []
with_z = r"(\d+\.\d+) (\d+.\d+) (\d+,?)"
without_z = r"(\d+.\d+) (\d+.\d+,?)"
typemap = {
"MULTILINESTRING (": ["LINESTRING", without_z, "((", "))"],
"MULTILINESTRING Z (": ["LINESTRING", with_z, "((", "))"],
"MULTIPOLYGON (": ["POLYGON", without_z, "(((", ")))"],
"MULTIPOLYGON Z (": ["POLYGON", with_z, "(((", ")))"],
"POINT (": ["POINT", without_z, "(", ")"],
"POINT Z (": ["POINT", with_z, "(", ")"]
}

with arcpy.da.SearchCursor(lyr, ["SHAPE@WKT"]) as cur:
for row in cur:
for k, v in typemap.items():
if row[0].startswith(k):
wkt_prefix = v[0]
coords = v[2] + ",".join([str(f[0] + " " + f[1]) for f in re.findall(v[1], row[0])]) + v[3]
wkts.append(wkt_prefix + coords)
return wkts``````