def plot_tbf(route, name='latest'): # Start map centered in US tbfmap = folium.Map(location=[39.82, -98.58], zoom_start=4, tiles="OpenStreetMap") # Define the popup markers for node in route: print(node) dt = datetime.datetime.strptime(node[5], '%Y-%m-%d %H:%M:%S') dt_text = dt.strftime("%A, %B %d, %Y - %I:%M %p") + ' (ET)' popup_text = '''<div> Game {}: {} @ {}<br> {}, {}<br> {}</div> '''.format(node[0], node[2], node[3], node[1], node[4], dt_text) popup_html = folium.Popup(popup_text, min_width=200, max_width=250) folium.Marker( location=[float(node[7]), float(node[6])], popup=popup_html, icon=folium.DivIcon( html= '<i class="fa fa-map-pin fa-stack-2x"></i><strong style="text-align: center; color: white; font-family: Trebuchet MS;" class="fa-stack-1x">{}</strong>' .format(node[0]))).add_to(tbfmap) # Add the lines between stadiums lines = folium.PolyLine(locations=[(float(i[7]), float(i[6])) for i in route]) lines.add_to(tbfmap) # Print maps to html tbfmap.save("maps/{}.html".format(name))
def add_text_by_region(dico_textes, carte, maille='region'): # @liste_textes : une liste de textes à afficher sur chaque région # Important : l'ordre des textes doit être le même que l'ordre alphabétique des région : alsace, aquitaine, aubergne, bourgogne... if maille == 'region': regions = { 'Grand Est': [48.5, 5.49], 'Aquitaine-Limousin-Poitou-Charentes': [45.65, 0.05], 'Auvergne-Rhône-Alpes': [45.25, 4.29], 'Bourgogne-Franche-Comté': [47, 4.85], 'Bretagne': [48, -3], 'Centre-Val de Loire': [47.4, 1.69], 'Ile-de-France': [48.3, 2.5], 'Languedoc-Roussillon-Midi-Pyrénées': [43.93, 2], 'Hauts-de-France': [50, 2.64], 'Normandie': [48.7, -0.2], 'Pays-de-la-Loire': [47.2, -0.94], "Provence-Alpes-Côte d'Azur": [43.7, 6.5], 'Corse': [42, 9.15] } for region in regions: folium.map.Marker( location=regions[region], icon=folium.DivIcon(html=dico_textes[region], icon_size=(80, 80)), ).add_to(carte) return carte
def saveLepsiusMap(): '''Creats Lepsius list and map Drop rows where Lepsius column contains NaN values zoom in to get the pyramids and the Pharaoh's name''' prmds_Le = prmds.dropna(subset=['Lepsius']) m2 = folium.Map( location=[prmds_Le['Latitude'].mean(), prmds_Le['Longitude'].mean()], zoom_start=9, min_zoom=6, width=600) for i in range(0, len(prmds_Le)): lat = prmds_Le.iloc[i]['Latitude'] lon = prmds_Le.iloc[i]['Longitude'] temp = prmds_Le.iloc[i]['Lepsius'] folium.CircleMarker([lat, lon], radius=8, color='red', fill=True, fill_color='red').add_to(m2) folium.Marker( [lat, lon], popup=prmds_Le.iloc[i]['Pharaoh'], icon=folium.DivIcon( html= f'''<div style="font-family: arial; color: 'black'">{"{}".format(temp)}</div>''' )).add_to(m2) #display(m2) m2.save(outfile="map-Lepsius.html")
def make_predict_map_html(testCombine): m = folium.Map( location=[ testCombine.iloc[0]['latitude'], testCombine.iloc[0]['longitude'] ], zoom_start=16, ) testCombine.reset_index(drop=True, inplace=True) count = 0 for i in range(len(testCombine)): if (testCombine.iloc[i]['data_ftp_rx_tp'] < 200): location = [ testCombine.iloc[i]['latitude'], testCombine.iloc[i]['longitude'] ] folium.CircleMarker(location=location, radius=15, color='red', fill=True, fill_color='white').add_to(m) folium.Marker( location=location, tooltip=testCombine.iloc[i]['top_match'], popup=testCombine.iloc[i]['top_match'], icon=folium.DivIcon( icon_size=(100, 36), icon_anchor=(5, 5), html='<div style="font-size: 8pt; color : black">{}</div>'. format(testCombine.iloc[i]['top_match']))).add_to(m) m.add_child(folium.CircleMarker(location, radius=10)) m.save('C:\\Work\\flask\\template\\predict_marker.html')
def test_divicon(): html = """<svg height="100" width="100"> <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /> </svg>""" # noqa div = folium.DivIcon(html=html) assert isinstance(div, Element) assert div.options['className'] == 'empty' assert div.options['html'] == html
def plotChain(point): #iframe = folium.IFrame(text, width=700, height=450) #popup = folium.Popup(iframe, max_width=3000) folium.Marker( [point['X1'], point['Y1']], radius=4 , color='black' #, fill_color='#808080' #, fill=True , icon=folium.DivIcon(html=str("<p style='font-family:verdana;color:#444;font-size:10px;'> %d</p>" % (point['cumlength'])))#, point['LABEL'], point['STARTCH']))) #, popup=str(point['cumlength']) ).add_to(feature_group4)
def add_label(map_object, location, text, font_size=18): # icon_anchor is left-aligned so need to shift length, width = get_text_size(text, font_size) folium.map.Marker(location, icon=folium.DivIcon( icon_size=None, icon_anchor=(length // 2, width // 2), html='<div style="font-size: {0}pt"><span style="background-color: rgba(255, 255, 255, 0.6); padding: 0px 5px; white-space: nowrap">'.format(font_size) + text + '</div>' ) ).add_to(map_object)
def showMap(self): homeLoc = {} homeLoc['lat'] = float(self.mylat.text()) homeLoc['lon'] = float(self.mylon.text()) self.map1 = folium.Map( location=[homeLoc['lat'],homeLoc['lon']], tiles=self.combomap.currentText(), zoom_start=13 ) folium.Marker([homeLoc['lat'],homeLoc['lon']], #Make color/style changes here icon = folium.Icon(color='blue'), popup = 'Home node', ).add_to(self.map1) global packet global msgcount for msg in packet: lat = float(msg['lat']) lon = float(msg['lon']) user = msg['user'] snr = msg['snr'] ora = msg['ora'] dist = msg['dist'] folium.Marker([lat,lon], icon = folium.Icon(color='red'), popup = user+'   <br>ora: '+ \ ora+'<br>snr: '+str(snr)+'<br>Km: '+str(dist), ).add_to(self.map1) folium.Marker([lat,lon], icon=folium.DivIcon(html=f"""<div style='font-size:20px; font-weight: bold;'>{user}</div>""") ).add_to(self.map1) print("Mark added") data = io.BytesIO() self.map1.save(data, close_file=False) self.map1 = QtWebEngineWidgets.QWebEngineView() self.map1.setHtml(data.getvalue().decode()) self.map1.page().profile().setUrlRequestInterceptor(self.interceptor) self.tabs.removeTab(1) self.tab2.destroy() self.tab2 = QWidget() self.tabs.addTab(self.tab2,"Map") self.tab2.layout = QVBoxLayout() self.tab2.layout.addWidget(self.map1) self.tab2.setLayout(self.tab2.layout) self.map1.show() packet = [] msgcount = 0
def get_icon(abbreviation, clust_icon_kwargs, default=False): """Get icon from /icons or create colored default folium icon.""" if default: return folium.Icon(**clust_icon_kwargs[abbreviation]) path = Path(__file__).parent icon_path = "icons//{abb}.svg".format(abb=abbreviation.replace("//", "_")) # print(path/icon_path, path) # print(abbreviation) try: with open(path / icon_path, "r") as f: svg_str = f.read() except FileNotFoundError: return folium.Icon(**clust_icon_kwargs[abbreviation]) height = float([ line for line in svg_str.split() if line.startswith("height") ][0].split("=")[-1].replace('"', "")) width = float([ line for line in svg_str.split() if line.startswith("width") ][0].split("=")[-1].replace('"', "")) icon = folium.DivIcon(html=svg_str, icon_anchor=(width / 2, height / 2)) return icon
def foliumGeneration(frameData): #generates the folium data mapCenter = [33.7, -84.4] #Create folium files #m = folium.Map(location=[33.7,-84.4]) #m = folium.Map(location=[mapCenter[0],mapCenter[1]]) m = folium.Map(location=[mapCenter[0], mapCenter[1]], zoom_start=12, tiles='https://api.mapbox.com/styles/v1/samsonbaskin/ckcf0m9xw1g711iq8e2re1yew/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1Ijoic2Ftc29uYmFza2luIiwiYSI6ImNqYnFyMTA3eTA3NWQyd3I2NHVibTdndTYifQ.OndsKFSRgSnU3hfCKPOX7A', attr='mapbox') svgFile = open("iconTest.svg") style = svgFile.read() i = 0 for frame in tqdm(frameData): i = i + 1 #m = folium.Map(location=[mapCenter[0],mapCenter[1]]) m = folium.Map(location=[mapCenter[0], mapCenter[1]], zoom_start=12, tiles='https://api.mapbox.com/styles/v1/samsonbaskin/ckcf0m9xw1g711iq8e2re1yew/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1Ijoic2Ftc29uYmFza2luIiwiYSI6ImNqYnFyMTA3eTA3NWQyd3I2NHVibTdndTYifQ.OndsKFSRgSnU3hfCKPOX7A', attr='mapbox') for entry in frame: if i < 200: coord = entry["coords"] folium.Marker([coord[1],coord[0]], icon=folium.DivIcon(icon_size=(10,10),html=style)).add_to(m) if i < 10: num = "000" + str(i) elif i < 100 and i >= 10: num = "00" + str(i) elif i < 1000 and i >= 100: num = "0" + str(i) else: num = str(i) fileName = 'htmlFrames/foliumTest'+ num +'.html' m.save(fileName)
'Montreal', 'Nairobi', 'Salvador' ], 'value': [10, 12, 40, 70, 23, 43, 100, 43] }, dtype=str) # Make an empty map n = folium.Map(location=[20, 0], tiles="OpenStreetMap", zoom_start=2) # add marker one by one on the map for i in range(0, len(data)): html = f""" <h1> {data.iloc[i]['name']}</h1> <p>You can use any html here! Let's do a list:</p> <ul> <li>Item 1</li> <li>Item 2</li> </ul> </p> <p>And that's a <a href="https://www.python-graph-gallery.com">link</a></p> """ iframe = folium.IFrame(html=html, width=200, height=200) folium.Marker(location=[data.iloc[i]['lat'], data.iloc[i]['lon']], popup=data.iloc[i]['name'], icon=folium.DivIcon(html=f""" <div style="font-family: courier new; color: blue">{data.iloc[i]['name']}<svg> <rect x="0", y="0" width="10" height="10", fill="red", opacity=".3"> </svg></div>""")).add_to(n) n.save('1map.html') webbrowser.open_new_tab('1map.html')
#objet map vierge issu d'OpenStreetMap map = folium.Map(location=coords, tiles='OpenStreetMap', zoom_start=7) #création du colormap de carte #cf http://soliton.vm.bytemark.co.uk/pub/cpt-city/cb/seq/index.html colormap = cm.linear.YlGnBu_09.scale(0, 80).to_step(10) #colormap = cm.linear.YlOrRd_05.scale(0, 100).to_step(10) colormap.caption = 'Nb de Salariés' map.add_child(colormap) #Gestion des données des frontières des départements folium.GeoJson( geo_json_data, style_function=lambda feature: { 'fillOpacity': 0.9, 'fillColor': colormap(stat_salaries[feature['properties']['nom']]), 'color': 'black', 'weight': 2, }).add_to(map) #Ecriture des noms des départements for i in infos_DP: str = f"{i[1].replace('-','.')}.{int(stat_salaries[i[1]])}" folium.Marker( location=[i[2][1], i[2][0] - 0.1], icon=folium.DivIcon( html=f"""<div style="font-size: 6pt; color : black">{str}</div>""") ).add_to(map) #Sauvegarde du HTML de la map totalement autonome map.save(outfile='map.html')
attr='1').add_to(m) layerlabel = '<span style="color: {col};">{txt}</span>' flayer = [ folium.FeatureGroup(name=layerlabel.format(col=iconcolors[c], txt=f'cluster {c+1}'), show=True) for c in range(nclusters) ] for cid, row in df_cluster.iterrows(): s = row['spira'] c = row['cluster'] # i = BeautifyIcon(icon=f'{verse}', inner_icon_style=f'color:{iconcolors[c]};font-size:30px;', background_color='transparent', border_color='transparent') if s[-1] == '0': i = folium.DivIcon(html=( f'<svg height="50" width="50"> <text x="0" y="35" fill={iconcolors[c]}>0</text> </svg>' )) else: i = folium.DivIcon(html=( f'<svg height="50" width="50"> <text x="6" y="35" fill={iconcolors[c]}>1</text> </svg>' )) shp = folium.Marker(location=coord_mat[s], popup=s, icon=i) flayer[c].add_child(shp) for l in flayer: m.add_child(l) folium.map.LayerControl(collapsed=False).add_to(m) m.save('spire_all.html') #%% grafico di singola spira spirap = '288_0'
def main(args): parser = argparse.ArgumentParser("") parser.add_argument('-d', '--date') parser.add_argument('-s', '--station') try: global opt opt = parser.parse_args(args[1:]) except: parser.print_help() raise option = webdriver.ChromeOptions() option.add_argument("headless") driver = webdriver.Chrome(ChromeDriverManager().install(), options=option) driver.set_window_size(1300, 1400) gdf_line = geopandas.read_file("mrt_line.geojson") gdf_node = geopandas.read_file("mrt_station.geojson") icon_url = "https://i.imgur.com/GZy08h3.png" for i in range(24): line_dict = json.load( open('{}_{}.json'.format(i, opt.date), encoding='utf-8-sig')) m = folium.Map(location=[25.061, 121.515], zoom_start=13, tiles="CartoDB positron", zoom_control=False) for idx, row in gdf_line.iterrows(): # MultiLineString to list # https://gis.stackexchange.com/questions/319295/how-to-reverse-the-multilinestring-command-to-a-list-of-arrays loc = [list(x.coords) for x in list(row.geometry)][0] loc = [tuple(reversed(x)) for x in loc] weight = line_dict[row["name"]] * 2000 color = Line_Color(row["Line_No"]) folium.PolyLine(loc, color=color, weight=weight, opacity=1).add_to(m) for idx, row in gdf_node.iterrows(): if row["中文站名"] in [ "中山", "台北車站", "大安", "板橋", "古亭", "西湖", "西門", "中正紀念堂", "士林", "忠孝新生", "忠孝復興", "淡水", "北投", "蘆洲", "新莊", "三重", "江子翠", "永安市場", "南港", "景美" ]: loc = list(reversed(list(row["geometry"].coords)[0])) icon = folium.features.CustomIcon(icon_url, icon_size=(16, 16)) folium.Marker(loc, icon=icon).add_to(m) p0 = [25.163, 121.5945] p1 = [25.15, 121.59] p2 = [25.165, 121.62] folium.Marker( p0, icon=folium.DivIcon( html= '<div style="font-size: 40pt; color : black">{:02d}:00</div>'. format(i))).add_to(m) folium.Rectangle([p1, p2], color='#ff7800', fill=True, fill_color='#ffff00', fill_opacity=0.2).add_to(m) m.save("{}_{}.html".format(i, opt.date)) url = "file:///Users/sam/{}_{}.html".format(i, opt.date) driver.get(url) driver.get_screenshot_as_file("{}_{}.png".format(i, opt.date))
from geopy.geocoders import Nominatim geocoder = Nominatim(user_agent='me', timeout=5) temp_data = [] for i in GERMAN_STATES: g = geocoder.geocode(i) path = f'https://api.darksky.net/forecast/{SECRET_KEY}/{g.latitude},{g.longitude}' # ,time response = re.get(path) data = response.json() temp = round((data['currently']['temperature'] -32) * 5/9, 2) temp_data.append((i,g.latitude,g.longitude,temp)) # %% mapping germany_map = folium.Map(location=(50.6118537,9.1909725), zoom_start = 6, titles = 'cartodbpositron') for state, lat, lon, temp in temp_data: #tuple unpacking custom_icon = folium.DivIcon(html=f'<div> {temp} ,</div>') marker = folium.Marker((lat,lon), popup=None, tooltip=(state, temp), icon=custom_icon, draggable=False) circle_market = folium.CircleMarket((lat, lon), radius = 20) marker.add_to(germany_map) circle_marker.add_to(germany_map) # %% save map germany_map.save('germany_map.html')
# if i > 5000: # break loc = (row['LATITUDE'], row['LONGITUDE']) folium.CircleMarker((loc[0], loc[1]), radius=.15, fill=True, opacity=.6, color=colors[int(row.REGION_ID)]).add_to(CHI_map) for region in centers: folium.Marker( location=(region["center_y"], region["center_x"]), icon=folium.DivIcon( html= f"""<div style="background-color:rgba(255,255,255,.7); border-radius:50%; width:20px"> <div style="color:black; font-size:14px; width:fit-content; margin:auto; font-weight: 600">{region["id"]}</div> </div>""")).add_to(CHI_map) CHI_map.save("./web/folium/chi_regions.html") # %% df = pd.read_csv("./data/fatal_incap_frac.csv", index_col="REGION_ID") # %% def calc_color(data): color_sq = colors = np.flip(np.array(Reds[6])) colors = 'Reds' new_data, bins = pd.qcut(data, 6, retbins=True, labels=list(range(6))) color_ton = []
popup_text = popup_text.format(round(df.at[i, 'Members'])) # folium.CircleMarker(location=[ # lat, long], radius=radius, popup=popup_text, fill=True).add_to(marker_cluster) # folium.Marker(location=[ # lat, long], radius=radius, popup=popup_text, fill=True).add_to(marker_cluster) # folium.Marker(location=[lat, long], # icon=folium.DivIcon( # html='''{}'''.format(popup_text)) # ).add_to(m) folium.Marker( location=[lat, long], icon=folium.DivIcon( # icon_size=(100, 100), html='''<div style=" font-size: 12pt; font-family: serif; color: black; text-align: center;"> {} </div>'''.format(popup_text))).add_to(m) # m m.save( '/Users/CN/Documents/Conferences/NCM21/ncm_highlights_article/ncm_world_map/figures/ncm_members_map_log10_with_numbers.html' ) # ------------------------------ Plot with log10 and member numbers as pop-up ------------------------------------ m = folium.Map()
"http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}", attr='default') groupA = folium.FeatureGroup(name='有饭票', control=True) ##创建一个Marker的FeatureGroup groupB = folium.FeatureGroup(name='无饭票', control=True) bankgroup = folium.FeatureGroup(name='网点', control=True) for i, r in bank.iterrows(): lon, lat = coordTransform.bd09_to_gcj02(r['经度'], r['纬度']) folium.Marker( [lat, lon], tooltip=r['网点名称'], icon=folium.DivIcon( icon_size=(80, 72), icon_anchor=(0, 0), html='<div style="font-size: 12px;color: blue; background: white;">' + f"{r['网点名称']}" + '</div>')).add_to(bankgroup) folium.Marker([lat, lon], tooltip=r['网点名称'], icon=folium.Icon(icon='credit-card', prefix='fa')).add_to(bankgroup) for i, r in df1.iterrows(): lon, lat = coordTransform.bd09_to_gcj02(r['lon'], r['lat']) folium.Marker( [lat, lon], tooltip=r['Name'], icon=folium.DivIcon( icon_size=(100, 72), icon_anchor=(0, 0),
fill_color='green', ).add_to(m) else: folium.Circle( location=[data.iloc[i]['Lat'], data.iloc[i]['Long']], radius=data.iloc[i]['Net2019']/100, color='crimson', fill=True, fill_color='crimson', ).add_to(m) for k in range(0,len(data)): folium.map.Marker([data.iloc[k]['Lat']-0.27, data.iloc[k]['Long']+0.49], icon=folium.DivIcon( icon_size=(150,36), icon_anchor=(0,0), html='<div style="font-weight:bold;font-size: 13.5pt">%s</div>' % data.iloc[k]['Net2019'] ) ).add_to(m) for j in range(0,len(data)): folium.map.Marker( [data.iloc[j]['Lat'], data.iloc[j]['Long']+0.59], icon=folium.DivIcon( icon_size=(150,36), icon_anchor=(0,0), html='<div style="font-size: 13.5pt;font-weight:bold">%s</div>' % data.iloc[j]['Diff2'] , ) ).add_to(m) # # Save it as html
weight=1.3, fill_color='red', tooltip=f"{filtered_users.loc[idx]['user_name']}, " f"eBirder since: " f" {int(2019 - filtered_users.loc[idx]['since'])}, " f"Species seen: " f"{int(filtered_users.loc[idx]['n_species'])}", popup= f"<a href={filtered_users.loc[idx]['profile']} target=_blank> eBird profile </a>", fill=True, fill_opacity=0.4, radius=match.pos).add_to(matches_map) folium.Marker( tuple([match.latitude, match.longitude]), icon=folium.DivIcon( html= f"""<div style="font-family: courier new; color: black;">{n}</div>""" )).add_to(matches_map) # plot map matches_map = MapWrapper(matches_map) st.write(matches_map._repr_html_(), unsafe_allow_html=True) # display top results st.markdown('## Best matches :trophy:') for idx, match in enumerate(matches): if filtered_users.iloc[match].profile: st.markdown( f'{idx + 1}. {filtered_users.iloc[match].user_name} -> {filtered_users.iloc[match].profile}' ) else: st.markdown(
fill_opacity=fill_opacity, fill_color='blue' if date < pd.datetime(year=2016, month=4, day=1) else 'red') return c # create a legend for colors/dates legend_html = """<div style="font-family: hack; color: black; font-size: 1.5em; width: 280px; background-color: white; padding: 5px 5px 5px 5px;"> <span style="border-radius: 50%; height: 15px; width: 15px; background-color: blue; display: inline-block"></span> <strong> old bridge</strong><br/>2007-01-28 to 2010-12-28<br/>205 crashes/1430 days <br/>0.143 crashes/day<br/> <br/> <span style="border-radius: 50%; height: 15px; width: 15px; background-color: red; display: inline-block"></span> <strong> new bridge</strong><br/>2016-04-03 to 2018-12-26<br/>391 crashes/997 days <br/>0.392 crashes/day<br/> </div>""" legend = folium.Marker(location=[44.9538, -93.0769], icon=folium.DivIcon(html=legend_html)) #legend.add_to(m) # now add a point for each row in the data for i, row in df_in.iterrows(): # uncomment to specifically view crashes with serious injury #if not row.sev == 2: # continue c = make_circle(lat=row.lat, lon=row.lon, radius=15, fill_opacity=0.3, date=row.date) c.add_to(m) m
# Create a list object Japan Japan = ["Japan"] # Find Japan Japan_row = geo_cv_gdp_pop_loc["name"].isin(Japan) Japan_geo = geo_cv_gdp_pop_loc[Japan_row] # Add the geometry shape of Japan to the interactive map folium.GeoJson(Japan_geo.geometry).add_to(world) # display(world) # PLace text on the map stating "2020 olympic Games" folium.Marker( location=[Japan_geo["lat"], Japan_geo["lng"]], popup=Japan_geo["name"], icon=folium.DivIcon( html= f"""<div style="font-family: courier new; color: orange">{"2020 Olympic Games"}</div>""" )).add_to(world) # display(world) # Tokyo stadium marker Tokyo_Stadium = folium.Marker(location=[35.67785955, 139.71351420013758], tooltip="Tokyo Stadium", icon=folium.Icon(color="orange")).add_to(world) # display(world) # India is the most at risk country # Create India Geodataframe # Create a list object Japan India = ["India"] # Find Japan India_row = geo_cv_gdp_pop_loc["name"].isin(India)
def add_scale_bar(my_map, scale_left_point, scale_right_point, font_size=11): # scale_left_point and scale_right_point should be manually tweaked so that p1-->p2 gives, for example, 5 km or 10 km distance as desired! # For example, following values give a 5 km distance-scale for Helsinki region map: # [60.307873, 25.008584] #lat,lon # [60.307873, 25.099400] #lat,lon # Another example # scale_left_point = [60.329000, 25.008584] #lat,lon # scale_right_point = [60.329000, 25.099400] #lat,lon p1 = scale_left_point p2 = scale_right_point d = np.round(tslib.gis.get_point_distance(p1, p2) / 1000, 2) # print("Distance between the scale-bar's *given* left and right points:", d, "km") # draw the scale-bar: folium.PolyLine( locations=[p1, p2], color='black', weight=2, opacity=1, #tooltip=folium.Tooltip(str(d)+' km') # To also add a hover-over tooltop to the line ).add_to(my_map) # scale's cross at left: cross_p1 = [p1[0] + 0.002, p1[1]] cross_p2 = [p1[0] - 0.002, p1[1]] folium.PolyLine(locations=[cross_p1, cross_p2], color='black', weight=2, opacity=1).add_to(my_map) # scale's cross at right: cross_p1 = [p2[0] + 0.002, p2[1]] cross_p2 = [p2[0] - 0.002, p2[1]] folium.PolyLine(locations=[cross_p1, cross_p2], color='black', weight=2, opacity=1).add_to(my_map) # scale's cross(es) at middle: lon_middle = p1[1] + (p2[1] - p1[1]) / 2 cross_p1 = [p1[0] + 0.001, lon_middle] cross_p2 = [p1[0] - 0.001, lon_middle] folium.PolyLine(locations=[cross_p1, cross_p2], color='black', weight=2, opacity=1).add_to(my_map) # scale numbers from 0 to d, at each cross point folium.map.Marker( [p2[0], p2[1]], icon=folium.DivIcon( icon_size=(5, -10), icon_anchor=(0, 0), html='<div style="width:50px; font-size:' + str(font_size) + 'pt; font-weight:bold">' + str(int(d)) + '</div>', )).add_to(my_map) folium.map.Marker( [cross_p1[0], cross_p1[1]], icon=folium.DivIcon( icon_size=(5, -10), icon_anchor=(0, 0), html='<div style="width:50px; font-size:' + str(font_size) + 'pt; font-weight:bold">' + str(np.round(d / 2, 1)) + '</div>', )).add_to(my_map) folium.map.Marker( [p1[0], p1[1]], icon=folium.DivIcon( icon_size=(5, -10), icon_anchor=(0, 0), html='<div style="width:50px; font-size:' + str(font_size) + 'pt; font-weight:bold">' + '0' + '</div>', )).add_to(my_map) # write 'km' folium.map.Marker( [p2[0], p2[1]], icon=folium.DivIcon( icon_size=(-10, +25), icon_anchor=(0, 0), html='<div style="width:50px; font-size:' + str(font_size) + 'pt; font-weight:bold">' + 'km' + '</div>', )).add_to(my_map)
def showMap(self): homeLoc['lat'] = float(self.mylat.text()) homeLoc['lon'] = float(self.mylon.text()) # tiles = 'OpenStreetMap' # tiles = 'Stamen Terrain' # tiles = 'Stamen Toner' # tiles = 'CartoDB dark_matter' # tiles = "CartoDB positron" self.map1 = folium.Map( location=[homeLoc['lat'],homeLoc['lon']], tiles=self.combomap.currentText(), \ zoom_start=13 ) folium.Marker([homeLoc['lat'],homeLoc['lon']], #Make color/style changes here icon = folium.Icon(color='blue'), popup = 'Home node', ).add_to(self.map1) if(self.radiob.isChecked()): #read connessioni in meshDB and mark all record = combobox selected qr = "select user,lat,lon,dist,ora,snr from connessioni where data = '"+self.combobox.currentText()+ \ "' and dist is not null" conn = dba.connect('meshDB.db') cur = conn.cursor() rows = cur.execute(qr) datas = rows.fetchall() prevd = 0 for row in datas: user = row[0] lat = row[1] lon = row[2] dist = row[3] ora = row[4] snr = row[5] dist = round(dist) dist = dist/1000 if(abs(dist-prevd)>0.01): prevd = dist folium.Marker([lat,lon], icon = folium.Icon(color='red'), popup = user+'   <br>ora: '+ \ ora+'<br>snr: '+str(snr)+'<br>Km: '+str(dist), ).add_to(self.map1) folium.Marker([lat,lon], icon=folium.DivIcon(html=f"""<div style='font-size: 22px; font-weight: bold;'>{user}</div>""") ).add_to(self.map1) print("Mark added") cur.close() conn.close() else: #add a marker for each node in nodeInfo for node in nodeInfo: if('lat' in node): dist = haversine([homeLoc['lat'],homeLoc['lon']],[node['lat'],node['lon']]) dist = round(dist) dist = dist/1000 ora = node['time'].split(' ')[1] if(dist > 0.01): folium.Marker([node['lat'],node['lon']], icon = folium.Icon(color='red'), popup = node['user']+'   <br>ora: '+ \ ora+'<br>snr: '+str(node['snr'])+'<br>Km: '+str(dist), ).add_to(self.map1) folium.Marker([node['lat'],node['lon']], icon=folium.DivIcon(html=f"""<div style='font-size: 22px; font-weight: bold;'>{node['user']}</div>""") ).add_to(self.map1) data = io.BytesIO() self.map1.save(data, close_file=False) self.map1 = QtWebEngineWidgets.QWebEngineView() self.map1.setHtml(data.getvalue().decode()) self.map1.page().profile().setUrlRequestInterceptor(self.interceptor) self.tabs.removeTab(2) self.tab3.destroy() self.tab3 = QWidget() self.tabs.addTab(self.tab3,"GeoMap") self.tab3.layout = QVBoxLayout() self.tab3.layout.addWidget(self.map1) self.tab3.setLayout(self.tab3.layout) self.map1.show()
print(style_dict2) ##data distgeometry_df = final_df2[['geometry']] distgeometry_gdf = gpd.GeoDataFrame(distgeometry_df) distgeometry_gdf = distgeometry_gdf.drop_duplicates().reset_index() distgeometry_gdf.head() slider_map2 = folium.Map(location=[25.0007, 67.0011], min_zoom=2, max_bounds=True,tiles='cartodbpositron') TimeSliderChoropleth(data=distgeometry_gdf.to_json(),styledict=style_dict2,).add_to(slider_map2) colour_bar2.add_to(slider_map2) colour_bar2.caption = "Number of Crime Cases" #Markers div1 = folium.DivIcon(html=('<svg height="50" width="50">' '<text x="10" y="10" fill="black">East</text>' '</svg>')) div2 = folium.DivIcon(html=('<svg height="50" width="50">' '<text x="10" y="10" fill="black">West</text>' '</svg>')) div3 = folium.DivIcon(html=('<svg height="50" width="50">' '<text x="10" y="10" fill="black">South</text>' '</svg>')) div4 = folium.DivIcon(html=('<svg height="50" width="50">' '<text x="10" y="10" fill="black">Central</text>' '</svg>')) folium.Marker((24.8832, 67.1060), icon=div1).add_to(slider_map2) folium.Marker([24.9713, 66.9511], icon=div2).add_to(slider_map2) folium.Marker([24.8625, 67.0046], icon=div3).add_to(slider_map2) folium.Marker([24.9551, 67.0044], icon=div4).add_to(slider_map2)
def plot_to_map( camera_pano_path, mountains_in_sight, coordinates, filename, dem_file, converter, locs=None, mountains=None, images=None, ): p_i("Creating Interactive Map") c_lat, c_lon, _, _ = coordinates ll, ul, ur, lr = location_handler.get_raster_bounds(dem_file) load_dotenv() MAPBOX_TOKEN = os.getenv("MAPBOX_TOKEN") MAPBOX_STYLE_URL = os.getenv("MAPBOX_STYLE_URL") m = folium.Map( [c_lat, c_lon], tiles=None, zoom_start=12, scrollWheelZoom=False, ) folium.TileLayer( location=[c_lat, c_lon], tiles=MAPBOX_STYLE_URL, API_key=MAPBOX_TOKEN, attr="Christian Hein", name="Settings", ).add_to(m) min_ele, max_ele = 10000, 0 for i in mountains: if i.location.elevation > max_ele: max_ele = i.location.elevation if i.location.elevation < min_ele: min_ele = i.location.elevation ########################################################################### ########################################################################### # All mountains in dataset if mountains: mountains_fg = folium.FeatureGroup(name="All Mountains", show=False) m.add_child(mountains_fg) [(folium.Marker( location=(i.location.latitude, i.location.longitude), popup="%s\n%im" % ( str(i.name), i.location.elevation, ), icon=folium.DivIcon(html=get_glyph( f"am-{i.name}-{int(i.location.elevation)}", "#755239", i.location.elevation, min_ele, max_ele)), zIndexOffset=1, ).add_to(mountains_fg)) for i in mountains] ########################################################################### ########################################################################### # Mountains in sight if mountains_in_sight: mountains_in_sight_fg = folium.FeatureGroup(name="Visible Mountains", show=True) m.add_child(mountains_in_sight_fg) [(folium.Marker( location=(i.location.latitude, i.location.longitude), popup="%s\n%im" % ( str(i.name), i.location.elevation, ), icon=folium.DivIcon(html=get_glyph( f"vm-{i.name}-{int(i.location.elevation)}", "#426877", i.location.elevation, min_ele, max_ele)), zIndexOffset=10, ).add_to(mountains_in_sight_fg)) for i in mountains_in_sight] ########################################################################### ########################################################################### # Other images in dataset if images: images_fg = folium.FeatureGroup(name="Visible Images", show=True) m.add_child(images_fg) for im in images: encoded = base64.b64encode(open(im.thumbnail_path, "rb").read()) html = f''' <!doctype html> <html> <head> <style> .redirect-button {{ color: #fff; cursor: pointer; background-color: #6c757d; border-color: #6c757d; display: inline-block; font-weight: 400; line-height: 1.5; text-align: center; text-decoration: none; vertical-align: middle; padding: .375rem .75rem; border-radius: .25rem; transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out; }} .redirect-button:hover {{ color: #fff; background-color: #5c636a; border-color: #545b62; }} </style> <script type="text/javascript"> function redirect() {{ console.log("Redirecting to: ", "{im.name}"); window.parent.parent.postMessage("{im.name}", '*'); }} </script> </head> <body> <button class="redirect-button" onclick="redirect();">View image</button> <img src="data:image/JPG;base64,{encoded.decode("UTF-8")}"> </body> </html> ''' iframe = folium.IFrame(html, width=450 + 20, height=150 + 20) popup = folium.Popup(iframe, max_width=470) folium.Marker( location=(im.location.latitude, im.location.longitude), popup=popup, icon=folium.Icon(color="orange", icon="camera"), zIndexOffset=12, ).add_to(images_fg) ########################################################################### ########################################################################### # Current viewpoint encoded = base64.b64encode(open(camera_pano_path, "rb").read()) html = f''' <!doctype html> <html> <img src="data:image/JPG;base64,{encoded.decode("UTF-8")}"> </html> ''' iframe = folium.IFrame(html, width=450 + 20, height=150 + 20) popup = folium.Popup(iframe, max_width=450) folium.Marker( location=[c_lat, c_lon], popup=popup, icon=folium.Icon(color="green", icon="camera"), zIndexOffset=13, ).add_to(m) ########################################################################### ########################################################################### # Visible coordinates if locs: locs_fg = folium.FeatureGroup(name="Retrieved Coordinates", show=True) m.add_child(locs_fg) for i in locs: loc = converter.convert(*i) folium.Circle( location=(loc.latitude, loc.longitude), color="#0a6496", fill=True, fill_color="#0a6496", fill_opacity=1, radius=15, ).add_to(locs_fg) ########################################################################### ########################################################################### # Raster bounds raster_bounds = folium.FeatureGroup(name="Raster Bounds", show=False) m.add_child(raster_bounds) folium.PolyLine(locations=[ll, ul, ur, lr, ll], color="#d63e29", zIndexOffset=15).add_to(raster_bounds) ########################################################################### ########################################################################### # Legend template = """ {% macro html(this, kwargs) %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div id='maplegend' class='maplegend' style='position: absolute; z-index:9999; border:2px solid grey; background-color:rgba(255, 255, 255, 0.8); border-radius:6px; padding: 10px 10px 1px; font-size:16px; font-weight:500; right: 20px; bottom: 24px;'> <div class='legend-scale'> <ul class='legend-labels'> <li><span style='background:#71b025;opacity:1.0;'></span>Current Viewpoint</li> <li><span style='background:#f69730;opacity:1.0;'></span>Images in dataset</li> <li><span style='background:#755239;opacity:1.0;'></span>All mountains in dataset</li> <li><span style='background:#426877;opacity:1.0;'></span>Mountains in sight</li> <li><span style='background:#d63e29;opacity:1.0;'></span>DEM bounding box</li> </ul> </div> </div> </body> </html> <style type='text/css'> .maplegend .legend-title { text-align: left; margin-bottom: 5px; font-weight: bold; font-size: 90%; } .maplegend .legend-scale ul { margin: 0; margin-bottom: 5px; padding: 0; float: left; list-style: none; } .maplegend .legend-scale ul li { font-size: 80%; list-style: none; margin-left: 0; line-height: 18px; margin-bottom: 2px; } .maplegend ul.legend-labels li span { display: block; float: left; height: 16px; width: 30px; margin-right: 5px; margin-left: 0; border: 1px solid #999; } .maplegend .legend-source { font-size: 80%; color: #777; clear: both; } .maplegend a { color: #777; } </style> {% endmacro %}""" macro = MacroElement() macro._template = Template(template) ########################################################################### ########################################################################### # Add to map folium.LayerControl().add_to(m) m.get_root().add_child(macro) # m.add_child(Fullscreen(position='topleft')) m.save(filename)
### creating gif images, note requirements! # - this uses selenium which needs to be installed # - the geckodriver binary is expected to exist in the directory (hint: just create a symlink to it) # create a legend for colors/dates legend_html = """<div style="font-family: hack; color: black; font-size: 1.5em; width: 280px; background-color: white; padding: 5px 5px 5px 5px;"> <span style="border-radius: 50%; height: 15px; width: 15px; background-color: blue; display: inline-block"></span> <strong> old bridge</strong><br/>2007-01-28 to 2010-12-28<br/>205 crashes/1430 days <br/>0.143 crashes/day<br/> <br/> <span style="border-radius: 50%; height: 15px; width: 15px; background-color: red; display: inline-block"></span> <strong> new bridge</strong><br/>2016-04-03 to 2018-12-26<br/>391 crashes/997 days <br/>0.392 crashes/day<br/> </div>""" legend = folium.Marker(location=[44.9538, -93.0769], icon=folium.DivIcon(html=legend_html)) # helper function to spit out circles def make_circle(lat, lon, radius, fill_opacity, date): c = folium.Circle(location=[lat, lon], radius=radius, fill=True, stroke=False, fill_opacity=fill_opacity, fill_color='blue' if date < pd.datetime(year=2016, month=4, day=1) else 'red') return c # create map object and fit to target area m = folium.Map(location=[left_lat, left_lon], zoom_control=False, tiles='cartodbpositron', width=550, height=550) m.fit_bounds(bounds=bbox) legend.add_to(m) date_html = """<div style="font-family: hack; color: black; font-size: 1.5em;">2007-01</div>""" date_legend = folium.Marker(location=[44.9383, -93.0877], icon=folium.DivIcon(html=date_html)) date_legend.add_to(m)
def contentWidget(self): # select region v box 1 select_region_h_box1 = QHBoxLayout() # selection one notice select_region_h_box1.addSpacing(10) # selection label 1 self.select_region_label = QLabel("Select Region", self) select_region_h_box1.addWidget(self.select_region_label) # drop down button self.select_region_combo = QComboBox(self) self.select_region_combo.addItems(self.italy_regions) select_region_h_box1.addWidget(self.select_region_combo) # push button self.select_region_botton = QPushButton("Check Region", self) self.select_region_botton.pressed.connect(self.italyRegionClicked) select_region_h_box1.addWidget(self.select_region_botton) # select region v box 2 select_region_h_box2 = QHBoxLayout() select_region_h_box2.addSpacing(10) # selection label 1 self.select_region_label = QLabel("Italy against", self) select_region_h_box2.addWidget(self.select_region_label) # drop down button (combo ) self.select_euro_combo = QComboBox(self) self.select_euro_combo.addItems(self.european_countries) select_region_h_box2.addWidget(self.select_euro_combo) # push button self.compare_button = QPushButton("Compare", self) self.compare_button.pressed.connect(self.europeanCountriesClicked) select_region_h_box2.addWidget(self.compare_button) # selection main V box select_region_main_v_box = QVBoxLayout() # An overall language pull down menu is being requested at the very top of the GUI # with the option of English and Italian labelling language_h_box = QHBoxLayout() self.language_lbl = QLabel("Select Language", self) self.language_combobox = QComboBox() # language option options = ([ ('English', 'en'), ('Italian', 'it'), ('Spanish', 'es'), ('Chinese', 'zh-CN'), ]) # add language and change language for i, (text, lang) in enumerate(options): self.language_combobox.addItem(text) self.language_combobox.setItemData(i, lang) language_h_box.addWidget(self.language_lbl) # on index changed self.language_combobox.currentIndexChanged.connect( self.languageChanged) language_h_box.addWidget(self.language_combobox) language_h_box.addStretch() # add language_h_box layout select_region_main_v_box.addLayout(language_h_box) # Italy Region Covid Report self.italy_lbl = QLabel("Italy Region Covid Report", self) self.italy_lbl.setStyleSheet("border: 0.5px solid gray") select_region_main_v_box.addWidget(self.italy_lbl) select_region_main_v_box.addLayout(select_region_h_box1) select_region_main_v_box.setSpacing(15) self.euro_text = QLabel( "Italy Covid report against European countries", self) self.euro_text.setStyleSheet("border: 0.5px solid gray") select_region_main_v_box.addWidget(self.euro_text) select_region_main_v_box.addLayout(select_region_h_box2) select_region_main_v_box.addStretch() # for region map and demographic region_map_box = QVBoxLayout() self.coordinate_title = "This is a title" self.coordinate = coordinate['Campania'] m = folium.Map(tiles="Stamen Terrain", zoom_start=6, location=self.coordinate) # create HTML for pop up def foliumHtml(lo): # get stats if lo != "Italy": stats = self.core.getRegionStats(str(lo)) return f""" <h1 style='color:#7b113a;'> {lo} </h1> <hr/> <p style='color:#7b113a;font-size:20px;'>Region Population: {stats['region_population']}</p> <p style='color:#7b113a;font-size:20px;'>Total Covid Case: {stats['case_number']}</p> <p style='color:#7b113a;font-size:20px;'>Daily Cases: {stats['expectedChanges']}</p> <p style='color:#7b113a;font-size:20px;'>Percentage: {stats['percentage']}%</p> """ else: return f""" <h1> {lo}</h1> <p>European country with a long Mediterranean coastline, has left a powerful mark on Western culture and cuisine.</p> """ # add marker one by one on the map for lo in coordinate: # add pop ups html = foliumHtml(lo) iframe = folium.IFrame(html=html, width=300, height=250) popUp = folium.Popup(iframe, max_width=2650) # Marker starts here folium.Marker(location=coordinate[lo], popup=popUp, icon=folium.DivIcon(html=f""" <div><svg> <circle cx="50" cy="50" r="40" fill="#7b113a" opacity=".4"/> <rect x="35", y="35" width="30" height="30", fill="#fff600", opacity=".3" </svg></div>""")).add_to(m) # save map data to data object data = io.BytesIO() m.save(data, close_file=False) webView = QWebEngineView() webView.setHtml(data.getvalue().decode()) region_map_box.addWidget(webView) # main box top - bottom h_box = QHBoxLayout() h_box.addLayout(select_region_main_v_box) h_box.addLayout(region_map_box) self.setLayout(h_box)
countries_with_coordinates = pd.read_csv('african_countries_with_coords.csv') covid_data_rich = pd.merge(df, countries_with_coordinates, on='Country') choropleth_data = df[df['Country'].isin(africa_shp['COUNTRY'])] choropleth_data.reset_index() print(choropleth_data.head()) # add a latitude and logitude property to the countries json objects for plotting # initialize map africa = folium.Map([-0.7832, 28.5085], zoom_start=3.48, tiles=None) folium.TileLayer(tiles='CartoDB positron',name="CartoDB Positron").add_to(africa) folium.TileLayer(tiles='CartoDB dark_matter',name="CartoDB Dark_Matter").add_to(africa) folium.LayerControl().add_to(africa) for idx, country in covid_data_rich.iterrows(): # generate and display marker icon = folium.DivIcon(html=f'<font color="red">{country["TotalConfirmed"]}</font>') folium.Marker([country['latitude'], country['longitude']], icon=icon).add_to(africa) # Add the color for the chloropleth: folium.GeoJson(africa_shp).add_to(africa) # save to html title_html = ''' <h3 align="center" style="font-size:20px"><b>Covid-19 TotalConfirmed Cases Africa</b></h3> ''' africa.get_root().html.add_child(folium.Element(title_html)) africa.save('covid.html') # driver = webdriver.Chrome(executable_path='/home/macbuntu/PycharmProjects/VisualizeTheRona/chromedriver')
0, 0.015 * total, 0.15 * total, 0.3 * total, 0.7 * total, total + 1 ], fill_opacity=1, line_opacity=1, legend_name='Confirmed Cases', highlight=True, ).add_to(folium_map) for i in range(0, len(df["Name"])): temp = df.iloc[i]["Name"] if temp == "Federal Capital Territory": temp = "FCT" folium.Marker( [df.iloc[i]["lon"], df.iloc[i]["lat"]], icon=folium.DivIcon(html=f"""<div style = "font-family: fantasy ; color: black; font-size: smaller; font-weight: boldest"> {"{}".format(temp) }</div> """)).add_to(folium_map) chloro.geojson.add_child( folium.features.GeoJsonTooltip( ["Name", "Confirmed Cases", "Discharged", "Death"])) folium.LayerControl().add_to(folium_map) return folium_map._repr_html_() if __name__ == "__main__": app.run()