Skip to content

Instantly share code, notes, and snippets.

@Goos
Last active August 25, 2021 23:45
Show Gist options
  • Save Goos/37fe27b073959dbc370f034816d6a9e7 to your computer and use it in GitHub Desktop.
Save Goos/37fe27b073959dbc370f034816d6a9e7 to your computer and use it in GitHub Desktop.
import sys, getopt, os
from osgeo import ogr, gdal
def main(argv):
inputfile = ''
outputfile = ''
point = ''
try:
opts, args = getopt.getopt(argv, "hi:o:p:", ["input=", "output=", "point="])
except getopt.GetoptError:
print('convert.py -i input.dxf -o output.geojson -p lat,lng')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print('convert.py -i input.dxf -o output.geojson -p lat,lng')
sys.exit()
elif opt in ("-i", "--input"):
inputfile = arg
elif opt in ("-o", "--output"):
outputfile = arg
elif opt in ("-p", "--point"):
point = arg
point_parts = point.split(",")
lng = float(point_parts[0])
lat = float(point_parts[1])
min_x, max_x, min_y, max_y = get_extent(inputfile)
aspect_ratio = (max_x - min_x) / (max_y - min_y)
reference_size = 0.001
input_bbox = {
'min_x': min_x,
'max_x': max_x,
'min_y': min_y,
'max_y': max_y
}
output_bbox = {
'min_x': lng - reference_size * aspect_ratio,
'max_x': lng + reference_size * aspect_ratio,
'min_y': lat - (reference_size / aspect_ratio),
'max_y': lat + reference_size / aspect_ratio
}
export_geojson(inputfile, outputfile, input_bbox, output_bbox)
def get_extent(inputfile):
gdal.SetConfigOption("DXF_FEATURE_LIMIT_PER_BLOCK", "-1")
datasource = ogr.Open(inputfile)
layer = datasource.GetLayer()
return layer.GetExtent()
def export_geojson(input_file, output_file, input_bbox, output_bbox):
command = """
ogr2ogr -f GeoJSON \
-gcp {input_min_x} {input_min_y} {output_min_x} {output_min_y} \
-gcp {input_max_x} {input_min_y} {output_max_x} {output_min_y} \
-gcp {input_min_x} {input_max_y} {output_min_x} {output_max_y} \
-gcp {input_max_x} {input_max_y} {output_max_x} {output_max_y} \
--config DXF_FEATURE_LIMIT_PER_BLOCK -1 \
{output_file} \
{input_file}
""".format(
input_file=input_file,
output_file=output_file,
input_min_x=input_bbox['min_x'],
input_max_x=input_bbox['max_x'],
input_min_y=input_bbox['min_y'],
input_max_y=input_bbox['max_y'],
output_min_x=output_bbox['min_x'],
output_max_x=output_bbox['max_x'],
output_min_y=output_bbox['min_y'],
output_max_y=output_bbox['max_y']
)
os.system(command)
if __name__ == "__main__":
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment