def draw_relation(relation, cross_info): m = folium.Map([31.2240060, 121.4639028], zoom_start=15) for single_relation in relation: color = get_random_color() for ele in single_relation: location_1 = [cross_info[ele[0]][6], cross_info[ele[0]][5]] location_2 = [cross_info[ele[1]][6], cross_info[ele[1]][5]] location = [location_1, location_2] route = folium.PolyLine(location, weight=5, color='black', opacity=1).add_to(m) m.add_child(folium.LatLngPopup()) m.add_child(folium.ClickForMarker(popup='Waypoint')) # for ele in cross_info: # coordinate = [ele[6], ele[5]] # folium.Marker( # # folium格式,【纬度,经度】 # location=coordinate, # fill_color='#43d9de', # radius=8 # ).add_to(m) m.save( os.path.join(r'' + os.path.dirname(os.getcwd()) + '/dataset/', 'relation_no_node.html'))
def map(): start_coords = (46.9540700, 142.7360300) folium_map = folium.Map(location=start_coords, zoom_start=14) folium_map.add_child(folium.ClickForMarker(popup='Potential Location')) map_path = 'templates/map_raw.html' folium_map.save(map_path) return render_template("map.html")
def create_map(data_frame, home_address, year): """ (pandas.core.frame.DataFrame) -> (file) This function takes data frame and builds an interactive map (using folium library), according to given data. It also creates feature group of markers to point places of filming on map. """ # Build a simple map. f_map = folium.Map(location=[49.839683, 24.029717], tiles='openstreetmap', zoom_start=10) home_location = list(get_coordinates(home_address)) if home_location: home = folium.Marker(location=home_location, popup="My location", icon=folium.Icon(icon='home', color='red')) f_map.add_child(home) # Create feature group of markers to point/mark filming set by year. f_year_gr = folium.FeatureGroup(name="Films_year_{}".format(year)) # Iterate through rows of extracted data. for data_tuple in data_frame.itertuples(): ltt = data_tuple[3] lng = data_tuple[4] ttl = data_tuple[2] # Add marker for each DataFrame row. f_year_gr.add_child( folium.Marker([ltt, lng], popup=ttl, icon=folium.Icon(icon='video', color='red'))) f_map.add_child(f_year_gr) travel_layer = folium.TileLayer('Stamen Terrain') paint_layer = folium.TileLayer('Stamen Watercolor') beautiful_layer = folium.TileLayer('Mapbox Bright') mark_on_cklick = folium.ClickForMarker(popup="My Marker") f_map.add_child(mark_on_cklick) f_map.add_child( folium.GeoJson( data=open('world.json', 'r', encoding='utf-8-sig').read(), name='population', style_function=lambda x: { 'fillColor': 'green' if x['properties']['POP2005'] < 10000000 else 'orange' if ((10000000 <= x['properties']['POP2005']) and (x['properties']['POP2005'] < 20000000)) else 'red' })) # Add map layers to give an option of map's look like. travel_layer.add_to(f_map) paint_layer.add_to(f_map) beautiful_layer.add_to(f_map) # Create Layer Controller. folium.LayerControl().add_to(f_map) # Save created map as .html file. f_map.save("result_film_map.html")
def index(): m = folium.Map(location=[23.6856, 77.5643], tiles="OpenStreetMap", zoom_start=5) m.add_child(folium.ClickForMarker()) m.save('templates/map.html') return render_template('map.html')
def PlaceMonster(map_object): ''' map_object: folium map object One click places monster, double click removes monster ''' my_map.add_child(folium.ClickForMarker()) return my_map
def add_map() -> folium.Map: map = folium.Map(width=800, height=500, location=[56.8519, 60.6122], tiles='Stamen Terrain', zoom_start=13) map.add_child(folium.ClickForMarker(popup='Waypoint')) return map._repr_html_()
def reto1(request): form = buscadorReto1Form(request.POST or None) if form.is_valid(): seleccion = form.cleaned_data['seleccion'] hora_ini = form.cleaned_data['horaInicio'] hora_fin = form.cleaned_data['horaFin'] if seleccion == '1': nombre_archivo = conexionHadoop(1, hora_ini, hora_fin) datos = resultadoHadoop(nombre_archivo) else: hora_ini = '00:00' hora_fin = '02:00' nombre_archivo = 'result22' datos = resultadoHadoop(nombre_archivo) datos = json.loads(datos) datos_mapa = datos.copy() for llave, valor in datos.items(): datos[llave] = '{} ({})'.format( decodificarLugar(valor.split(',')[0]).replace('\n', ''), valor.split(',')[1]) diccionario = dict() lat = [] log = [] amout = [] #print(datos_mapa) for llave, valor in datos_mapa.items(): latitud, longitud = decodificarLugar_df(valor.split(',')[0]) lat.append(float(latitud)) log.append(float(longitud.replace('\n', ''))) amout.append(int(valor.split(',')[1])) diccionario['latitud'] = lat diccionario['longitud'] = log diccionario['valor'] = amout datos_df = pd.DataFrame(diccionario) base_map = generateBaseMap() HeatMap(data=datos_df[['latitud', 'longitud', 'valor']].groupby( ['latitud', 'longitud']).sum().reset_index().values.tolist(), radius=8, max_zoom=10).add_to(base_map) base_map.add_child(folium.ClickForMarker(popup='valor')) context = { 'datos': datos, 'imagen': base_map._repr_html_(), 'hora_ini': hora_ini, 'hora_fin': hora_fin, } return render(request, 'taller1/reto_1.html', context) context = { 'form': form, } return render(request, 'taller1/buscadores/reto_1_search.html', context)
def map(self): uiuc_coords = [40.1100, -88.2272] my_map = folium.Map(location=uiuc_coords, zoom_start=18) my_map.add_child(folium.ClickForMarker()) html = my_map.get_root().render() html = html.encode("utf-8", "replace") b64 = base64.b64encode(html).decode("utf-8", "replace") url = "data:text/html;base64,{data}".format(data=b64) self.add_widget(CEFBrowser(url=url))
def plot_places(): """ INPUT: database containing places w/ long, lat, name, comment, and visited status OUTPUT: map with pins on locations """ colors = [ 'red', 'green', 'blue', 'purple', 'orange', 'darkred', 'lightred', 'beige', 'darkblue', 'darkgreen', 'gray', 'black', 'lightgray' ] # Creates map map1 = folium.Map(zoom_start=2, tiles='OpenStreetMap') # map1.Marker(location=[46.8354,-121.7325], popup='Camp Muir') # folium.Marker(location=[-100,-60]).add_to(map1) folium.ClickForMarker(popup='test point').add_to(map1) map1.save('map.html')
def show_maps_Flood(): colors = [ '#2b83ba', '#abdda4', '#ffffbf', '#fdae61', '#d7191c' ] # these have been assigned to each FloodRisk category in the GeoJSON file on QGIS!!! m = folium.Map(location=[15.4275, -61.3408], zoom_start=11) # center of island overview # # Show Landslide GeoJSON to the map # folium.GeoJson( # landslide_json, # name='Landslide', # style_function=lambda feature: { # # 'fillColor': feature['properties']['Color'], # # 'color' : feature['properties']['Color'], # 'weight' : 1, # 'fillOpacity' : 0.3, # } # ).add_to(m) ## Show risk zones folium.GeoJson(flood_gj, name='Flood Risk', style_function=lambda feature: { 'fillColor': feature['properties']['Color'], 'color': feature['properties']['Color'], 'weight': 1, 'fillOpacity': 0.3, }).add_to(m) # Setup colormap MUST USE SAME COLORS AS QGIS GEOJSON FILE!!!! levels = len(colors) cmap = branca.colormap.LinearColormap(colors, vmin=0, vmax=4).to_step(levels - 1) cmap.add_to(m) # Enable lat-long Popup; LayerControl; Call to render Folium map in Streamlit m.add_child( folium.ClickForMarker(popup='Waypoint (Double-click to remove it)') ) # and click-for-marker functionality (dynamic) m.add_child( folium.LatLngPopup() ) # It's not possible to save lat long automatically from clicking on it :-( . # https://github.com/python-visualization/folium/issues/520 folium.LayerControl().add_to(m) folium_static(m)
def plot_places(): """ INPUT: database containing places w/ long, lat, name, comment, and visited status OUTPUT: map with pins on locations """ # Creates map placesMap = folium.Map(zoom_start=2, tiles='Mapbox bright') # folium.Marker(location=[356915.68,482043.25],icon=folium.Icon(color='green'),popup='hi').add_to(placesMap) # Loads database from json file 'placesdb.json' with open('placesdb.json') as f: PlacesDB = json.load(f) # TEST PRINT STATMENTS # location=[PlacesDB["places"][0]["lat"],PlacesDB["places"][0]["long"]] # icon = folium.Icon(color=colors[0]) # popup = {PlacesDB["places"][0]["name"], # name # PlacesDB["places"][0]["comment"], # comment # PlacesDB["places"][0]["visited"]} # print(location, icon, popup) # Loops through placesDB and drops pins i.e. 'markers' # for i in range(len(PlacesDB["places"])): # # if PlacesDB[i] == []: # # pass # # else: # if PlacesDB["places"][i]["visited"]: # if "visited" == true, make icon blue # folium.map.Marker(location=[PlacesDB["places"][i]["lat"],PlacesDB["places"][i]["long"]], # lat, long (northing, easting) # icon=folium.Icon(color='blue'), # blue if visited # popup=PlacesDB["places"][i]["name"]+': '+ # name # PlacesDB["places"][i]["comment"] # comment # ).add_to(placesMap) # else: # if "visited" == false or doesn't exist, make icon red # folium.map.Marker(location=[PlacesDB["places"][i]["lat"],PlacesDB["places"][i]["long"]], # lat, long (northing, easting) # icon=folium.Icon(color='red'), # red if not yet visited # popup=PlacesDB["places"][i]["name"]+': '+ # name # PlacesDB["places"][i]["comment"] # comment # ).add_to(placesMap) # sleep(1) # Delays calls to open cage geocoder # keep_in_front(marker) folium.ClickForMarker(popup='place').add_to(placesMap) placesMap.save('map2.html')
def main(): data_url = "jingweidu2.xlsx" data = pd.read_excel(data_url, sheet_name='Sheet1') data_list = data.to_numpy() oil_and_speed_data_list = [] for i in range(len(data_list)): l = [] l.append(data_list[i][6]) l.append(data_list[i][5]) oil_and_speed_data_list.append(l) # print(oil_and_speed_data_list) m = folium.Map([25.99242, 119.367781], zoom_start=10) # 中心区域的确定 route = folium.PolyLine( # polyline方法为将坐标用线段形式连接起来 oil_and_speed_data_list, # 将坐标点连接起来 weight=3, # 线的大小为3 color='orange', # 线的颜色为橙色 opacity=0.8 # 线的透明度 ).add_to(m) # 将这条线添加到刚才的区域m内 m.add_child(folium.ClickForMarker(popup='Waypoint')) m.save(os.path.join(r'C:\Users\87660\Desktop', 'chuli2.html')) # 将结果以HTML形式保存到桌面上
def map(request, pk): # reco_face = Recognize.objects.all() # for # reco_face = folium.Map(width=100, height=100, # location=[45.5236, -122.6750]) # reco_face._repr_html_() # # list_reco_face.append(Recognize.objects.get(face_id=pk)) # print(reco_face) map_rec = Recognize.objects.filter(face_id=pk) upload_rec = Face_image.objects.get(id=pk) check = False m = None case_colour = None if map_rec.count() == 0: check = True else: m = folium.Map([map_rec[0].latitude, map_rec[0].longitude], zoom_start=10) for map_r in map_rec: # str1 = "<b>time:</b>" # test = folium.Html('<b>time:</b>', script=True) # popup = folium.Popup(test, max_width=2650) map_r if upload_rec.case == 'MISSING': case_colour = 'blue' else: case_colour = 'red' folium.Marker(location=[map_r.latitude, map_r.longitude], popup=f"time:{map_r.image_taken_time}", icon=folium.Icon(color=case_colour, icon="info-sign")).add_to(m) m.add_child( folium.ClickForMarker(popup=f"time:{map_r.image_taken_time}")) m = m._repr_html_() # updated context = {'reco_face': m, 'check': check} # print(m) return render(request, 'faceuploader/map.html', context)
def show_nearby_restaurant(request): form = RestaurantModelForm(request.POST or None) geolocator = Nominatim(user_agent="geolocation") ip = '178.169.27.223' # change content with get_client_ip(request) in deploying stage. l_lat, l_lon = get_user_ip(ip) user_location = (l_lat, l_lon) m = folium.Map(width=800, height=400, zoom_start=12, location=user_location, no_touch=False) folium.Marker(location=user_location, tooltip='Click', popup='Your Position', icon=folium.Icon(color='red')).add_to(m) nearby_restaurant = RestaurantModel.objects.all() for res in nearby_restaurant: distance = int( geodesic((res.latitude, res.longitude), user_location).meters) if 1000 >= distance: folium.Marker(location=(res.latitude, res.longitude), tooltip='Click', popup=f"{res.service} m", icon=folium.Icon(color='blue')).add_to(m) # folium.Circle(location=(res.latitude, res.longitude), color='red', fill=True, weight=0, # radius=res.service).add_to(m) if form.is_valid(): form_location = form.cleaned_data.get('location') user_location = geolocator.geocode(form_location) lat, lon = user_location.latitude, user_location.longitude lat_lon = (lat, lon) m = folium.Map(width=800, height=400, zoom_start=14, location=lat_lon) folium.ClickForMarker().add_to(m) m = m._repr_html_() context = {'form': form, 'map': m} return render(request, 'nearby_restaurant.html', context)
############################################################################### map_2 = folium.Map(location=[45.5236, -122.6750], tiles='Stamen Toner', zoom_start=13) folium.Marker(location=[45.5244, -122.6699], popup='The Waterfront').add_to(map_2) folium.CircleMarker(location=[45.5215, -122.6261], radius=500, popup='Laurelhurst Park', color='#3186cc', fill_color='#3186cc').add_to(map_2) map_2.save('/tmp/folium_xx_portland.html') ############################################################################### map_3 = folium.Map(location=[46.1991, -122.1889], tiles='Stamen Terrain', zoom_start=13) folium.LatLngPopup().add_to(map_3) map_3.save('/tmp/folium_xx_sthelens.html') ############################################################################### map_4 = folium.Map(location=[46.8527, -121.7649], tiles='Stamen Terrain', zoom_start=13) folium.Marker(location=[46.8354, -121.7325], popup='Camp Muir').add_to(map_4) folium.ClickForMarker(popup='Waypoint').add_to(map_4) map_4.save('/tmp/folium_xx_mtrainier.html') ############################################################################### map_5 = folium.Map(location=[45.5236, -122.6750], zoom_start=13) folium.RegularPolygonMarker(location=[45.5012, -122.6655], popup='Ross Island Bridge', fill_color='#132b5e', number_of_sides=3, radius=10).add_to(map_5) folium.RegularPolygonMarker(location=[45.5132, -122.6708], popup='Hawthorne Bridge', fill_color='#45647d', number_of_sides=4, radius=10).add_to(map_5) folium.RegularPolygonMarker(location=[45.5275, -122.6692], popup='Steel Bridge', fill_color='#769d96', number_of_sides=6, radius=10).add_to(map_5) folium.RegularPolygonMarker(location=[45.5318, -122.6745], popup='Broadway Bridge', fill_color='#769d96', number_of_sides=8, radius=10).add_to(map_5) map_5.save('/tmp/folium_xx_bridges.html')
import folium theme = [ "OpenStreetMap", "Stamen Terrain", "Stamen Toner", "Mapbox Bright", "Mapbox Control Room" ] selected_theme_index = 0 selected_theme = theme[selected_theme_index] location = [51.523910, -0.158578] m = folium.Map(location=location, tiles=selected_theme, zoom_start=10) folium.Circle(location=location, radius=50, popup='Holmes Home', color='#3186cc', fill=True, fill_color='#3186cc').add_to(m) m.add_child(folium.ClickForMarker()) m.save("map.html") """ <html> <body style="background:#888888"> </body> </html> """
zoom_start=12, tiles='Stamen Terrain') map_1.add_child( folium.Marker([-27.538482, 153.019902], popup="Home sweet home", icon=folium.Icon(icon='home', color='green'))) folium.CircleMarker([-27.477337, 153.028423], popup="University", radius=20, color="white", fill_color="black").add_to(map_1) map_1.add_child( folium.ClickForMarker(popup="You made a marker you clever person")) map_1.save("Map_1.html") # a more organised way of setting this up is to create a feature group. # a feature group allows you to add more controls later on to specific parts of the map, # as things get more complicated map_2 = folium.Map(location=[-28.263088, 153.571857], zoom_start=13, tiles='Stamen Terrain') fg = folium.FeatureGroup(name="The Map 2") #Parents current house marker fg.add_child(
folium.Marker(location=[28.339080, 77.319134], popup="Cave", icon=folium.Icon(color='blue'))) map.add_child( folium.Marker(location=[29.339080, 77.319134], popup="Hacienda Del Patron", icon=folium.Icon(color='red'))) # One more way of marking tooltip = "Click Me !" folium.Marker([28.539080, 77.319134], popup="<i>Camp Alpha</i>", tooltip=tooltip).add_to(map) folium.Marker([28.539080, 77.519134], popup="Pochinki").add_to(map) # Another Way of marking fg = folium.FeatureGroup(name="My Map") fg.add_child( folium.Marker(location=[29.439080, 77.319134], popup="Bootcamp", icon=folium.Icon(color='green'))) map.add_child(fg) #Using some other functionality - marking with the click of the mouse map.add_child( folium.ClickForMarker(popup='Waypoint') ) # This ClickForMarker is used to have mouse button click functionality map.save("Map1.html")
zoom_start=9) # Simple marker folium.Marker([51.5079, 0.0877], popup='London Bridge', icon=folium.Icon(color='green')).add_to(map_hooray) # Circle marker folium.CircleMarker( [51.4183, 0.2206], radius=30, popup='East London', color='red', ).add_to(map_hooray) # Interactive marker map_hooray.add_child(folium.ClickForMarker(popup="Dave is awesome")) map_hooray # # Interaction with the map # In[ ]: map_hooray = folium.Map( location=[51.5074, 0.1278], zoom_start=11 ) # Uses lat then lon. The bigger the zoom number, the closer in you get from folium import plugins # Adds tool to the top right from folium.plugins import MeasureControl
# conn = sqlite3.connect('DB\\GPS.db') # conn.execute("insert into GPS_points (lat,lon) values (34,56)") # conn.commit() # conn.close() # print(4) print(folium.__version__) # python+folium地图 map_osm = folium.Map( location=[36.9848416666667, 111.8207], # tiles='Stamen Toner', zoom_start=18) map_osm.add_child(folium.LatLngPopup()) # 点击地图任意一个位置将显示对应的经纬度 map_osm.add_child( folium.ClickForMarker(popup='ClickForMarker')) # 点击地图任意一个位置会显示一个默认标记 # 标记方式一 folium.Marker([36.9848416666667, 111.8207], popup='center').add_to(map_osm) # popup为点击标记点时出现的注释文字 # 标记方式二 folium.Marker([36.9846633333333, 111.820741666667], popup='point_1', icon=folium.Icon(color='cloud')).add_to(map_osm) # 标记方式三 folium.Marker([36.9846866666667, 111.820841666667], popup='point_2', icon=folium.Icon(color='green')).add_to(map_osm) # 标记方式四 folium.Marker([36.9846483333333, 111.820878333333],
def main(): st.write('this map will use coordinate format WGS84/UTMzone19N') colors = ['#2b83ba', '#abdda4', '#ffffbf', '#fdae61', '#d7191c'] # these have been assigned to each FloodRisk category in the GeoJSON file on QGIS!!! m = folium.Map(location=[15.4275, -61.3408], zoom_start=11) # center of island overview ## Show risk zones folium.GeoJson( flood_gj, name='Flood Risk', style_function=lambda feature: { 'fillColor': feature['properties']['Color'], 'color' : feature['properties']['Color'], 'weight' : 1, 'fillOpacity' : 0.3, } ).add_to(m) # Show Landslide GeoJSON to the map folium.GeoJson( landslide_json, name='Landslide' ).add_to(m) # Setup colormap MUST USE SAME COLORS AS QGIS GEOJSON FILE!!!! levels = len(colors) cmap = branca.colormap.LinearColormap(colors, vmin=0, vmax=4).to_step(levels-1) cmap.add_to(m) # Enable lat-long Popup; LayerControl; Call to render Folium map in Streamlit m.add_child(folium.ClickForMarker(popup='Waypoint (Double-click to remove it)')) # and click-for-marker functionality (dynamic) m.add_child(folium.LatLngPopup()) # It's not possible to save lat long automatically from clicking on it :-( . # https://github.com/python-visualization/folium/issues/520 folium.LayerControl().add_to(m) folium_static(m) #------------------- # Text labels to enter the lat & long coordinates once you read them on the map lat_long = st.text_input('Insert Latitude and Longitude in the format WGS84/UTMzone19N (DD.dddd) for example: 15.2533,-61.3164') if lat_long != '': latitude = float(lat_long.split(',')[0]) longitude = float(lat_long.split(',')[1]) if st.button('Analyse Lat & Long'): # this is if you want to add a button to launch the analysis (without this, it does automatically when there's lat & long values in the cell) st.header('Extracting Results for the location selected:\n(Lat: ' + str(latitude) +' & Long: ' + str(longitude) + ')') # ======= Get Value from Shapefile #coordinate = shapely.geometry.Point((-61.346482,15.393996,)) # outside #coordinate = shapely.geometry.Point((-61.419855,15.396184,)) # 1771 coordinate = shapely.geometry.Point((longitude,latitude,)) # Printing a list of the coords to ensure iterable #list(coordinate.coords) ######## First loop for flood risk for i in landslide_shp.loc[:,'geometry']: p = Point(longitude,latitude) if p.within(i): polig_landslide = landslide_shp[landslide_shp.geometry.intersects(coordinate)].values[0][0] landslide_code =polig_landslide print(landslide_code) st.markdown('**-Landslide Risk: **'+ landslide_code) st.write('wait for Flood Risk Analysis... ') break else: landslide_code = 'Outside Risk Zone' print(landslide_code) st.markdown('**-Landslide Risk: **'+ landslide_code) ######## Second loop for flood risk frisk_code = 'NAN' new_risk = 'NAN' for i in flood_shp.loc[:,'geometry']: p = Point(longitude,latitude) if p.within(i): frisk_code = flood_shp[flood_shp.geometry.intersects(coordinate)].values[0][0] new_risk = frisk_code-1 if new_risk == 0: new_risk = 'No Risk' st.markdown('**-Flood risk: **' + str(new_risk)) print(new_risk) url1 = 'tablerisk.png' image1 = Image.open(url1) st.markdown(get_table_download_link(df), unsafe_allow_html=True) st.image(image1, caption='',use_column_width=True) else: st.markdown('**-Flood risk: **' + str(new_risk)) print(new_risk) url1 = 'tablerisk.png' image1 = Image.open(url1) st.markdown(get_table_download_link(df), unsafe_allow_html=True) st.image(image1, caption='',use_column_width=True) break
def add_clickmarker(self, *args): popup = "".join(args) self.base_map.add_child(folium.ClickForMarker(popup=popup))
def main(): colors = [ '#2b83ba', '#abdda4', '#ffffbf', '#fdae61', '#d7191c' ] # these have been assigned to each FloodRisk category in the GeoJSON file on QGIS!!! m = folium.Map(location=[15.4275, -61.3408], zoom_start=11) # center of island overview # Show Landslide GeoJSON to the map folium.GeoJson( landslide_json, name='Landslide', style_function=lambda feature: { # 'fillColor': feature['properties']['Color'], # 'color' : feature['properties']['Color'], 'weight': 1, 'fillOpacity': 0.3, }).add_to(m) ## Show risk zones folium.GeoJson(flood_gj, name='Flood Risk', style_function=lambda feature: { 'fillColor': feature['properties']['Color'], 'color': feature['properties']['Color'], 'weight': 1, 'fillOpacity': 0.3, }).add_to(m) # Setup colormap MUST USE SAME COLORS AS QGIS GEOJSON FILE!!!! levels = len(colors) cmap = branca.colormap.LinearColormap(colors, vmin=0, vmax=4).to_step(levels - 1) cmap.add_to(m) # Enable lat-long Popup; LayerControl; Call to render Folium map in Streamlit m.add_child( folium.ClickForMarker(popup='Waypoint (Double-click to remove it)') ) # and click-for-marker functionality (dynamic) m.add_child( folium.LatLngPopup() ) # It's not possible to save lat long automatically from clicking on it :-( . # https://github.com/python-visualization/folium/issues/520 folium.LayerControl().add_to(m) folium_static(m) st.write('This map uses coordinate format WGS84-EPGS4326') #------------------- # Text labels to enter the lat & long coordinates once you read them on the map lat_long = st.text_input( 'Insert Latitude,Longitude (without spaces) format WGS84-EPGS4326 (DD.dddd) for example: 15.2533,-61.3164', max_chars=16) if lat_long != '': latitude = float(lat_long.split(',')[0]) longitude = float(lat_long.split(',')[1]) if st.button( 'Analyse Lat & Long' ): # this is if you want to add a button to launch the analysis (without this, it does automatically when there's lat & long values in the cell) st.header('Extracting Results for the location selected:\n(Lat: ' + str(latitude) + ' & Long: ' + str(longitude) + ')') landslide_code, new_risk = risk_prediction(longitude, latitude) st.markdown('**-Landslide Risk: **' + str(landslide_code) + ' ---> ' + dict2(landslide_code)) st.markdown('**-Flood risk: **' + str(new_risk) + '---> ' + dict1(new_risk)) url1 = 'tablerisk.png' image1 = Image.open(url1) st.image(image1, caption='', width=350)
# In[48]: for lat, lng, in zip(china.Latitude, china.Longitude): incidents.add_child( folium.CircleMarker([lat, lng], radius=8, color='pink', fill=True, fill_color='purple', fill_opacity=0.5)) china_map = folium.Map(location=[latitude, longitude], zoom_start=4) china_map.add_child(incidents) '''为地图对象添加点击显示经纬度的子功能''' china_map.add_child(folium.LatLngPopup()) china_map.add_child(folium.ClickForMarker()) # In[ ]: # In[49]: # 添加标签 incidents = folium.map.FeatureGroup() latitudes = list(china.Latitude) longitudes = list(china.Longitude) labels = list(china.Name) for lat, lng, label in zip(latitudes, longitudes, labels): folium.Marker([lat, lng], popup=label).add_to(china_map)
def main(): st.write('this map will use coordinate format WGS84/UTMzone19N') landslide_shp = gpd.read_file( 'Flood_and_Landslide_Datasets/landslides_1_4326.shp') landslide_json = 'Flood_and_Landslide_Datasets/landslides_1_4326.geojson' landslide_path = 'Flood_and_Landslide_Datasets/landslides_1_4326.shp' # Flood Risk (Vectorised) flood_shp = gpd.read_file( 'Flood_and_Landslide_Datasets/geonode_flood_hazard_map_vector.shp') flood_gj = geojson.load( open( 'Flood_and_Landslide_Datasets/geonode_flood_hazard_map_vector.geojson' ) ) # Import geojson file # https://stackoverflow.com/questions/42753745/how-can-i-parse-geojson-with-python flood_path = 'Flood_and_Landslide_Datasets/geonode_flood_hazard_map_vector.shp' colors = [ '#2b83ba', '#abdda4', '#ffffbf', '#fdae61', '#d7191c' ] # these have been assigned to each FloodRisk category in the GeoJSON file on QGIS!!! m = folium.Map(location=[15.4275, -61.3408], zoom_start=11) # center of island overview ## Show risk zones folium.GeoJson(flood_gj, name='Flood Risk', style_function=lambda feature: { 'fillColor': feature['properties']['Color'], 'color': feature['properties']['Color'], 'weight': 1, 'fillOpacity': 0.3, }).add_to(m) # Show Landslide GeoJSON to the map folium.GeoJson(landslide_json, name='Landslide').add_to(m) # Setup colormap MUST USE SAME COLORS AS QGIS GEOJSON FILE!!!! levels = len(colors) cmap = branca.colormap.LinearColormap(colors, vmin=0, vmax=4).to_step(levels - 1) cmap.add_to(m) # Enable lat-long Popup; LayerControl; Call to render Folium map in Streamlit m.add_child( folium.ClickForMarker(popup='Waypoint (Double-click to remove it)') ) # and click-for-marker functionality (dynamic) m.add_child( folium.LatLngPopup() ) # It's not possible to save lat long automatically from clicking on it :-( . # https://github.com/python-visualization/folium/issues/520 folium.LayerControl().add_to(m) folium_static(m) #------------------- # Text labels to enter the lat & long coordinates once you read them on the map lat = st.text_input( 'Insert Latitude in the format WGS84/UTMzone19N (DD.dddd) for example: 15.2533' ) if lat != '': latitude = float(lat) longi = st.text_input( 'Insert Longitude in the format WGS84/UTMzone19N (DD.dddd) for example: -61.3164' ) if longi != '': longitude = float(longi) df1 = read_shapefile(landslide_path) df2 = read_shapefile(flood_path) if st.button( 'Analyse Lat & Long' ): # this is if you want to add a button to launch the analysis (without this, it does automatically when there's lat & long values in the cell) p = Point(longitude, latitude) st.header('Extracting Results for the location selected:\n(Lat: ' + str(latitude) + ' & Long: ' + str(longitude) + ')') # ======= Get Value from Shapefile landslide_code = 'Outside Risk Zone' # From a given Point coordinates, quickly/efficiently check if it's contained in any polygons geometry, and print out the LANDSLIDE code of that polygon if so. # this works, but is this teh most efficient way?!? Think it can be improved with lampda / apply / map, without iterating on the whole dataframe? ####################### # for i in df1.loc[:,'coor']: # if p.within(i): # landslide_code = df1.loc[df1.loc[:,'coor'] == i]['LANDSLIDES'].values[0] # st.markdown('**-Landslide Risk: **'+ landslide_code) # st.write('wait for Flood Risk Analysis... ') ##################à## for i in landslide_shp.loc[:, 'geometry']: if p.within(i): landslide_code = landslide_shp.loc[ landslide_shp.loc[:, 'geometry'] == i]['LANDSLIDES'].values[0] st.markdown('**-Landslide Risk: **' + landslide_code) st.write('wait for Flood Risk Analysis... ') # ======= Get Value from Raster # From a given Point coordinates, quickly/efficiently check if it's contained in any polygons geometry, and print out the LANDSLIDE code of that polygon if so. # this works, but is this teh most efficient way?!? Think it can be improved with lampda / apply / map, without iterating on the whole dataframe? frisk_code = 'NAN' new_risk = 'NAN' for k in flood_shp.loc[:, 'geometry']: if p.within(k): frisk_code = flood_shp.loc[flood_shp.loc[:, 'geometry'] == k]['FloodRisk'].values[0] new_risk = frisk_code - 1 print(new_risk) if new_risk == 0: new_risk = 'No Risk' ## TEST ## ## flood risk ==3 #15.2533,-61.3164 ## flood risk ==4 #15.3393,-61.2603 ## flood risk ==0 #15.3451,-61.3588 ## LandslideNO + flood risk ==0 ## 15.3955,-61.2482 ## LandslideXX + flood risk ==0 ## 15.4757,-61.2679 st.markdown('**-Flood risk: **' + str(new_risk)) url1 = 'tablerisk.png' image1 = Image.open(url1) st.image(image1, caption='', use_column_width=True)
def bokeh_new_class_folium(self, file_name: str = 'folium', lonlat_text_inputs: list = None, height: int = 1600, width: int = 1850): # topo_map.add_points_with_text(points_chosen, text='original images') # folium.LayerControl().add_to(self.topo_map.map) # folium.plugins.MeasureControl().add_to(topo_map.map) # folium.plugins.MousePosition(lng_first=True).add_to(topo_map.map) self.topo_map.map.add_child( folium.ClickForMarker(popup="new class chosen")) self.topo_map.map.add_child(folium.LatLngPopup()) # save the folium html static_folder = os.path.join(os.path.dirname(__file__), 'static') os.makedirs(static_folder, exist_ok=True) file_name_hash = hash(f'{file_name}{time.time()}') file_name = f'{file_name_hash}.html' filePath = os.path.join(static_folder, file_name) if os.path.exists(filePath): logging.info('removing') os.remove(filePath) self.topo_map.map.save(filePath) click_str = f""" f.contentWindow.document.body.onclick = function() {{ console.log('fsdfs') console.log({file_name_hash}) console.log({lonlat_text_inputs[0].id}) console.log({lonlat_text_inputs[1].id}) ff = document.getElementById('{file_name_hash}'); popup = ff.contentWindow.document.getElementsByClassName('leaflet-popup-content')[0]; popup_text = popup.innerHTML if(popup_text.length==38||popup_text.length==39){{ popup_words = popup_text.split(' ') longtitude = popup_words[2] latitude = popup_words[1].split('<br>')[0] console.log(longtitude); console.log(latitude); lon_old_values = window.Bokeh.index[Object.keys(window.Bokeh.index)[0]].model.document._all_models[{ lonlat_text_inputs[0].id}].value window.Bokeh.index[Object.keys(window.Bokeh.index)[0]].model.document._all_models[{ lonlat_text_inputs[0].id}].value = longtitude + ', ' + lon_old_values; lat_old_values = window.Bokeh.index[Object.keys(window.Bokeh.index)[0]].model.document._all_models[{ lonlat_text_inputs[1].id}].value; window.Bokeh.index[Object.keys(window.Bokeh.index)[0]].model.document._all_models[{ lonlat_text_inputs[1].id}].value = latitude + ', ' + lat_old_values; }} }}; """ if lonlat_text_inputs is not None else "" fig = Div(text=f""" <iframe onload="console.log('changing map props'); f = document.getElementById('{file_name_hash}'); map = eval('f.contentWindow.'+f.contentWindow.document.getElementsByClassName('folium-map')[0].id); if({self.center} && {self.zoom}){{console.log('lala'); map.setView({self.center}, {self.zoom});}}; {click_str} " id="{file_name_hash}" src="bokeh_server/static/{file_name}" width={width} height={height}></iframe> """, height=height, width=width) return fig
# 地图 m = folium.Map(location=[31.22, 121.48]) m.save('index.html') #显示黑白的街道 # b = folium.Map( # location=[31.22, 121.48], # tiles='Stamen Toner', # zoom_start=10 # ) # b.save('index_test1.html') # 点击显示精度 # shenqiu = folium.Map( # location=[33.41, 115.06], # tiles='Stamen Terrain', # zoom_start=13 # ) # shenqiu.add_child(folium.LatLngPopup()) # shenqiu.save('shenqiu.html') # # 标记 mar = folium.Map(location=[33.41, 115.06], tiles='Stamen Terrain', zoom_start=13) folium.Marker([33.41, 115.06], popup='Camp Muir').add_to(mar) mar.add_child(folium.ClickForMarker(popup='Waypoint')) mar.save('mar.html')
levels = len(colors) cmap = branca.colormap.LinearColormap(colors, vmin=0, vmax=4).to_step(levels - 1) cmap.add_to(m) folium.GeoJson(flood_gj, name='Flood Risk', style_function=lambda feature: { 'fillColor': feature['properties']['Color'], 'color': feature['properties']['Color'], 'weight': 1, 'fillOpacity': 0.3, }).add_to(m) # Enable lat-long Popup; LayerControl; Call to render Folium map in Streamlit m.add_child(folium.ClickForMarker(popup='Waypoint (Double-click to remove it)') ) # and click-for-marker functionality (dynamic) m.add_child( folium.LatLngPopup() ) # It's not possible to save lat long automatically from clicking on it :-( . # https://github.com/python-visualization/folium/issues/520 folium.LayerControl().add_to(m) folium_static(m) #------------------- # Text labels to enter the lat & long coordinates once you read them on the map lat_long = st.text_input('Insert Lat & Long in the format (Lat,Long):') if lat_long != '': latitude = float(lat_long.split(',')[0]) longitude = float(lat_long.split(',')[1])
fill_color=get_colour(elevation))) map.add_child(fg_volcanoes) # Downtown feature group fg_downtown = folium.FeatureGroup(name="San Jose Downtown") fg_downtown.add_child( folium.Marker(location=[37.3382, -121.893028], popup="Marker", icon=folium.Icon(color='blue'))) fg_downtown.add_child( folium.CircleMarker(location=[37.3389, -121.893020], popup="Circle Marker", color="green", fill=True, fill_opacity=0.7)) fg_downtown.add_child(folium.ClickForMarker()) fg_downtown.add_child( folium.RegularPolygonMarker(location=[37.3350, -121.893028], popup="RegularPolygonMarker", color="purple", fill=True)) map.add_child(fg_downtown) # Population feature group fg_population = folium.FeatureGroup(name="World Population") fg_population.add_child((folium.GeoJson( data=open("world.json", "r", encoding="utf-8-sig").read(), style_function=lambda x: { 'fillColor': 'green' if x['properties']['POP2005'] < 10000000 else 'yellow' if 10000000 <= x['properties']['POP2005'] < 100000000 else 'red'
fill_color='#43d9de', radius=10, number_of_sides=3, rotation=-90, weight=1, popup=popup1).add_to(kreta) #Agios Nikolaos Marker folium.RegularPolygonMarker(location=[35.192464, 25.706721], fill_color='#43d9de', radius=10, number_of_sides=3, rotation=-90, weight=1, popup=popup2).add_to(kreta) #Sitia Marker folium.RegularPolygonMarker(location=[35.198516, 26.077081], fill_color='#43d9de', radius=10, number_of_sides=3, rotation=-90, weight=1, popup=popup3).add_to(kreta) # #Click Marker folium.ClickForMarker() kreta.save("../figures/kreta.html")