-
Notifications
You must be signed in to change notification settings - Fork 1
/
wkt2ogr
executable file
·70 lines (64 loc) · 2.22 KB
/
wkt2ogr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env bash
PROGRAM_NAME=$(basename "$0")
INPUT_FILE=${1:--}
INPUT_SRS=${2}
FORMAT=${3}
OUTPUT_FILE=${4}
LAYERNAME=${5}
function usage {
echo "Convert WKT objects to fileformat supported by OGR/GDAL. Requires ogr2ogr and gdalsrsinfo binary to be available in PATH"
echo ""
echo "usage: $PROGRAM_NAME <wkt_file|-(wkt objects on stdin)> <input_srs> <output_format> <output_file> <layername>"
echo " - <wkt_file|-(wkt objects on stdin>: file containing wkt geometries or pass wkt objects on stdin"
echo " - <input_srs>: epsg code of input data"
echo " - <output_format>: ogr2ogr output format"
echo " - <output_file>: destination file"
echo " - <layername>: layername in output file"
exit 1
}
if [ "$#" -ne 5 ]; then
usage
fi
set -euo pipefail
VRT_STRING="<OGRVRTDataSource>
<OGRVRTLayer name=\"wkt_convert\">
<SrcDataSource>/tmp/wkt_convert.csv</SrcDataSource>
<GeometryType>wkbPolygon</GeometryType>
<LayerSRS>{{input_srs}}</LayerSRS>
<GeometryField encoding=\"WKT\" field=\"wkt\"></GeometryField >
</OGRVRTLayer>
</OGRVRTDataSource>"
CSV_FILE="/tmp/wkt_convert.csv"
function process_wkt_strings() {
local wkt_strings format output_file layername input_srs
wkt_strings="$1"
input_srs="$2"
format="$3"
output_file="$4"
layername="$5"
echo "id,wkt" >$CSV_FILE
i=0
while IFS= read -r wkt_string; do
echo "$i,\"$wkt_string\"" >>$CSV_FILE
i=$((i + 1))
done <<<"$wkt_strings"
SRS_WKT=$(gdalsrsinfo "EPSG:$input_srs" -o WKT)
SRS_WKT=${SRS_WKT/\"/\\\"}
VRT_STRING=${VRT_STRING/\{\{input_srs\}\}/$SRS_WKT}
echo "$VRT_STRING" >/tmp/ogr.vrt
rm -f "$output_file"
tmp_name="/tmp/$(uuidgen)-($(basename "$output_file")"
ogr2ogr -f "$format" "$tmp_name" /tmp/ogr.vrt -nln "$layername" wkt_convert
ogr2ogr -f "$format" "$output_file" "$tmp_name" -sql "select geom from $layername" -nln "$layername"
}
if [[ $INPUT_FILE == "-" ]]; then
# INPUT_FILE passed on stdin
if [ -t 0 ]; then
# if do not allow interactive tty
usage
fi
WKT_STRINGS=$(</dev/stdin)
else
WKT_STRINGS=$(<"$INPUT_FILE")
fi
process_wkt_strings "$WKT_STRINGS" "$INPUT_SRS" "$FORMAT" "$OUTPUT_FILE" "$LAYERNAME"