def update_output(value): if value != None: w1 = keplergl.KeplerGl(height=500) w1.add_data(json_data, 'geojson') w1.save_to_html(file_name='assets/Lets_try.html') return html.Div([ html.Iframe(src=dash_app.get_asset_url("Lets_try.html"), width=1800, height=500) ]) else: w1 = keplergl.KeplerGl(height=500) w1.add_data(json_data, 'geojson') w1.save_to_html(file_name='assets/Lets_try.html') return html.Div([ html.Iframe(src=dash_app.get_asset_url("Lets_try.html"), width=1800, height=500) ])
def kepler_viz(link_df, name, title="", config=None): if title == "": title = name if config: kmap = keplergl.KeplerGl(height=400, data={name: link_df}, config=config) else: kmap = keplergl.KeplerGl(height=400, data={name: link_df}) kmap.save_to_html(file_name=f"{title}.html")
def draw_layers_kepler(hexagons_gdf, layers_dict): map_kepler = keplergl.KeplerGl(height=800) for layer_name, geo in layers_dict.items(): map_kepler.add_data(geo, name=layer_name) map_kepler.add_data(data=hexagons_gdf[["geometry"]], name="hexagons") return map_kepler
def make_kepler_plot(conn): q = conn.runInstalledQuery("getAllTravel") df = pd.json_normalize(q[0]['Seed']) # print(df) map_1 = keplergl.KeplerGl() map_1.add_data(data=df, name='covid') map_1.config = config map_1.save_to_html(file_name="covid_map.html")
def generateKeplerMap(): q = conn.runInstalledQuery("getAllTravel") df = pd.json_normalize(q[0]['Seed']) # print(df) map_1 = keplergl.KeplerGl() map_1.add_data(data=df) if not os.path.isfile('Dash-Bootstrap-TigerGraph-Covid19/covid_map.html'): map_1.save_to_html(file_name="covid_map.html") else: os.remove('Dash-Bootstrap-TigerGraph-Covid19/covid_map.html') map_1.save_to_html(file_name="covid_map.html") kep_viz = html.Iframe(srcDoc=open('covid_map.html').read(), height='800', width='100%') return kep_viz
def plot_geodataframes_on_kepler_map(gdfs: Dict[str, gpd.GeoDataFrame], height=750, kepler_config=None): """ Plots geodataframes on a kepler map. :param gdfs: {'gdf name': gdf} dictionary of geodataframes :param height: optional, height for the kepler map :param kepler_config: optional, dict kepler config or one of the keys in the predefined configs in KEPLER_CONFIGS :return: """ if kepler_config in KEPLER_CONFIGS: kepler_config = KEPLER_CONFIGS[kepler_config] elif isinstance(kepler_config, dict): kepler_config = kepler_config else: kepler_config = {} return keplergl.KeplerGl(data=gdfs, height=height, config=kepler_config)
} } } # Cut the data in half # overall_map = keplergl.KeplerGl(height=400, # data={"all_roads": overall_links.loc[:, ['roadType', 'x1', 'y1', 'x2', 'y2']]}, # config=map_config) # overall_map.save_to_html(file_name="combined_roads.html") filename = "data/roadNetwork-Directed-TokyoArea-v5.json" with open(filename, encoding='utf-8-sig') as f: js_graph = json.load(f) elevation_small_roads = pd.DataFrame( js_graph['links'] ).loc[:, ['x1', 'y1', 'x2', 'y2', 'elevationGain', 'timeWeight', 'roadType']] elevation_nodes = pd.DataFrame( js_graph['nodes']).loc[:, ['id', 'lat', 'lon', 'elevation']] kmap = keplergl.KeplerGl( height=400, # # data={'green_data': green_data}) # # data={'elevation_data': elevation_data}) # data={'elevation_links': links, 'elevation_nodes': nodes}) data={ 'elevation_small_roads': elevation_small_roads, 'elevation_nodes': elevation_nodes }) kmap.save_to_html(file_name="elevation_gains.html")
"building": True, "water": True }, "threeDBuildingColor": [224.4071295378559, 224.4071295378559, 224.4071295378559], "mapStyles": { "uafryn": { "accessToken": "pk.eyJ1Ijoic2h1dG9hcmFraSIsImEiOiJja2F4bGpwZGgwMXdoMnNwaTZwNzZ1N2ozIn0.4MK9evmXh1eQPTUauJQbMg", "custom": True, "icon": "https://api.mapbox.com/styles/v1/shutoaraki/ckaxlks630p1s1ilbdw4i26no/static/-122.3391,37.7922,9,0,0/400x300?access_token=pk.eyJ1Ijoic2h1dG9hcmFraSIsImEiOiJja2F4bGpwZGgwMXdoMnNwaTZwNzZ1N2ozIn0.4MK9evmXh1eQPTUauJQbMg&logo=false&attribution=false", "id": "uafryn", "label": "Shuto's Classic", "url": "mapbox://styles/shutoaraki/ckaxlks630p1s1ilbdw4i26no" } } } } } kmap = keplergl.KeplerGl(height=400, data={ 'chome_master_data': chome_df, 'hex_master_data': hex_df, 'elevation_data': elevation_df }, config=map_config) kmap.save_to_html(file_name="elevation_map.html")
def services_to_kepler(): ##setting about kubernetes client config.load_kube_config() v1 = client.CoreV1Api() pod = v1.list_pod_for_all_namespaces(watch=False) namespace_list = v1.list_namespace() svc = v1.list_service_for_all_namespaces(watch=False) ##get elasticsearch URL for i in svc.items: if i.metadata.name == 'elasticsearch': elasticIp = i.spec.cluster_ip + ':9200' ##get nodes and location ##sol 1) from ipstack api (latitude, longitude) -> node_dict # node = v1.list_node(watch=False) # node_dict = {} # for i in node.items: # adds = i.status.addresses # InternalIP = adds[0].address # hostname = adds[1].address # print(hostname) # url = "http://api.ipstack.com/"+InternalIP+"?access_key={YOUR_API_KEY}" # result = json.loads(requests.get(url).text) # node_dict[hostname+'_lat'] = result['latitude'] # node_dict[hostname+'_lng'] = result['longitude'] # print(result['latitude'],result['longitude']) ##sol 2) write your nodes and location below node_dict = {} node_dict['netcs-quantagrid-d52g-4u'+'_lat'] = 35.229247 node_dict['netcs-quantagrid-d52g-4u'+'_lng'] = 126.84459686279297 node_dict['netcs-virtual-machine'] = 35.229581 node_dict['netcs-virtual-machine'] = 126.847718 ### save services' communication information from elasticsearch to info.csv csv_columns = ['@timestamp', 'source', 'srcnamespace', 'destination', 'latency', 'desnamespace', 'severity','tag','responseCode','user','responseSize', ] csv_file = './info.csv' es = Elasticsearch(hosts=elasticIp) data = es.indices.get_alias("*") for k in data.keys(): if k != '.kibana': data = es.search(index=k, size=10000, body={"query": {"match_all":{}}}) with open(csv_file,'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=csv_columns) for document in [x['_source'] for x in data['hits']['hits']]: writer.writerow(document) ### get 'services by namespace' from info.csv f = open('info.csv', 'r', encoding='utf-8') rdr = csv.reader(f) for i in namespace_list.items: kepler_file_name = './Kepler/Kepler-csvfiles/kepler_' + i.metadata.name + '.csv' with open(kepler_file_name, 'w') as csvfile1: wtr1 = csv.writer(csvfile1) wtr1.writerow(['node1_lat','node1_lng','node1','p1','node2_lat','node2_lng','node2','p2','duration','timestamp']) for line in rdr: time_stamp = line[0] p1 = line[1] p2 = line[3] duration = line[4] src_namespace = line[2] des_namespace = line[5] node1 = "" node2 = "" if time_stamp == 'unknown' or p1 == 'unknown' or p2 == 'unknown' or src_namespace == 'unknown' or des_namespace == 'unknown': continue for i in pod.items: if p1 == i.metadata.name: node1 = i.spec.node_name if p2 == i.metadata.name: node2 = i.spec.node_name if src_namespace == des_namespace: kepler_file_name = './Kepler/Kepler-csvfiles/kepler_' + src_namespace + '.csv' else: if src_namespace == 'istio-system' or des_namespace == 'istio-system': kepler_file_name = './Kepler/Kepler-csvfiles/kepler_istio-system.csv' else: continue with open(kepler_file_name, 'a', newline = '') as csvfile: node1_lat = "" node1_lng = "" node2_lat = "" node2_lng = "" wtr = csv.writer(csvfile) a = 0 if node1+'_lat' in node_dict: node1_lat = node_dict[node1+'_lat'] else: a = 1 if node1+'_lat' in node_dict: node1_lng = node_dict[node1+'_lng'] else: a = 1 if node2+'_lat' in node_dict: node2_lat = node_dict[node2+'_lat'] else: a = 1 if node2+'_lat' in node_dict: node2_lng = node_dict[node2+'_lng'] else: a = 1 if a != 1: wtr.writerow([node1_lat,node1_lng,node1,p1,node2_lat,node2_lng,node2,p2,duration,time_stamp]) f.close() ### Kepler config (you can change kepler config) kepler_config = {'version': 'v1', 'config': {'visState': {'filters': [{'dataId': 'data_1', 'id': 'uisb16gma', 'name': 'time_stamp', 'type': 'timeRange', 'value': [1585094781038, 1585094781538], 'enlarged': True, 'plotType': 'histogram', 'yAxis': None}], 'layers': [{'id': '9rm0hg', 'type': 'point', 'config': {'dataId': 'data_1', 'label': 'node1', 'color': [14, 112, 119], 'columns': {'lat': 'node1_lat', 'lng': 'node1_lng', 'altitude': None}, 'isVisible': True, 'visConfig': {'radius': 10, 'fixedRadius': False, 'opacity': 0.8, 'outline': False, 'thickness': 2, 'strokeColor': None, 'colorRange': {'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']}, 'strokeColorRange': {'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']}, 'radiusRange': [0, 50], 'filled': True}, 'textLabel': [{'field': {'name': 'p1', 'type': 'string'}, 'color': [255, 255, 255], 'size': 18, 'offset': [0, 0], 'anchor': 'start', 'alignment': 'center'}]}, 'visualChannels': {'colorField': None, 'colorScale': 'quantile', 'strokeColorField': None, 'strokeColorScale': 'quantile', 'sizeField': None, 'sizeScale': 'linear'}}, {'id': '52mxpob', 'type': 'point', 'config': {'dataId': 'data_1', 'label': 'node2', 'color': [18, 92, 119], 'columns': {'lat': 'node2_lat', 'lng': 'node2_lng', 'altitude': None}, 'isVisible': True, 'visConfig': {'radius': 10, 'fixedRadius': False, 'opacity': 0.8, 'outline': False, 'thickness': 2, 'strokeColor': None, 'colorRange': {'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']}, 'strokeColorRange': {'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']}, 'radiusRange': [0, 50], 'filled': True}, 'textLabel': [{'field': {'name': 'duration_str', 'type': 'string'}, 'color': [255, 254, 230], 'size': 18, 'offset': [0, 0], 'anchor': 'start', 'alignment': 'top'}, {'field': {'name': 'p2', 'type': 'string'}, 'color': [255, 255, 255], 'size': 18, 'offset': [0, 0], 'anchor': 'start', 'alignment': 'center'}]}, 'visualChannels': {'colorField': None, 'colorScale': 'quantile', 'strokeColorField': None, 'strokeColorScale': 'quantile', 'sizeField': None, 'sizeScale': 'linear'}}, {'id': 'ld5iezk', 'type': 'arc', 'config': {'dataId': 'data_1', 'label': 'node1 -> node2 arc', 'color': [255, 254, 230], 'columns': {'lat0': 'node1_lat', 'lng0': 'node1_lng', 'lat1': 'node2_lat', 'lng1': 'node2_lng'}, 'isVisible': True, 'visConfig': {'opacity': 0.8, 'thickness': 7, 'colorRange': {'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']}, 'sizeRange': [0, 10], 'targetColor': [87, 136, 46]}, 'textLabel': [{'field': None, 'color': [255, 255, 255], 'size': 18, 'offset': [0, 0], 'anchor': 'start', 'alignment': 'center'}]}, 'visualChannels': {'colorField': None, 'colorScale': 'quantile', 'sizeField': None, 'sizeScale': 'linear'}}, {'id': 'kcsigvh', 'type': 'line', 'config': {'dataId': 'data_1', 'label': 'node1 -> node2 line', 'color': [77, 193, 156], 'columns': {'lat0': 'node1_lat', 'lng0': 'node1_lng', 'lat1': 'node2_lat', 'lng1': 'node2_lng'}, 'isVisible': False, 'visConfig': {'opacity': 0.8, 'thickness': 2, 'colorRange': {'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']}, 'sizeRange': [0, 10], 'targetColor': None}, 'textLabel': [{'field': None, 'color': [255, 255, 255], 'size': 18, 'offset': [0, 0], 'anchor': 'start', 'alignment': 'center'}]}, 'visualChannels': {'colorField': None, 'colorScale': 'quantile', 'sizeField': None, 'sizeScale': 'linear'}}], 'interactionConfig': {'tooltip': {'fieldsToShow': {'data_1': ['node1', 'p1', 'node2', 'p2', 'pro_namespace']}, 'enabled': True}, 'brush': {'size': 0.5, 'enabled': False}}, 'layerBlending': 'normal', 'splitMaps': [], 'animationConfig': {'currentTime': None, 'speed': 1}}, 'mapState': {'bearing': 11.94979079497908, 'dragRotate': True, 'latitude': 35.22821027516838, 'longitude': 126.84184175512864, 'pitch': 58.88625196338873, 'zoom': 13.94183054311009, 'isSplit': False}, 'mapStyle': {'styleType': 'dark', 'topLayerGroups': {}, 'visibleLayerGroups': {'label': True, 'road': True, 'border': False, 'building': True, 'water': True, 'land': True, '3d building': False}, 'threeDBuildingColor': [9.665468314072013, 17.18305478057247, 31.1442867897876], 'mapStyles': {}}}} ### draw map through kepler.gl and save_to_html for i in namespace_list.items: kepler_file_name = './Kepler/Kepler-csvfiles/kepler_' + i.metadata.name + '.csv' kepler_html_filename = './templates/kepler_'+i.metadata.name+'.html' df = pd.read_csv(kepler_file_name) w2 = keplergl.KeplerGl(height = 600,data={'data_1':df},config = kepler_config) w2.save_to_html(file_name=kepler_html_filename)
# Make plot fig = px.choropleth_mapbox(ubc, geojson=ubc.geometry, locations=ubc.index, color="Area", center={"lat": 49.261, "lon": -123.246}, zoom=12.5, mapbox_style="carto-positron") fig.update_layout(margin=dict(l=0, r=0, t=30, b=10)) Check out the `plotly` [documentation](https://plotly.com/python/maps/) for more - there are many plotting options and examples to learn from! Other popular map plotting options include [altair](https://altair-viz.github.io/gallery/index.html#maps) ([doesn't support interactivity yet](https://github.com/vega/vega-lite/issues/3306)), [folium](https://python-visualization.github.io/folium/), and [bokeh](https://docs.bokeh.org/en/latest/docs/user_guide/geo.html). ### 1.3. Kepler.gl The above mapping was pretty cool, but are you ready for more power? ![](img/thanos.gif) Time to introduce [kepler.gl](https://docs.kepler.gl/)! `keplergl` is a web-based tool for visualing spatial data. Luckily, it has a nice Python API and Jupyter extension for us to use (see the [install instructions](https://docs.kepler.gl/docs/keplergl-jupyter#install)). The basic way `keplergl` works is: 1. We create an instance of a map with `keplergl.KeplerGl()` 2. We add as much data to the map as we like with the `.add_data()` method 3. We customize and configure the map in any way we like using the GUI (graphical user interface) ubc_map = keplergl.KeplerGl(height=500) ubc_map.add_data(data=ubc.copy(), name="Building heights") ubc_map %%html <iframe src="../_images/ubc-2d.html" width="80%" height="500"></iframe> I'll do you one better than that! Let's add a 3D element to our plot! I'm going to load in some data of UBC building heights I downloaded from the [City of Vancouver Open Data Portal](https://opendata.vancouver.ca/explore/dataset/building-footprints-2009/information/): ubc_bldg_heights = gpd.read_file("data-spatial/ubc-building-footprints-2009") ubc_bldg_heights.head()
def create(row, odf): config = { 'version': 'v1', 'config': { 'visState': { 'filters': [], 'layers': [{ 'id': '8m7d8xn', 'type': 'geojson', 'config': { 'dataId': 'shop_loc', 'label': 'shop_loc', 'color': [195, 208, 57], 'columns': { 'geojson': '_geojson' }, 'isVisible': True, 'visConfig': { 'opacity': 0.95, 'thickness': 0.5, 'strokeColor': None, 'colorRange': { 'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': [ '#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300' ] }, 'strokeColorRange': { 'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': [ '#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300' ] }, 'radius': 10, 'sizeRange': [0, 10], 'radiusRange': [0, 50], 'heightRange': [0, 500], 'elevationScale': 5, 'stroked': False, 'filled': True, 'enable3d': False, 'wireframe': False }, 'textLabel': [{ 'field': None, 'color': [255, 255, 255], 'size': 18, 'offset': [0, 0], 'anchor': 'start', 'alignment': 'center' }] }, 'visualChannels': { 'colorField': None, 'colorScale': 'quantile', 'sizeField': None, 'sizeScale': 'linear', 'strokeColorField': None, 'strokeColorScale': 'quantile', 'heightField': None, 'heightScale': 'linear', 'radiusField': None, 'radiusScale': 'linear' } }, { 'id': 'njmuyyv', 'type': 'geojson', 'config': { 'dataId': 'shop_delivery_area', 'label': 'shop_delivery_area', 'color': [254, 137, 26], 'columns': { 'geojson': '_geojson' }, 'isVisible': True, 'visConfig': { 'opacity': 0.24, 'thickness': 0.5, 'strokeColor': [130, 154, 227], 'colorRange': { 'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': [ '#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300' ] }, 'strokeColorRange': { 'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': [ '#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300' ] }, 'radius': 10, 'sizeRange': [0, 10], 'radiusRange': [0, 50], 'heightRange': [0, 500], 'elevationScale': 5, 'stroked': True, 'filled': True, 'enable3d': False, 'wireframe': False }, 'textLabel': [{ 'field': None, 'color': [255, 255, 255], 'size': 18, 'offset': [0, 0], 'anchor': 'start', 'alignment': 'center' }] }, 'visualChannels': { 'colorField': None, 'colorScale': 'quantile', 'sizeField': None, 'sizeScale': 'linear', 'strokeColorField': None, 'strokeColorScale': 'quantile', 'heightField': None, 'heightScale': 'linear', 'radiusField': None, 'radiusScale': 'linear' } }, { 'id': 'r0tp09r', 'type': 'hexagon', 'config': { 'dataId': 'heatmap', 'label': 'user', 'color': [30, 150, 190], 'columns': { 'lat': 'user_latitude', 'lng': 'user_longitude' }, 'isVisible': True, 'visConfig': { 'opacity': 0.8, 'worldUnitSize': 0.05, 'resolution': 8, 'colorRange': { 'name': 'ColorBrewer Reds-6', 'type': 'singlehue', 'category': 'ColorBrewer', 'colors': [ '#fee5d9', '#fcbba1', '#fc9272', '#fb6a4a', '#de2d26', '#a50f15' ] }, 'coverage': 1, 'sizeRange': [0, 500], 'percentile': [0, 100], 'elevationPercentile': [0, 100], 'elevationScale': 5, 'colorAggregation': 'sum', 'sizeAggregation': 'count', 'enable3d': False }, 'textLabel': [{ 'field': None, 'color': [255, 255, 255], 'size': 18, 'offset': [0, 0], 'anchor': 'start', 'alignment': 'center' }] }, 'visualChannels': { 'colorField': { 'name': 'value', 'type': 'integer' }, 'colorScale': 'quantile', 'sizeField': None, 'sizeScale': 'linear' } }], 'interactionConfig': { 'tooltip': { 'fieldsToShow': { 'shop_delivery_area': [], 'shop_loc': [], 'heatmap': ['tracking_id', 'value'] }, 'enabled': True }, 'brush': { 'size': 0.5, 'enabled': False } }, 'layerBlending': 'normal', 'splitMaps': [], 'animationConfig': { 'currentTime': None, 'speed': 1 } }, 'mapState': { 'bearing': 0, 'dragRotate': False, 'latitude': 25.046293545256706, 'longitude': 102.68942390403629, 'pitch': 0, 'zoom': 12.65144314957595, 'isSplit': False }, 'mapStyle': { 'styleType': 'dark', 'topLayerGroups': {}, 'visibleLayerGroups': { 'label': True, 'road': True, 'border': False, 'building': True, 'water': True, 'land': True, '3d building': False }, 'threeDBuildingColor': [9.665468314072013, 17.18305478057247, 31.1442867897876], 'mapStyles': {} } } } shopmap = keplergl.KeplerGl(height=800) shopmap.config = config shopmap.add_data(data=geopandas.GeoSeries([Polygon(row['polygon_points']) ]).to_json(), name='shop_delivery_area') shopmap.add_data(data=geopandas.GeoSeries( [MultiPoint(row['shop_lnglat_group'])]).to_json(), name='shop_loc') shopmap.add_data(data=odf, name='heatmap') hl.update(row['shop_id_set'].encode(encoding='utf-8')) shopmap.save_to_html(file_name='html/' + hl.hexdigest() + '.html')
import json import numpy as np import pandas as pd import keplergl from helpers.helperFunctions import readJSON map_config = readJSON("ultimateMapConfig.json") filename = "data/roadNetwork-combined-v6.json" with open(filename, encoding='utf-8-sig') as f: js_graph = json.load(f) links = pd.DataFrame( js_graph['links'] ).loc[:, ['x1', 'y1', 'x2', 'y2', 'elevationGain', 'roadType', 'capacity']] nodes = pd.DataFrame(js_graph['nodes']).loc[:, ['id', 'lat', 'lon', 'elevation']] kmap = keplergl.KeplerGl(height=400, data={ 'Links': links, 'Nodes': nodes }, config=map_config) kmap.save_to_html(file_name="ultimate_roads.html")
def make_kepler_plot(): map_data = pd.read_csv("data.csv") map_1 = keplergl.KeplerGl() map_1.add_data(data=map_data) map_1.save_to_html(file_name="map_test.html")
def main(adress): #Transform the input adress to a dataframe df_adress = pd.DataFrame({'adress' : adress}, index = {0}) #Init the geocoding and limit the rate locator = geopy.geocoders.Nominatim(user_agent="mygeocoder") geocode = RateLimiter(locator.geocode, min_delay_seconds=0.1) #For the production try : st.text('adress found ! 👌 ') st.text('☕☕☕ Prepare yourself a coffee the map will arrive in 2 minute ! ☕☕☕') allowed_distance = 10000 #Apply the geocoding to retrieve the lat & long df_adress["loc"] = df_adress["adress"].apply(geocode) df_adress["lat"] = df_adress["loc"].apply(lambda x : x[1][0]) df_adress["lon"] = df_adress["loc"].apply(lambda x : x[1][1]) df_adress["city"] = df_adress["loc"].apply(lambda x : x[0].split(',')[4]) #Create the geodataframe gdf = gpd.GeoDataFrame(df_adress, geometry = gpd.points_from_xy(df_adress.lon, df_adress.lat), crs = 'EPSG:4326') gdf['allowed_distance'] = allowed_distance #Create the max distance authorized gdf_lockdown = gpd.GeoDataFrame(df_adress, geometry = gpd.points_from_xy(df_adress.lon, df_adress.lat), crs = 'EPSG:4326') gdf_lockdown = gdf_lockdown.to_crs('EPSG:2154') gdf_lockdown['geometry'] = gdf_lockdown['geometry'].buffer(allowed_distance) gdf_lockdown = gdf_lockdown.to_crs('EPSG:4326') #Retrieve the value from osm, transform it to a geodataframe, reset the index and keep only the right columns gdf_city_edge = ox.graph_to_gdfs(ox.graph_from_polygon(gdf_lockdown['geometry'][0], network_type='drive'), nodes= False)[['name', 'highway', 'geometry']] #Memory optimisations gdf_city_edge['highway'] = gdf_city_edge['highway'].apply(lambda x : str(x) ) gdf_city_edge['highway'] = gdf_city_edge['highway'].astype("category") gdf_city_edge['name'] = gdf_city_edge['name'].apply(lambda x : str(x) ) gdf_city_edge['name'] = gdf_city_edge['name'].astype("category") available_street = gdf_city_edge['name'].copy().reset_index()['name'].drop_duplicates().dropna() st.sidebar.text('If the street is inside the list ') st.sidebar.text('the location is at less than 10km !') st.sidebar.selectbox('Available streets:', available_street) with open('config.json') as f: config = json.load(f) config['config']['mapState']['latitude'] = df_adress["lat"][0] config['config']['mapState']['longitude'] = df_adress["lon"][0] config['config']['mapStyle']['styleType'] = 'satellite' st.text('Map loading...') #Some modification on the confg file (use config = config to retrieve th last version) #kepler_map = keplergl.KeplerGl(height=400, data={"city lockdown": gdf_city_edge_reduce.copy(), "location" : gdf.drop(['loc'], axis = 1).copy(), "lockdown" : gdf_lockdown.drop(['loc'], axis = 1).copy()}, config = config)._repr_html_() #Init the map kepler_map = keplergl.KeplerGl(height=400) #Adding the data kepler_map.add_data(data=gdf_city_edge, name='city lockdown') kepler_map.add_data(data=gdf.drop(['loc'], axis = 1), name='location') kepler_map.add_data(data=gdf_lockdown.drop(['loc'], axis = 1), name = 'lockdown') #Adding the config kepler_map.config = config #Transform to a html file kepler_map_html = kepler_map._repr_html_() return(kepler_map_html) except : st.text('location not found ! 😲')