数据格式:
代码片段:
# coding: utf-8
import os
import arcpy
import json
import sys
def set_encoding():
a, b, c = sys.stdin, sys.stdout, sys.stderr
reload(sys)
sys.setdefaultencoding('utf-8')
sys.stdin, sys.stdout, sys.stderr = a, b, c
def get_files(root):
files = os.listdir(root)
return files
def create_feature(root, workspace, sp_ref):
temp_dic_root, database = get_path(workspace)
temp_dic = os.path.join(temp_dic_root, "temp_data")
if not os.path.exists(temp_dic):
os.makedirs(temp_dic)
for sourcefile in get_files(root):
if not sourcefile.endswith(".txt"):
continue
filename = os.path.splitext(sourcefile)[0]
out_file = workspace + "\\v_" + filename
jsonfile = os.path.join(temp_dic, filename + ".json")
sourcefile = root + "\\" + sourcefile
coordinates = analysis(sourcefile)
if create_geojson(jsonfile, coordinates, sp_ref):
arcpy.JSONToFeatures_conversion(jsonfile, out_file)
arcpy.AddMessage("info: " + filename)
else:
arcpy.AddWarning("waring: " + filename)
def create_geojson(targetfile, coordinates, sp_ref):
features_template = {
"displayFieldName": "",
"fieldAliases": {
"FID": "FID"
},
"geometryType": "esriGeometryPolygon",
"spatialReference": {
"wkt": ""
},
"fields": [
{
"name": "FID",
"type": "esriFieldTypeOID",
"alias": "FID"
}
],
"features": [
]
}
features_template["spatialReference"]["wkt"] = sp_ref
for fid, item in enumerate(coordinates):
features_template["features"].append(get_geometry(fid, item))
with open(targetfile, "w") as out_file:
out_file.write(json.dumps(features_template))
return True
def get_geometry(fid, rings):
feature_template = {
"attributes": {
"FID": 0
}, "geometry": {
"rings": [
]
}
}
feature_template["attributes"]["FID"] = fid
temp = [ring for index, ring in rings.items()]
feature_template["geometry"]["rings"].extend(temp)
return feature_template
def analysis(sourcefile):
geometry = []
rings = {}
with open(sourcefile, "r") as in_file:
line = in_file.readline()
while line:
flag1 = "@" in line.replace("\n", "").split(",")
flag2 = line.startswith("J")
if not (flag1 or flag2):
line = in_file.readline()
continue
if flag1:
geometry.append(rings)
rings = {}
elif flag2:
temp = line.split(",")
ring_index = temp[1]
ring_part = list(map(float, reversed(temp[2:])))
if not rings.has_key(ring_index):
rings[ring_index] = []
rings[ring_index].append(ring_part)
line = in_file.readline()
geometry.append(rings)
geometry.pop(0)
return geometry
def get_path(path):
temps = path.split('\\')
result = []
if '.' in temps[-1]:
root = "\\".join(temps[0:-1])
result.append(root)
result.append(temps[-1])
return result
if __name__ == "__main__":
set_encoding()
root = arcpy.GetParameterAsText(0)
workspace = arcpy.GetParameterAsText(1)
sp_ref = arcpy.GetParameterAsText(2)
sp_ref = sp_ref.replace("\'", "\"")
create_feature(root, workspace, sp_ref)
工具参数:
工具界面: