def map_objects(): map = folium.Map( tiles='Stamen Toner', location=[df['Lat'][0], df['Lon'][0]], zoom_start=10, ) for lat, lon, sv_photo, address in zip(df['Lat'], df['Lon'], df['street_view'], df['address_price']): encoded = base64.b64encode(open(sv_photo, 'rb').read()).decode() #zillow = f'{address}: $$$' html = '<img src="data:image/jpeg;base64,{}" >'.format resolution, width, height = 75, 50, 25 iframe = IFrame(html(encoded), width=300, height=600) popup = folium.Popup(iframe, max_width=1000) icon = folium.Icon(color="red", icon="home") marker = folium.Marker(location=[lat, lon], popup=popup, icon=icon, tooltip=address) marker.add_to(map) map.save('multi_map_200.html')
def add_points_with_images(self, points: List[Point], images: np.ndarray, color: str = 'red', resolution=100, tooltip='Click me!'): ''' add points with images. Args: points: the points to show on the map images: the images that pop when clicking. len(images) should be len(points) color: the color of the points resolution: tooltip: text that comes on hover Returns: ''' _, height, width = images.shape scale = 30 for point, image in zip(points, images): if type(point) is Point: point = [point.x, point.y] html = '<img src="data:image/png;base64,{}">'.format encoded = self.get_encoded_image(image, resolution=resolution, scale=scale) iframe = IFrame(html(encoded), width=(width * scale) + 20, height=(height * scale) + 20) popup = folium.Popup(iframe, max_width=1530, max_height=1300) icon = folium.Icon(color=color, icon="ok") folium.Marker(point[::-1], popup=popup, tooltip=tooltip, icon=icon).add_to(self.map)
def generate_map(postal_code): og_name = postal_code if postal_code in postal_codes: data = postal_codes[postal_code] else: data = None # sudo fuzzy matching for missing postal code while data is None: postal_code = postal_code[:-1] for code in codes: if postal_code in code: postal_code = code break if postal_code in postal_codes: data = postal_codes[postal_code] m = folium.Map(location=[data['long'], data['lat']], zoom_start=16) html = f'<b>Crime Score:</b> {data["crime_score"]} <br> \ <b>Traffic Score:</b> {data["traffic_score"]} <br> \ <b>Emergency Score:</b> {data["emerg_score"]} <br> \ {style}' iframe = IFrame(html=html, width=200, height=100) popup = folium.Popup(iframe, max_width=200) folium.Marker([data['long'], data['lat']], popup=popup).add_to(m) m.save(f'templates/{og_name}.html')
def map_points(pois, tiles='OpenStreetMap', width='100%', height='100%', show_bbox=False): """Returns a Folium Map displaying the provided points. Map center and zoom level are set automatically. (Adapted from LOCI) Args: pois (GeoDataFrame): A GeoDataFrame containing the POIs to be displayed. tiles (string): The tiles to use for the map (default: `OpenStreetMap`). width (integer or percentage): Width of the map in pixels or percentage (default: 100%). height (integer or percentage): Height of the map in pixels or percentage (default: 100%). show_bbox (bool): Whether to show the bounding box of the GeoDataFrame (default: False). Returns: A Folium Map object displaying the given POIs. """ # Set the crs to WGS84 if pois.crs['init'] != '4326': pois = pois.to_crs({'init': 'epsg:4326'}) # Automatically center the map at the center of the bounding box enclosing the POIs. bb = bbox(pois) map_center = [bb.centroid.y, bb.centroid.x] # Initialize the map m = folium.Map(location=map_center, tiles=tiles, width=width, height=height) # Automatically set the zoom level m.fit_bounds(([bb.bounds[1], bb.bounds[0]], [bb.bounds[3], bb.bounds[2]])) # Columns containing scores per attribute score_cols = [col for col in pois.columns if '_score' in col] # Column containing the entity name name_col = 'name' # Create chart plots in the background # Change to a backend that does not display to the user in order to avoid showing plots when creating them plt_backend=matplotlib.get_backend() matplotlib.use('Agg') # Add pois to a marker cluster coords, popups = [], [] for idx, row in pois.iterrows(): coords.append([row.geometry.y, row.geometry.x]) label = str(row['id']) + '<br>' + str(row['name']) iframe = IFrame(html=label, width=200, height=80) popups.append(folium.Popup(iframe, min_width=100, max_width=200, parse_html=True)) poi_layer = folium.FeatureGroup(name='pois') poi_layer.add_child(MarkerCluster(locations=coords, popups=popups)) m.add_child(poi_layer) # Restore the native backend for plots matplotlib.use(plt_backend) if show_bbox: folium.GeoJson(bb).add_to(m) return m
def getHref(url): html = """ <a href="{url}" target="_blank">{url}</a> """.format(url=url) iframe = IFrame(html=html, width=300, height=100) popup = folium.Popup(iframe, max_width=2650) return popup
def make_marker(p, location, fname): html = file_html(p, CDN, fname) iframe = IFrame(html, width=width + 45, height=height + 80) popup = folium.Popup(iframe, max_width=2650) icon = folium.Icon(color="green", icon="stats") marker = folium.Marker(location=location, popup=popup, icon=icon) return marker
def get_popup_image(path_to_img: str, resolution=1, height=400, width=500): with open(path_to_img, 'rb') as img: pop_img = base64.b64encode(img.read()).decode('utf-8') html_img = '<div><img src="data:image/png;base64,{}">{}</div>'.format( pop_img, description) iframe = IFrame(html_img, width=(width*resolution) + 20, height=(height*resolution)+20) popup = folium.Popup(iframe, max_width=2650) return popup
def plotdataPop(data, vals): """ simple data popup, take in data and values, plots it as a mpld3 plot allowing for interaction, add it to an Iframe what then can be used in a folium map popup returns a popup Last edit: 25/05/2019 -added exceptions with line number """ try: df = data[vals] # print(df) width = 300 height = 320 #If more than one varable add fadding alpha = 1 if len(vals) > 1: alpha = 0.8 #define figure fig, ax = plt.subplots(figsize=(4, 4)) #plot data for val in vals: ax.plot(df[val], alpha=alpha, label=val) ax.legend() #Plot information ax.set_ylabel('Mass concentration (ug/m^3)') ax.set_xlabel('') #solving issue with x labes being cut in 1/2 #set tile based of time interval ax.set_title(df.index[0].strftime("%Y/%m/%d") + "-(" + df.index[0].strftime("%H:%M") + " to " + df.index[len(df) - 1].strftime("%H:%M")) ax.grid() #grid #setppop up in mld3 now = datetime.datetime.now() date = df.index[0].strftime("%Y%m%d") #get the date #save=datetime.datetime.strptime(now,"%HH%MM%SS") figname = 'popup_plot' + date + str(now.microsecond) + '.html' mpld3.save_html(fig, 'Mapoutput//' + figname) time.sleep(0.1) a = mpld3.fig_to_html(fig) #put pop up in iframe format ready to be put into the popup iframe = IFrame(a, width=(width), height=(height)) popup = folium.Popup(iframe, max_width=600) return popup except Exception as e: print("Error in GPS Data cirlce generation") print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno)) print(type(e)) print(e.args) pass
def iframe_img(mymap, resolution, width, height, img_src, lat, lan): html = '<img src=' + img_src + '>' iframe = IFrame(html, width=(width * resolution) + 20, height=(height * resolution) + 20) popup = folium.Popup(iframe, max_width=2650) icon = folium.Icon(color="red", icon="ok") marker = folium.Marker(location=[lat, lan], popup=popup, icon=icon) marker.add_to(mymap)
def iframe_img_para(mymap, resolution, width, height, img_src, lat, lan, paragraph): html = '<img src=' + img_src + ' style="width:70%"">' html += '<pre>' + paragraph + '</pre>' iframe = IFrame(html, width=(width * resolution) + 20, height=(height * resolution) + 20) popup = folium.Popup(iframe, max_width=2650) icon = folium.Icon(color="red", icon="ok") marker = folium.Marker(location=[lat, lan], popup=popup, icon=icon) marker.add_to(mymap)
def make_marker(p, station): lons = stations_keys(config, key="lon") lats = stations_keys(config, key="lat") lon, lat = lons[station], lats[station] html = file_html(p, CDN, station) iframe = IFrame(html, width=width + 40, height=height + 80) popup = folium.Popup(iframe, max_width=2650) icon = folium.Icon(color="green", icon="stats") marker = folium.Marker(location=[lat, lon], popup=popup, icon=icon) return marker
def add_loc_info(loc_info, loc, map): loc_info = loc_info.reset_index() species = [] for specie, strain, clade, link in zip(loc_info['Species'], loc_info['Strain'], loc_info['Clade'], loc_info['Link']): link_ncbi = '<a href={}>{}</a>'.format(link, strain) species.append([specie, clade, link_ncbi]) table_species = pd.DataFrame(species, columns=["Species", "Clade", "Strain"]) table_species['Species'] = [ f'<i>{x}</i>' for x in table_species['Species'] ] # Convert table to html str_io = io.StringIO() table_species.to_html(buf=str_io, classes='table table-striped', border=0.5, col_space=100, justify="center", escape=False, index=False) html_str = str_io.getvalue().replace('table border="0.5"', 'table border="0.5" align="center"') html_str = html_str.replace('<td>', '<td style = "text-align:center">') encoded = base64.b64encode(open('plot_{}.png'.format(loc), 'rb').read()).decode() html = f'''<TABLE BORDER=0> \ <TR> <TD> <img ALIGN="Right" src="data:image/png;base64,{encoded}" width="400" height="400" > \ </TD> <TD> <h1 style="text-align: center; vertical-align: middle;"> Location: {loc} <br/><br/> \ {html_str} </TD> </TR> </TABLE>''' iframe = IFrame(html, width=(width * resolution) + 200, height=(height * resolution) - 100) marker = folium.Marker(location=[loc_info['LAT'][0], loc_info['LON'][0]], popup=folium.Popup(iframe, max_width=2650), icon=folium.Icon(icon_color='green', icon="ok")) marker.add_to(map)
def add_volcanoes(map): map = map volcanoes = read_excel('volcanoes.xlsx').iloc[1:, [1, 2, 4, 5, 6]] latitudes, longitudes = volcanoes['Latitude'], volcanoes['Longitude'] name = volcanoes['Volcano Name'] country = volcanoes['Country'] elevation = volcanoes['Elev'] fg_volcanoes = FeatureGroup(name='Volcanoes', show=False) def color_by_elevation(elev): if type(elev) == str: return 'white' if elev <= -4000: return 'darkblue' if elev <= -2000: return 'cadetblue' if elev <= 0: return 'lightblue' if elev <= 2000: return 'orange' if elev <= 4000: return 'red' if elev <= 6000: return 'darkred' else: return 'black' for i in range(len(volcanoes)): i += 1 if isnan(elevation[i]): elevation[i] = 'Unknown' if name[i] == 'Unnamed': html = f'Volcano name:{name[i]}<br>Height: {elevation[i]} m<br> {country[i]}' else: html = f'Volcano name:<b4> <a href="https://www.google.com/search?q={name[i]} volcano" target="_blank">{name[i]}</a><br> \ Height: {elevation[i]} m<br> {country[i]}' iframe = IFrame(html=html, width=200, height=100) coords = (latitudes[i], longitudes[i]) fg_volcanoes.add_child( CircleMarker(location=coords, popup=Popup(iframe), color="gry", fill_color=color_by_elevation(elevation[i]), fill_opacity=0.9, radius=6)) i -= 1 map.add_child(fg_volcanoes)
def _folium(outfile): colors = list(zip(color)) locations = list(zip(lat, long)) popups = [] popup_list = list(zip(hosts, country_array, state_array)) for i in popup_list: shodan_data = [] try: host = api.host(i[0]) country = i[1] shodan_ip = host['ip_str'] shodan_org = str(host.get('org', 'n/a')) shodan_os = str(host.get('os', 'n/a')) for item in host['data']: shodan_ports = "Port: %s <br>Banner: %s <br>" % (item['port'], item['data']) s1 = shodan_ports.replace("\n", "<br />") s = s1.replace("\r", "<br />") shodan_data.append(s) time.sleep(2) except shodan.APIError as e: print(e.value) shodan_ip = i[0] country = i[1] shodan_org = "No data available" shodan_os = "No data available" shodan_data = "--No data available--" html = """ <p>IP: """ + shodan_ip + """ </p> <p>Country: """ + country + """ </p> <p>Organization: """ + shodan_org + """ </p> <p>OS: """ + shodan_os + """ </p> <p> """ + str(shodan_data)[2:-2] + """ </p> """ iframe = IFrame(html=html, width=300, height=300) popups.append(iframe) m = folium.Map(location=[np.mean(lat), np.mean(long)], tiles='cartodbdark_matter', zoom_start=2) m.add_child(MarkerCluster(locations=locations, popups=popups, icons=color)) m.save(outfile)
def _convert_spotted_location_to_popup(self, address, time: str): popup_msg = dumps(address, ensure_ascii=False).split('"') popup_formatted = "{}<br><br>".format(time) count = 1 while count < len(popup_msg) - 4: popup_formatted += "{}:<br>{}<br><br>".format( popup_msg[count].upper(), popup_msg[count + 2], ) count += 4 return Popup(IFrame(popup_formatted, width=200, height=280), max_width=200)
def create_popups_from_template( location, html_template=POPUP_TEMPLATE, *args, **kwargs ): iframe = IFrame( html=html_template(*args, **kwargs), width=400, height=200 ) popup = Popup( iframe, max_width=500 ) return popup
def jpg2popup(h): encoded = base64.b64encode(open(outdir + h.name + '.jpg', 'rb').read()).decode() html = '<img src="data:image/jpeg;base64,{}">'.format resolution, width, height = 20, 40, 17 iframe = IFrame(html(encoded), width=(width * resolution) + 20, height=(height * resolution) + 20) popup = folium.Popup(iframe, max_width=1000) fgn.add_child( folium.CircleMarker(location=hobo.coords, radius=8, color='grey', fill_color='green', fill_opacity=0.8, popup=popup))
def add_news(mymap, news_lat, news_lon, news_msg, news_img_link, news_link): resolution, width, height = 75, 7, 3 news_where = [news_lat, news_lon] news_msg = news_msg icon = folium.Icon(color="red", icon="ok") news_img = '<img src=' + news_img_link + '>' news_atag = '<a href=' + news_link + ' target="_blank">' + news_img + '</a>' #print(news_atag) news_iframe = IFrame(news_atag, width=(width * resolution) + 20, height=(height * resolution) + 20) news_popup = folium.Popup(news_iframe, max_width=2650, parse_html=True) folium.Marker(news_where, tooltip=news_msg, icon=icon, popup=news_popup).add_to(mymap)
def add_cities(map): cities = read_csv('worldcities.csv').iloc[:, [1, 2, 3, 4, 7, 8, 9]] latitudes, longitiudes = cities['lat'], cities['lng'] name = cities['city_ascii'] country = cities['country'] admin_name = cities['admin_name'] population = cities['population'] fg_05to1m_cities = FeatureGroup(name='500k-1m', show=False) fg_1to2m_cities = FeatureGroup(name='1m-2m', show=False) fg_2to5m_cities = FeatureGroup(name='2m-5m', show=False) fg_5to10m_cities = FeatureGroup(name='5m-10m', show=False) fg_more_than_10m_cities = FeatureGroup(name='>10m', show=False) for i in range(len(cities)): if nan_to_num(population[i]) < 500000: continue html = f'City: <a href="https://www.google.com/search?q={name[i]} city" target="_blank">{name[i]}</a><br> \ Admin: {admin_name[i]}<br> \ Country: {country[i]}<br>\ Population: {population[i]}' iframe = IFrame(html=html, width=200, height=200) coords = (latitudes[i], longitiudes[i]) if population[i] < 1000000: fg_05to1m_cities.add_child( Marker(location=coords, popup=Popup(iframe))) elif population[i] < 2000000: fg_1to2m_cities.add_child( Marker(location=coords, popup=Popup(iframe))) elif population[i] < 5000000: fg_2to5m_cities.add_child( Marker(location=coords, popup=Popup(iframe))) elif population[i] < 10000000: fg_5to10m_cities.add_child( Marker(location=coords, popup=Popup(iframe))) elif population[i] >= 1000000: fg_more_than_10m_cities.add_child( Marker(location=coords, popup=Popup(iframe))) map.add_child(fg_05to1m_cities) map.add_child(fg_1to2m_cities) map.add_child(fg_2to5m_cities) map.add_child(fg_5to10m_cities) map.add_child(fg_more_than_10m_cities)
def gera_icones_da_ufpb(logo, dict_logo, dict_coordenadas, html1, tooltip, mapa_, arquivo_json, dado): #AQUIII #picture1 = base64.b64encode(open('C:\\Users\\gabri\\OneDrive\\Área de Trabalho\\Pasta de backup\\ODE\\logos\\' + logo ,'rb').read()).decode() files = limpa_nome_arquivo(logo) file = files.upper() cur = chama_cursos[file] if dado == 0: html1 = f""" <h1> Informações sobre o {file}</h1> Nome do Centro: {centro_extenso[file]}<br><br> Ano de criação: {chama_ano_criacao[file]}<br><br> Número de departamentos: {chama_departamentos[file]}<br><br> Cursos: {', '.join(str(x) for x in cur)}<br><br> Diretor: {chama_diretor[file]}<br><br> Vice-Diretor: {chama_vice[file]}<br><br> Assessor(es): {chama_assessor[file]}<br><br> """ else: html1 = f""" <h1> Informações sobre o {file}</h1> Nome do Centro: {centro_extenso[file]}<br><br> Ano de criação: {chama_ano_criacao[file]}<br><br> Número de departamentos: {chama_departamentos[file]}<br><br> Cursos: {', '.join(str(x) for x in cur)}<br><br> Diretor: {chama_diretor[file]}<br><br> Vice-Diretor: {chama_vice[file]}<br><br> Assessor(es): {chama_assessor[file]}<br><br> {dado}: {chama_projetos(file,dado)}<br><br> Quantidade de professores Envolvidos: {professores_envolvidos[file + dict_ajeita_ano[dado]]}<br><br> """ #picture1 = base64.b64encode(open('Apoio/logos/' + logo ,'rb').read()).decode() arquivo_json = limpa_nome_arquivo_json(arquivo_json) #iframe1 = IFrame(html1(picture1), width=200+20, height=200+20) icon1 = folium.features.CustomIcon('Apoio/logos/' + logo, icon_size=(20, 20)) ifr = IFrame(html=html1, width=500, height=300) popup1 = folium.Popup(ifr, max_width=2650) #popup1 = folium.Popup(dict_centros[arquivo_json],max_width=600) folium.Marker(location=dict_coordenadas[files], popup=popup1, tooltip='Clique para um maior conhecimento sobre centro', icon=icon1).add_to(mapa_)
def create_popup(index, district): """Creates an interactive timeseries popup for each district. """ district = str(district) i = index * 97 j = i + 97 pop = plot[i:j] fig = go.Figure([go.Scatter(x=pop[date_time_col_name], y=pop[value_col_name])]) fig.update_layout( title=pollutants[pollutant_ID]["notation"], xaxis_title="Time Stamp", yaxis_title="Pollutant Concentration (µg/m³)", ) fig.update_xaxes(showticklabels=False) script = plotly.offline.plot(fig, include_plotlyjs=False, output_type="div") html_start = ( """ <html> <head> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> <body> <h1>"%s"</h1>""" % district ) html_end = """ </body> </html>""" html_final = html_start + script + html_end resolution, width, height = 75, 7, 5 iframe = IFrame( html_final, width=(width * resolution) + 75, height=(height * resolution) + 50, ) return iframe
def maps(self): m = folium.Map(location=[37.550475, 126.989745], zoom_start=3) tooltip = "Click to see picture" html = '<img src="data:image/png;base64,{}">'.format i = 0 for ii, kk in self.gps: picture = base64.b64encode(open(self.path[i], 'rb').read()).decode() iframe = IFrame(html(picture), width=1300 + 20, height=420 + 20) popup = folium.Popup(iframe, max_width=650) icon = folium.Icon(color="blue") folium.Marker(location=[round(float(ii), 6), round(float(kk), 6)], popup=popup, tooltip=tooltip, icon=icon).add_to(m) i += 1 m.save("result.html")
def gera_icones_da_ufpb(logo, dict_logo, dict_coordenadas, html1, tooltip, mapa_): #AQUIII #picture1 = base64.b64encode(open('C:\\Users\\gabri\\OneDrive\\Área de Trabalho\\Pasta de backup\\ODE\\logos\\' + logo ,'rb').read()).decode() picture1 = base64.b64encode(open('Apoio/logos/' + logo, 'rb').read()).decode() iframe1 = IFrame(html1(picture1), width=300, height=300) #icon1 = folium.features.CustomIcon('C:\\Users\\gabri\\OneDrive\\Área de Trabalho\\Pasta de backup\\ODE\\logos\\' + logo, icon_size=(20,20)) icon1 = folium.features.CustomIcon('Apoio/logos/' + logo, icon_size=(20, 20)) files = limpa_nome_arquivo(logo) popup1 = folium.Popup(iframe1, max_width=650) folium.Marker(location=dict_coordenadas[files], popup=popup1, tooltip=tooltip, icon=icon1).add_to(mapa_)
def plot_obj_images_on_map(obj_gps_pos, track_gps, path_to_images): app = QtWidgets.QApplication(sys.argv) token = "pk.eyJ1IjoiaGFja3p1cmljaHVzZXIiLCJhIjoiY2tmOWl4NjU0MG1rcDJ5cWdxbHphNzQ5ayJ9.IEOl1OkLzh_vgznx38Anog" # your mapbox token tileurl = 'https://api.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}@2x.png?access_token=' + str( token) m = folium.Map(location=[ obj_gps_pos['GPSLatitude'].values[0], obj_gps_pos['GPSLongitude'].values[0] ], zoom_start=13, tiles=tileurl, attr='Mapbox') for index, row in obj_gps_pos.iterrows(): img_path = "file://" + path_to_images.replace( "\\", "/") + "/" + row["ImgName"] # html = '<div><img src="{}" width="512" height="384"></div>'.format(img_path) # frame = IFrame(html=html, width=512, height=384) # popup = folium.Popup(frame, max_width=1024) iframe = IFrame('<a href="{}">{}</a>'.format(img_path, row["Element Type"]), width=512, height=384) popup = folium.Popup(iframe, max_width=1000) folium.Marker([row['GPSLatitude'], row['GPSLongitude']], popup=popup).add_to(m) points = [] for index, row in track_gps.iterrows(): points.append((row['GPSLatitude'], row['GPSLongitude'])) folium.PolyLine(points, color="red", weight=2.5, opacity=1).add_to(m) data = io.BytesIO() m.save(data, close_file=False) w = QtWebEngineWidgets.QWebEngineView() w.setHtml(data.getvalue().decode()) w.resize(640, 480) w.show() sys.exit(app.exec_())
def folium(dest="docs/folium.html"): """ genreate folium.html """ my_map = Map( location=[43.0645597, 141.3481196], zoom_start=10, width="100%", height="90%", tiles="openstreetmap", ) marker_cluster = MarkerCluster() for _, row in df.iterrows(): lat = row["緯度"] lng = row["経度"] name = row["施設名"] address = row["検索用住所"] data_type = row["データ区分"] popup_html = f""" <h1>{name}</h1> <h2>{address}</h2> <table> <tbody> <tr> <th>緯度</th> <td>{lat}</td> </tr> <tr> <th>経度</th> <td>{lng}</td> </tr> <tr> <th>データ区分</th> <td>{data_type}</td> </tr> </tbody> </table> """ popup = Popup(IFrame(popup_html), min_width=400, max_width=400) Marker(location=[lat, lng], popup=popup, icon=Icon(color="red")).add_to(marker_cluster) marker_cluster.add_to(my_map) my_map.save(dest)
def add_popup(image_path, row): image = row['image'] boxedImage = 'boxedImage' if boxedImage in row and row['boxedImage'] is not 'None': image = RESULT_SUBDIR + os.path.sep + row['boxedImage'] encoded = base64.b64encode(open(image_path + image, 'rb').read()) # Produce content for popup with embedded image text = '<p>Traffic lights: ' + str(row['trafficLightCount']) + '</p><p>Max confidence: ' + str(row['trafficLightConfidenceMax']) +\ '</p><p>Direction: ' + str(row['direction']) + '</p><p>' + row['image'] + '</p>' header = '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">' image = '<img src="data:image/JPEG;base64,{}" class="rounded float-left img-thumbnail">' content = header + text + image html = content.format iframe = IFrame(html(encoded.decode("UTF-8")), width=960, height=540) popup = folium.Popup(iframe, max_width=1920) return popup
def add_img_markers(m, image_list=None): images = [ 'Darren', 'Dovestones', 'Ewan', 'Harry', 'John', 'Jon', 'Laura', 'Simon', 'Stephen' ] latlon = [(51.5525, -0.8051), (53.5312, -1.9740), (53.5056, -2.2919), (54.4569, -2.9498), (57.2236, -2.3219), (53.4879, -2.2744), (53.2756, -2.7396), (54.0615, -2.8404), (53.4262, -2.3313)] # Add markers for name, coord in zip(images, latlon): tmp_b64 = base64.b64encode(open(name + '.png', 'rb').read()) html_img = '<img src="data:image/png;base64,{}" style="height:180px;">'.format iframe = IFrame(html_img(tmp_b64.decode('ascii')), width=200, height=200) popup = folium.Popup(iframe) folium.Marker([coord[0], coord[1]], popup=popup, tooltip='Click me!').add_to(m) return m
def makemap(): from folium import IFrame # click = "<br><img src='data:image/png;base64,{}'>".format # information = "地址:"+row["地址"]+"<br>"+"房型:"+row["房型"]+"<br>"+"樓層:"+str(row["樓層"])+"<br>"+"坪數:"+str(row["坪數"])+"<br>"+"總價:"+str(row["總價"])+"萬" iframe = IFrame(html=html, width=500, height=395) # pp= folium.Html(click, script=True) # popup = folium.Popup(pp, max_width=2650) popup = folium.Popup(iframe, max_width=900, parse_html = True) folium.Marker( #標記作標位置 location=[row["緯度"], row["經度"]], #在標記中添加資訊:坪數、金額、房型... #target='_blank'新開起一個分頁 popup = popup, tooltip = str(row["單價"])+"萬", #設定標記樣式 icon=folium.map.Icon(color='orange',icon='fa-home', prefix='fa') ).add_to(marker_cluster)
def app(df_listings, df_attractions): html_temp = """ <div><font color=\"#C8C8C8\" size=\"18\"><strong>Is there any connection between NY City's attraction and the Airbnb prices?</font></div><br> <div><font color=\"#C8C8C8\" size=\"6\">How many Airbnb listings are located in NY?</font></div>""" st.markdown(html_temp, unsafe_allow_html=True) st.markdown("This website will provide you an easy and fun set of visualizations and tools to search on the different available Airbnb accommodations in New York City. " "We know that in a city as big and expensive as New York, finding a suitable apartment can be a daunting task. " "In the left menu you can find different interactive tools that illustrate geographically the variation of the different listings characteristics \(such as price, ratings, etc.\), " "as well as some other helpful apps.") df_heatmap = df_listings.copy() df_heatmap['count'] = 1 html_temp = """ <div><font color=\"#C8C8C8\" size=\"6\">Heat Map of NY's Airbnb listings</font></div>""" st.markdown(html_temp, unsafe_allow_html=True) map_hooray = folium.Map([40.730610, -73.935242], zoom_start=11, tiles="OpenStreetMap") heatmap = HeatMap(data=df_heatmap[['latitude', 'longitude', 'count']].groupby( ['latitude', 'longitude']).sum().reset_index().values.tolist(), radius=8, max_zoom=13) heatmap.add_to(map_hooray) popup = [] for i in range(len(png)): encoded = base64.b64encode(open(png[i], 'rb').read()).decode() building_name = df_attractions.Attraction[i] html = building_name html += '<img src="data:image/png[i];base64,{}" width="100" height="100">'.format(encoded) iframe = IFrame(html, width=130, height=150) popup.append(folium.Popup(iframe, max_width=130)) for i in range(len(png)): folium.Marker([df_attractions.latitude[i], df_attractions.longitude[i]], popup=popup[i], icon=folium.Icon(color='blue', icon_color='white', icon='globe')).add_to(map_hooray) folium_static(map_hooray, width=1000, height=600)
def map_objects(): #build map with folium library map = folium.Map(tiles='Stamen Toner', location=[df['Lat'][0], df['Lon'][0]], zoom_start=10,) #build the map based on the address we collected in our dataframe for lat,lon,sv_photo,address in zip(df['Lat'],df['Lon'],df['street_view'],df['address_price']): encoded = base64.b64encode(open(sv_photo, 'rb').read()).decode() #building html for the map html = '<img src="data:image/jpeg;base64,{}" >'.format resolution, width, height = 75, 50, 25 iframe = IFrame(html(encoded), width=300, height=600) popup = folium.Popup(iframe, max_width=1000) #defining marker parameters icon = folium.Icon(color="red", icon="home") marker = folium.Marker(location=[lat, lon], popup=popup, icon=icon,tooltip=address) #add marker to mapp marker.add_to(map) #save map data map.save('multi_map_200.html')