Skip to content

Instantly share code, notes, and snippets.

@mthh
Last active November 3, 2016 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mthh/e66536f5e3986f34bd6f20ea2f35430d to your computer and use it in GitHub Desktop.
Save mthh/e66536f5e3986f34bd6f20ea2f35430d to your computer and use it in GitHub Desktop.
Get Borders to GeoJSON
#### Get borders from TopoJSON polygons to GeoJSON MultiLineString.
-not tested in pure python (only in cython)
-the accuracy of the result may vary, depending in particular on the quantization used when converting to TopoJSON
cdef list get_comm(list arc_a, list arc_b):
cdef:
list comm = []
int aa, bb
for aa in flatten_arc(arc_a):
for bb in flatten_arc(arc_b):
if aa < 0:
aa = ~aa
if bb < 0:
bb = ~bb
if aa == bb:
comm.append(aa)
return comm
cdef list flatten_arc(list arcs):
cdef list res = []
for aa in arcs:
if isinstance(aa, list):
res.extend(aa)
else:
res.append(aa)
return res
cdef dict get_common_arcs(dict topojson):
cdef:
dict geom_a, geom_b, common_borders = {}
str layer_name = list(topojson['objects'].keys())[0]
list geoms = topojson['objects'][layer_name]['geometries']
list arcs_ref = topojson['arcs']
set seen = set()
str _id_arcs, _id_arcs_reverse
for geom_a in geoms:
for geom_b in geoms:
if geom_a["id"] != geom_b["id"]:
common_arcs = get_comm(geom_a["arcs"][0], geom_b["arcs"][0])
if common_arcs:
_id_arcs = "_".join([str(geom_a["id"]), str(geom_b["id"])])
_id_arcs_reverse = "_".join([str(geom_b["id"]), str(geom_a["id"])])
if not _id_arcs in seen and not _id_arcs_reverse in seen :
seen.add(_id_arcs)
common_borders[_id_arcs] = [arcs_ref[j] for j in common_arcs]
return common_borders
cpdef get_borders_to_geojson(dict topojson):
cdef:
list res_features = []
str feature_st = '''{"type":"Feature","geometry":{"type": "MultiLineString","coordinates":'''
str feature_middle = '''},"properties":{"id":"'''
str feature_end = '''"}}'''
dict common_borders = get_common_arcs(topojson)
for _id, geom in common_borders.items():
res_features.append("".join([feature_st, str(geom), feature_middle, str(_id), feature_end]))
return "".join([
'''{"type":"FeatureCollection","features":[''',
','.join(res_features),
''']}'''
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment