-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgeo.py
73 lines (55 loc) · 2.32 KB
/
geo.py
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
import pandas as pd
import geopandas as gpd
import base64
from shapely.geometry import LineString, MultiLineString, Point
import numpy as np
def add_ids(gdf, index_list, labels_col, tolerance=0):
geo_names = list(gdf[str(labels_col)])
geojson = {'type': 'FeatureCollection', 'features': []}
for index in index_list:
geo = gdf['geometry'][index].simplify(tolerance)
if isinstance(geo.boundary, LineString):
gtype = 'Polygon'
bcoords = np.dstack(geo.boundary.coords.xy).tolist()
elif isinstance(geo.boundary, MultiLineString):
gtype = 'MultiPolygon'
bcoords = []
for b in geo.boundary:
x, y = b.coords.xy
coords = np.dstack((x, y)).tolist()
bcoords.append(coords)
else:
pass
feature = {'type': 'Feature',
'id': index,
'properties': {'name': geo_names[index]},
'geometry': {'type': gtype,
'coordinates': bcoords},
}
geojson['features'].append(feature)
return geojson
def parse_geojson(contents, filename):
try:
if 'geojson' in filename:
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
try:
geojson = decoded.decode("utf-8")
geodf = gpd.read_file(geojson, encoding="utf-8")
geodf['geometry'] = geodf['geometry'].astype(str)
except Exception as e:
geojson = decoded.decode("ISO-8859-1")
geodf = gpd.read_file(geojson, encoding="ISO-8859-1")
geodf['geometry'] = geodf['geometry'].astype(str)
except Exception as e:
print(e)
return print('There was an error processing this file.')
data = geodf.to_dict('records')
columns = [{'name': i, 'id': i} for i in geodf.columns]
return columns, data
def spatial_join(cluster_df, lon, lat, geojson_df):
cluster_df['geometry'] = [Point(x, y) for x, y in zip(cluster_df[lon], cluster_df[lat])]
points_geo = gpd.GeoDataFrame(cluster_df, geometry='geometry')
geojson_geo = gpd.GeoDataFrame(geojson_df, geometry='geometry')
spjoin = gpd.sjoin(points_geo, geojson_geo)
return spjoin