Created
September 17, 2013 22:58
-
-
Save carlosefonseca/6601839 to your computer and use it in GitHub Desktop.
Converts WKT to KML.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding=utf-8 | |
import sys | |
import re | |
import simplekml | |
import argparse | |
import random | |
def splitByLines(wkt): | |
return re.findall(r"LINESTRING\(([^)]*)", wkt) | |
def getAColor(): | |
r = lambda: random.randint(0,255) | |
r() | |
return '#FF{:02X}{:02X}{:02X}'.format(r(),r(),r()) | |
def createKMLLines(lines, colors): | |
kml = simplekml.Kml() | |
for idx,l in enumerate(lines): | |
splitted = re.findall(r"[^ ,]+", l) | |
spl = [float(i) for i in splitted] | |
coords = zip(splitted[::2],splitted[1::2]) | |
ls = kml.newlinestring(name='Line '+str(idx)) | |
ls.coords = coords | |
if colors: | |
ls.style.linestyle.color = getAColor() | |
ls.style.linestyle.width= 4 | |
return kml | |
# Argument Parser | |
parser = argparse.ArgumentParser(description='Converter of WKT\'s linestrings to KML') | |
parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),default=sys.stdin) | |
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),default=sys.stdout) | |
parser.add_argument('-c','--colors', action='store_true', help='add random colors to the lines for easy differentiation') | |
args = parser.parse_args() | |
wkt = args.infile.read() | |
lines = splitByLines(wkt) | |
kml = createKMLLines(lines, args.colors) | |
args.outfile.write(kml.kml()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment