def position_visual(comp_info, envi_info): ''' 观测站点分布简单可视化. ''' map_station = folium.Map(CN_center, zoom_start=5) # Add comp stations for _, row in comp_info.iterrows(): lat, lon = row['latitude'], row['longitude'] text = folium.Html( u'<b>编号:{}</b></br> <b>名称:{}</b></br> <b>城市:{}</b></br></br>'.format( row['stationcode'], row['name'], row['cityname']), script=True) popup = folium.Popup(text, max_width=2650) icon = folium.Icon(color='red', icon='info-sign') folium.Marker([lat, lon], popup=popup, icon=icon).add_to(map_station) # Add envi stations for _, row in envi_info.iterrows(): lat, lon = row['纬度'], row['经度'] text = folium.Html( u'<b>编号:{}</b></br> <b>名称:{}</b></br> <b>城市:{}</b></br></br>'.format( row['站号'], row['站点'], row['城市']), script=True) popup = folium.Popup(text, max_width=2650) icon = folium.Icon(color='green', icon='info-sign') folium.Marker([lat, lon], popup=popup, icon=icon).add_to(map_station) # save html map_station.save(u"{}.html".format('demo'))
def mapper(loc = ""): chur = pd.read_json("./static/data/churches.json") care = pd.read_json("./static/data/rec2.json") if loc == "": locref = (50.804055, -1.980081) if loc == "Loc1": locref = (50.804055, -1.980081) if loc == "Loc2": locref = (50.7192, -1.8808) if loc == "Loc3": locref = (50.7112, -2.4412) start_coords = (float(locref[0]), float(locref[1])) folium_map = folium.Map(location=start_coords, zoom_start=14) for row in chur.itertuples(): uri = "https://www.snu.org.uk"+row.lnk[0] print(f"URI = {uri}") test = folium.Html(f'<b>{row.church}</b></br> <a href="{uri} "target="_blank"> SNU Link </a>', script=True) popup = folium.Popup(test) folium_map.add_child(folium.Marker(location=[row.lat, row.lng], popup=popup, icon=folium.Icon(color='green', icon='leaf'))) for row in care.itertuples(): test1 = folium.Html(f'<b>{row.locationName}</b></br><p>PostCode: {row.postalCode} Constit: {row.parliamentary_constituency}</p>', script=True) popup = folium.Popup(test1) folium_map.add_child(folium.Marker(location=[row.lat, row.lng], popup=popup, icon=folium.Icon(color='green', icon='hand-holding-heart'))) return folium_map._repr_html_()
def generate_html(location, geocode, latitude: float = 49.817545, longitude: float = 24.023932, html_path="map.html"): """ This function generatess and html file containing a map with films. """ page_map = folium.Map(titles="OpenStreetMap", location=[latitude, longitude], zoom_start=10) location_title_dict = prepare_location_title_data() current_user_location = location.address logging.debug(f"{current_user_location = }") logging.debug("Finding current closest films...") best_matches = find_closest_locations(current_user_location, location_title_dict) logging.debug("Finding current closest films locations...") closest_films_featuregroup = folium.FeatureGroup(name="Closest films") films_num_left = 20 for match in best_matches: match_location = geocode(match) if match_location is None: continue match_lat, match_lon = match_location.latitude, match_location.longitude closest_films_featuregroup.add_child( folium.Marker(location=[match_lat, match_lon], popup=folium.Popup(folium.Html(", ".join( location_title_dict[match])), min_width=500, max_width=500), icon=folium.Icon())) films_num_left -= 1 if films_num_left <= 0: break page_map.add_child(closest_films_featuregroup) user_location_featuregroup = folium.FeatureGroup(name="Your location") user_location_featuregroup.add_child( folium.Marker(location=[latitude, longitude], popup=folium.Popup(folium.Html("Your Location"), min_width=100, max_width=100), icon=folium.Icon(color="red"))) page_map.add_child(user_location_featuregroup) page_map.save(html_path)
def avmap(request, listing_id): listing = get_object_or_404(Listing, pk=listing_id) location_lat = float(listing.location_lat) location_lon = float(listing.location_lon) location = listing.location address = listing.address data = pd.read_csv('kc_house_data.csv') data_map = data.groupby('zipcode')[['price']].mean().reset_index() data_map['zipcode'] = data_map['zipcode'].astype(str) k_c = 'new.json' map = folium.Map( location=[47.5577, -122.1277], zoom_start=10.5, detect_retina=True, control_scale=False, ) choropleth = folium.Choropleth(geo_data=k_c, name='choropleth', data=data_map, columns=['zipcode', 'price'], key_on='feature.properties.ZIPCODE', fill_color='Blues', line_color='red', fill_opacity=0.9, line_opacity=0.5, highlight=True, legend_name='Average Price ($)').add_to(map) folium.LayerControl().add_to(map) choropleth.geojson.add_child( folium.features.GeoJsonTooltip(['ZIPCODE'], labels=False)).add_to(map) city = folium.Html('<b>Seattle</b>', script=True) pin = folium.Html('<h1>Property Location -</h1>' + location + address, script=True) popup_1 = folium.Popup(pin, max_width=2650) popup_2 = folium.Popup(city, max_width=2650) folium.Marker(location=[location_lat, location_lon], popup=popup_1, icon=folium.Icon(color="red", icon="home", prefix='fa')).add_to(map) folium.CircleMarker(location=[47.6062, -122.3321], radius=10, popup=popup_2, color='#FF0000', fill=True, fill_color='#FF0000').add_to(map) map = map._repr_html_() context = {'my_map': map, 'location': location} return render(request, 'listings/maps.html', context)
def Mapping(): global fig with app.app_context(): count = db.session.query(Data.name_).count() fig = folium.Figure(width=1000, height=200) map = folium.Map(location=[33.811257, 35.605018], zoom_start=14, tiles='OpenStreetMap') org = folium.FeatureGroup(name="Green") carbsour = folium.FeatureGroup(name="Brown") for i in range(count): name = db.session.query(Data.name_)[i][0] coord = db.session.query(Data.coord_)[i][0].split(",") try: lat = float(coord[0]) lon = float(coord[1]) res = db.session.query(Data.source_)[i][0] if res == "Brown": html = '<p>Resource : Brown</p>' test = folium.Html("Name: " + name + html, script=True) popup = folium.Popup(test) carbsour.add_child( folium.Marker(location=[lat, lon], popup=popup, icon=folium.Icon(color='darkred'))) elif res == "Green": html = '<p>Resource : Green</p>' test = folium.Html("Name: " + name + html, script=True) popup = folium.Popup(test) popup = folium.Popup(test, max_width=400) org.add_child( folium.Marker(location=[lat, lon], popup=popup, icon=folium.Icon(color='green'))) except: message_coord = "Warning: Coordinates are not numerical values" map.add_child(org) map.add_child(carbsour) map.add_child(folium.LayerControl()) fig.add_child(map)
def add_marker_per_minute(folium_map, trip_id, stop_id, date_time, next_number_of_minutes): for i in range(next_number_of_minutes + 1): current_datetime = date_time + timedelta(minutes=i) recent_pings = get_most_recent_pings(trip_id, current_datetime) if len(recent_pings) == 0: continue point = (recent_pings.iloc[0].lat, recent_pings.iloc[0].lng) actual_arrival_time = get_actual_arrival_timing( trip_id, stop_id, current_datetime) predicted_arrival_time = get_predicted_arrival_timing( trip_id, stop_id, current_datetime) add_marker( folium_map, point, folium_icon=folium.Icon(color='green'), folium_popup=folium.Popup( folium.Html( "<b>Stop id: {}</b><br>Current time: {}<br>Predicted: {}<br>Actual: {}" .format( stop_id, current_datetime.strftime(TIME_FORMAT), predicted_arrival_time.strftime(TIME_FORMAT) if predicted_arrival_time else '', actual_arrival_time.strftime(TIME_FORMAT) if actual_arrival_time else ''), script=True)))
def index(request): kitchens = Kitchen_info.objects.all() # Get first data m = folium.Map( location=[37.558773, 126.970260], zoom_start=11, ) marker_cluster = MarkerCluster().add_to(m) for i in kitchens: html = folium.Html('<div style="font-family: Nanum Gothic"><h1>' + i.kitchen_name + '</h1>', script=True) iframe = folium.IFrame(html=html, width=200, height=100) popup = folium.Popup(iframe, parse_html=True) tooltip = i.kitchen_name folium.Marker( location=[i.lat, i.lng], popup=popup, icon=folium.Icon(color="red", icon="ok"), tooltip=tooltip, ).add_to(marker_cluster) m.save('reservation/map.html') return render(request, 'reservation/index.html', { 'map': m._repr_html_, 'kitchens': kitchens })
def bldg_detail(request, id): with connection.cursor() as cursor: sql = f"""SELECT * FROM skyscrapers, bldg_images WHERE skyscrapers.id={id} AND skyscrapers.id = bldg_images.bldg_id""" cursor.execute(sql) result = cursor.fetchall() print(result) lat_long = [result[0]['x_coord'], result[0]['y_coord']] m = folium.Map(lat_long, zoom_start=14) # m = folium.Map(lat_long, zoom_start=12, tiles='Stamen Terrain') # folium 한글깨짐 해결 방법 : 아래 명령어 실행 후 서버 재실행 # sudo pip3 install git+https://github.com/python-visualization/branca.git@master text = "<b>" + result[0]['building_name'] + "</b></br><i>" + result[0][ 'city_name'] + "</i></br>" popText = folium.Html(text + str(lat_long), script=True) popup = folium.Popup(popText, max_width=2650) folium.Marker(location=lat_long, popup=popup).add_to(m) m = m._repr_html_() #updated context = {'data': result, 'bldg_map': m} return render(request, 'buildings/bldg_detail.html', context)
def make_dup_location_popup_html(row: pd.Series): # was: row.to_frame().to_html() # ['LocationA', 'NameA', 'coordinatesA', 'LocationB', 'NameB', 'coordinatesB', 'dist_m'] html = """ <b>Location A :</b> {location_a}<br> <b>Coordinates :</b> {coordinates_a}<br> <b>LocationA ID :</b> {location_a_id}<br> <b></b> <br> <b>Location B :</b> {location_b}<br> <b>Coordinates :</b> {coordinates_b}<br> <b>LocationB ID :</b> {location_b_id}<br> <b></b> <br> <b>Distance (m) :</b> {distance_m}<br> <b>Distance (ft):</b> {distance_ft}<br> """ distance_ft = f'{float(row.dist_m) / foot:.02f}' popup_contents = folium.Html(html.format(location_a=row.NameA, coordinates_a=row.coordinatesA, location_a_id=row.LocationA, location_b=row.NameB, coordinates_b=row.coordinatesB, location_b_id=row.LocationB, distance_m=row.dist_m, distance_ft=distance_ft), script=True) return popup_contents
def make_observation_popup_html(row: pd.Series): # was: row.to_frame().to_html() checklist_base_url = 'https://ebird.org/checklist' checklist_url = f'{checklist_base_url}/{row.subId}' html = """ <b>Observer :</b> {observer_name}<br> <b>When :</b> {observation_dt}<br> <b>Species :</b> {num_species}<br> <b>Location :</b> {location_name}<br> <b>Coordinates:</b> {coordinates}<br> <b>LocationID :</b> {locationID}<br> <b>Checklist :</b> <a href="{checklist_url}">{checklist_subid}</a><br> """ observation_dt = f'{row.obsDt} {row.obsTime}' coordinates = f'({row.latitude}, {row.longitude})' popup_contents = folium.Html(html.format(observer_name=row.Name, observation_dt=observation_dt, num_species=row.numSpecies, location_name=row.loc_name, coordinates=coordinates, locationID=row.locId, checklist_url=checklist_url, checklist_subid=row.subId), script=True) return popup_contents
def folium_map0(request): # map m = folium.Map([51.5, -0.25], zoom_start=10) test = folium.Html('<b>Hello world</b>', script=True) popup = folium.Popup(test, max_width=2650) folium.RegularPolygonMarker(location=[51.5, -0.25], popup=popup).add_to(m) m = m._repr_html_() # access to the data from DB (light and imgs_light) lights = Light.objects.all() img_lights = ImageLight.objects.all() # light. define the current date (day and month) now = datetime.datetime.now() now_day, now_month = now.day, now.month now_hour, now_min = now.hour, now.minute context = { 'my_map': m, 'lights': lights, 'now_day': now_day, 'now_month': now_month, 'img_lights': img_lights, 'now_hour': now_hour, 'now_min': now_min } return render(request, 'folium_map0/folium_map0.html', context)
def make_popups(map, lat, lon, title, date, description, icon, color): """ Adds a popup with the specified information & styling attributes to the data layer at the geographical location dictated by the latitude and longitude coordinates. Parameters ---------- map : Map (folium) map to be displayed lat : float latitude coordinate (decimal notation) lon : float longitude coordinate (decimal notation) title : string name of the datapoint (to be displayed by the tooltip) date : string date associated with the datapoint description : string description of the datapoint icon : string icon to be displayed in the popup pin color : string color of the popup pin """ folium.Marker( location = [lat, lon], icon = folium.Icon(icon=icon, color=color), tooltip = title, popup = folium.Popup( folium.Html('<b>%s</b> <br> <i>%s</i> <br> %s' %(title, date, description), script=True), min_width=100, max_width=450 ) ).add_to(map)
def listajax_detail(request): if request.method == 'POST': id = request.POST.get('id', 1) with connection.cursor() as cursor: sql = f"""SELECT * FROM mountains, mt_images WHERE mountains.id={id} AND mountains.id = mt_images.mt_id""" cursor.execute(sql) results = cursor.fetchall() print(results) lat_long = [results[0]['y_coord'], results[0]['x_coord']] m = folium.Map(lat_long, zoom_start=14) # m = folium.Map(lat_long, zoom_start=12, tiles='Stamen Terrain') # folium 한글깨짐 해결 방법 : 아래 명령어 실행 후 서버 재실행 # sudo pip3 install git+https://github.com/python-visualization/branca.git@master text = "<b>" + results[0]['name'] + "</b></br><i>" + results[0][ 'title'] + "</i></br>" popText = folium.Html(text + str(lat_long), script=True) popup = folium.Popup(popText, max_width=2650) folium.Marker(location=lat_long, popup=popup).add_to(m) m = m._repr_html_() #updated # context = {'data':result, 'mountain_map': m} # results = list(paginator.page(page_n)) # return render(request, 'mountains/mt_detail.html', context) return JsonResponse({"results": list(results), 'mountain_map': m})
def get_searchmap(self, data): if data['flag'] == True: self.scrapping_jobkorea_search(data) if self.db.keyword.count() != 0: self.db.keyword.drop() self.db.keyword.insert_one(data) infolists = list(self.db.Joblist2.find()) lat_long = [36, 127.4] m = folium.Map(lat_long, zoom_start=7, tiles='openstreetmap') for infolist in infolists: coord = [float(infolist['y']), float(infolist['x'])] info_mark = f'''<a href="{infolist["link"]}" target="_top"><b>{infolist["title"]}</b></a><br> 회사이름: {infolist['company']}<br> ''' popText = folium.Html(info_mark, script=True) popup = folium.Popup(popText, max_width=2650) icon = folium.Icon(icon='building', prefix='fa') folium.Marker(location=coord, popup=popup, icon=icon).add_to(m) folium.TileLayer('openstreetmap').add_to(m) folium.TileLayer('Stamenterrain').add_to(m) folium.TileLayer('stamentoner').add_to(m) folium.TileLayer('Stamenwatercolor').add_to(m) folium.TileLayer('cartodbpositron').add_to(m) folium.TileLayer('cartodbdark_matter').add_to(m) folium.LayerControl().add_to(m) m = m._repr_html_() return m
def map(request, listing_id): listing = get_object_or_404(Listing, pk=listing_id) location_lat = float(listing.location_lat) location_lon = float(listing.location_lon) location = listing.location address = listing.address data = pd.read_csv('kc_house_data.csv') data["weight"] = .8 lat_lon = data[["lat", "long"]].values[:15000] map = folium.Map( location=[47.4081, -121.9949], zoom_start=8.5, ) HeatMap(lat_lon, radius=10).add_to(map) test = folium.Html('<h1>Property Location</h1>' + location + address, script=True) popup = folium.Popup(test, max_width=2650) folium.Marker(location=[location_lat, location_lon], popup=popup, icon=folium.Icon(color="red", icon="home", prefix='fa')).add_to(map) marker_cluster = MarkerCluster().add_to(map) for point in range(0, len(lat_lon)): folium.Marker(lat_lon[point], popup=data['price'][point]).add_to(marker_cluster) map = map._repr_html_() context = {'my_map': map, 'location': location} return render(request, 'listings/maps.html', context)
def get_one_map(self, no): infolists = self.get_mountinfo() infolist = infolists[no - 1] coord = [infolist['coord']['lat'], infolist['coord']['lon']] m = folium.Map(coord, zoom_start=10, tiles='stamenterrain') info_mark = f'''<b>산이름: {infolist["name"]}</b><br> 좌표: {infolist['coord']['lat']:04f}, {infolist['coord']['lon']:04f}<br> 날씨: {infolist['weather'][0]['main']}<br> 기온: {infolist['main']['temp']}<br> <img src="{infolist['img']}" alt="{infolist['name']}" height="64"> ''' popText = folium.Html(info_mark, script=True) popup = folium.Popup(popText, max_width=2650) icon_img = folium.features.CustomIcon('./data/greenmounticon.png', icon_size=(30, 30)) folium.Marker(location=coord, popup=popup, icon=icon_img).add_to(m) folium.TileLayer('openstreetmap').add_to(m) folium.TileLayer('Stamenterrain').add_to(m) folium.TileLayer('stamentoner').add_to(m) folium.TileLayer('Stamenwatercolor').add_to(m) folium.TileLayer('cartodbpositron').add_to(m) folium.TileLayer('cartodbdark_matter').add_to(m) folium.LayerControl().add_to(m) m = m._repr_html_() return m
def update_map(n, data): data = pd.DataFrame(data) try: lat_max = data['lat'].max() lat_min = data['lat'].min() lon_max = data['lon'].max() lon_min = data['lon'].min() if len(data): latc = np.mean([lat_min, lat_max]) lonc = np.mean([lon_min, lon_max]) coordinates = (latc, lonc) else: coordinates = (0, 0) #width='100%', height='100%', folium_map = folium.Map( location=coordinates, tiles=tiles, zoom_start=4, prefer_canvas=True) #, tiles='CartoDB dark_matter' for index, row in data.dropna().iterrows(): popup_text = "{}<br> Location: {:}".format(row['aqi'], row["location"]) test = folium.Html(popup_text, script=True) popup = folium.Popup(test, max_width=300, min_width=100) folium.CircleMarker(location=[row["lat"], row["lon"]], radius=8, color=row['marker_color'], popup=popup, fill=True).add_to(folium_map) return folium_map._repr_html_() except: raise PreventUpdate
def getMapStationInformationbyFullDate(date): dateparser = re.compile(r"(?P<year>\d+)-(?P<month>\d+)-(?P<day>\d+) (?P<hour>\d+):(?P<minute>\d+)") match_date = dateparser.match(date) if not match_date: print("Rentrez une date valide YYYY-MM-DD HH:MM") return date_dict = match_date.groupdict() rows = session.execute(f"""SELECT * FROM {KEYSPACE}.{TABLE} where year={int(date_dict['year'])} AND month={int(date_dict['month'])} AND day={int(date_dict['day'])} AND hour={int(date_dict['hour'])} AND minute={int(date_dict['minute'])}""") m = folium.Map(location=[47.029895, 2.440967], zoom_start=6) if rows: for row in rows: html=f""" <b>{row.station} informations le {date}</b></br></br> <ul> <li>Temperature réelle: {round(row.tmpf,1)} F</li> <li>Temperature ressentie: {round(row.feel,1)} F</li> <li>Pression atmosphérique : {round(row.alti,1)} inches</li> <li>Force du vent : {round(row.sknt,1)} noeuds</li> <li>Direction du vent : {round(row.drct,1)} degrée</li> <li>Humidité de l'air : {round(row.relh,1)} %</li> </ul> """ popupHtml = folium.Html(html, script=True) popup = folium.Popup(popupHtml,max_width=300,min_width=300) tooltip = row.station folium.Marker([row.lat, row.lon], popup=popup, tooltip=tooltip).add_to(m) m.save(f"""./images/map-info-{date}.html""")
def addimagestomap(df, pincolor): # append thumbnail directory to image names df[df.columns[0]] = path_for_thumnails + df[df.columns[0]] # make list out of photos imgpaths = df[df.columns[0]].to_list() # batch coordinates for each image imgcoords = [[df[df.columns[1]][i], df[df.columns[2]][i]] for i in range(len(df))] testNOloop = [ folium.Html('<img src=' + imgpaths[i] + '>', script=True) for i in range(len(imgpaths)) ] ##### # add marker for each popup ##### [ folium.Marker( location=imgcoords[j], popup=folium.Popup(testNOloop[j], max_width=imgsize), #icon=folium.Icon(color='green') icon=folium.Icon(color=pincolor, icon='picture')).add_to(m) for j in range(len(imgcoords)) ] counter = len(imgcoords) return print(counter, ' ' + pincolor + ' pins added')
def getMapStationInformationbyFullDate(df, k): m = folium.Map(location=[47.029895, 2.440967], zoom_start=6) for row in df.itertuples(index=True, name='Pandas'): # getattr(row, "c1"), getattr(row, "c2") html = f""" <b> informations de periode</b></br></br> <ul> <li>Temperature réelle: {getattr(row, "tmpf")} F</li> <li>Force du vent : {getattr(row, "sknt")} noeuds</li> <li>Direction du vent : {getattr(row, "drct")} degrée</li> <li>Humidité de l'air : {getattr(row, "relh")} %</li> </ul> """ popupHtml = folium.Html(html, script=True) popup = folium.Popup(popupHtml, max_width=300, min_width=300) marker_colors = ['red', 'blue', 'green', 'purple', 'orange', 'darkred', 'lightred', 'beige', 'darkblue', 'darkgreen', 'cadetblue', 'darkpurple', 'white', 'pink', 'lightblue', 'lightgreen', 'gray', 'black', 'lightgray'] tooltip = getattr(row, "station") folium.Marker([getattr(row, "lat"), getattr(row, "lon")], popup=popup, tooltip=tooltip, icon=folium.Icon(color=marker_colors[getattr(row, "label_kmeans")], icon='info-sign')).add_to(m) m.save(f"""./images/map_q3.html""")
def krmt(request): center = [36.6691961, 127.9295186] m = folium.Map(center, zoom_start=7) marker_cluster = MarkerCluster().add_to(m) with MongoClient('mongodb://192.168.219.104:27017') as client: db = client.mydb mt_data_list = list(db.mountain.find({})) wt_data_list = list(db.weather.find({})) for mt_data, wt_data in zip(mt_data_list, wt_data_list): mt_address_temp = mt_data['mt_address'] mt_address = mt_address_temp.split(" ")[0] if mt_address in mt_data['mt_address']: lat_lon = [mt_data['mt_lat'], mt_data['mt_lon']] pop_text = folium.Html( f"<img src={mt_data['mt_img_path_preview']} width=300px; height=300px;><br>" + f"<a href='detail/{mt_data['mt_num']}/' target='_blank'><b>Mountain : {mt_data['mt_name']}</a><br>" + f"<b>Height : {mt_data['mt_height']}m<br>" + f"<b>Current weather : {wt_data['mt_weather_main']} <br>Current temperature : {wt_data['temp']}°C", script=True ) pop_up = folium.Popup(pop_text) folium.Marker(lat_lon, popup=pop_up, tooltip=mt_data['mt_name']).add_to(marker_cluster) paginator = Paginator(mt_data_list, 10) page =request.GET.get('page', 1) page_data = paginator.get_page(page) m = m._repr_html_() return render(request, 'mt/krmt.html', context={'page_data':page_data, 'map':m})
def create_html_link(address: str): html = folium.Html("""<a href =""" + STREET_VIEW_URL + address.replace(" ", "+") + """> Street View</a><br><p>""" + address + """</p>""", script=True) link = folium.Popup(html, max_width=2650) return link
def get_associates_cluster_layer(df, layer_name='Associates Cluster', show=False): popups = [] table = df.loc[df.has_coords] for i in range(len(table)): nombre = table.iloc[i]['Número de personal'] numero = table.iloc[i]['Nº pers.'] CP = table.iloc[i]['CP'] text = f''' <ul> <li><b>CP:</b> {CP}</li> <li><b>Nombre de personal:</b> {nombre}</li> <li><b>Número de personal:</b> {numero}</li> </ul> ''' text = folium.Html(text, script=True) popups.append(folium.Popup(text, max_width=2650)) pt_lyr = folium.FeatureGroup(name=layer_name, show=show) pt_lyr.add_child( MarkerCluster(locations=table[['lat', 'lon']].astype(float).values, popups=popups)) return pt_lyr
def get_associates_zip_codes_layer(df, layer_name='Associates ZipCodes', show=False): pt_lyr = folium.FeatureGroup(name=layer_name, show=show) table = group_zip_codes(df) for i in range(len(table)): point = table.iloc[i][['lat', 'lon']].values CP = table.iloc[i]['CP'] num = table.iloc[i]['count'] text = '<p>CP: {}</p><p>Asociados: {}</p>'.format(CP, num) text = f''' <ul> <li><b>CP:</b> {CP}</li> <li><b>Número de Asociados:</b> {num}</li> </ul> ''' text = folium.Html(text, script=True) popup = folium.Popup(text, max_width=2650) pt_lyr.add_child( folium.CircleMarker( point, radius=4, popup=popup, fill=True, # Set fill to True fill_color='white', color='red', fill_opacity=1)) return pt_lyr
def create_edge_table(graph, i, j): text = f''' <p><b>Edge {i} - {j}</b></p> <table border="1" style="width:100%"> <tr> <th></th> <th> Distance </th> <th> Duration </th> <th> Sum </th> </tr> <tr> <th> Est. </th> <td>{format_distance(graph.edges_distances_est[i,j])}</td> <td>{format_duration(graph.edges_durations_est[i,j])}</td> <td> - </td> </tr> <tr> <th> Real </th> <td>{format_distance(graph.edges_distances[i,j])}</td> <td>{format_duration(graph.edges_durations[i,j])}</td> <td> - </td> </tr> </table> ''' text = folium.Html(text, script=True) return folium.Popup(text, max_width=2650)
def makeMap(): # Build empty map at specified location and zoom # EDIT this to specify location based on user (search?) # Get user location ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr) userLocation = subprocess.check_output( 'curl http://api.ipstack.com/' + ip + '?access_key=27104e68a758ad15540f3065ff3254dc', shell=True) userLocation = json.loads(userLocation.decode("ascii")) if userLocation["latitude"] == None or userLocation["longitude"] == None: mapLatitude = 0 mapLongitude = 0 mapZoom = 1 else: mapLatitude = userLocation["latitude"] mapLongitude = userLocation["longitude"] mapZoom = 6 map = folium.Map(location=[mapLatitude, mapLongitude], zoom_start=mapZoom, titles="test title", width='100%', height='100%') locations = db.execute('SELECT * FROM locations').fetchall() for entry in locations: id = entry[0] datetime = entry[1] latitude = entry[2] longitude = entry[3] title = entry[4] description = entry[5] locType = entry[6] if locType == "Work": color = "red" elif locType == "Sleep": color = "purple" elif locType == "Shower": color = "lightblue" else: color = "green" icon = "bed" html = folium.Html("<b>" + title + "</b><br>" + description, script=True) # i'm assuming this bit runs fine iframe = branca.element.IFrame(html=html, width=320, height=120) popup = folium.Popup(iframe, parse_html=True) folium.Marker(location=[latitude, longitude], icon=folium.Icon(color=color, icon=icon), radius=6, popup=popup).add_to(map) map.save("maps/mapEmbed.html")
def add_park_locations_to_map(map, df): ''' Add park location markers to a map. This function adds all locations in the This function creates a Folium map object, centered on the lat/long center of the lower 48 states. Parameters ---------- map : Folium map object Folium map to add location markers to. df : Pandas DataFrame DataFrame of all park locations to add to the map. Returns ------- map : Folium map object Folium map with location markers added. ''' # Create a dataframe of park sets with assigned icons and colors. icon_df = pd.DataFrame( {'park_set' : ['National Park', 'National Monument', 'National Preserve or Reserve', 'National Lakeshore or Seashore', 'National River', 'National Trail', 'National Historic Site', 'National Memorial', 'National Recreation Area', 'National Parkway', 'National Heritage Area', 'Affiliated Area', 'Other'], 'color' : ['green', 'lightgreen', 'beige', 'lightblue', 'lightblue', 'beige', 'red', 'red', 'beige', 'beige', 'red', 'orange', 'orange'], 'icon' : ['tree', 'tree', 'pagelines', 'tint', 'tint', 'pagelines', 'university', 'university', 'pagelines', 'road', 'university', 'map-marker', 'map-marker'] }) for _, row in df[~df.lat.isnull()].iterrows(): # Create popup with link to park website. popup_string = ('<a href="' + 'https://www.nps.gov/' + row.park_code + '" target="_blank">' + row.park_name + '</a>').replace("'", r"\'") popup_html = folium.Html(popup_string, script=True) # Assign color and graphic to icon. icon_df_row = icon_df[icon_df.park_set == row.park_set] map_icon = folium.Icon(color=icon_df_row.values[0][1], prefix='fa', icon=icon_df_row.values[0][2]) marker = folium.Marker(location = [row.lat, row.long], icon = map_icon, popup = folium.Popup(popup_html) ).add_to(map) return map
def health(request): m = folium.Map([51.5, -0.25], zoom_start=10) test = folium.Html('<b>Hello world</b>', script=True) popup = folium.Popup(test, max_width=2650) folium.RegularPolygonMarker(location=[51.5, -0.25], popup=popup).add_to(m) m = m._repr_html_() context = {'map': m} return render(request, 'health/health.html', context)
def add_markers(folium_map, lat_lng_pairs, stop_ids): for i in range(len(lat_lng_pairs)): add_marker(folium_map, lat_lng_pairs[i], folium_popup=folium.Popup( folium.Html('<b>' + str(i + 1) + '</b>. ' + str(stop_ids.iloc[i]), script=True)))
def make_folium(wards_df, data_json, save_file="../results/kathmandu.html", center=[27.700769, 85.300140], zoom=11, tiles="http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"): m = folium.Map( location=center, zoom_start=zoom, tiles=tiles, attr='...', ) width = 310 popups, polygons = [], [] # print(data_json) for _, rows in wards_df.iterrows(): district = rows["DISTRICT"] palika = rows["GaPa_NaPa"] + " " + rows["Type_GN"] ward = rows["NEW_WARD_N"] polygon = polygon_to_list(rows["geometry"]) polygons.append(polygon) ddgnww = rows["DDGNWW"] required_row = data_json.loc[(data_json["DDGNWW"] == ddgnww)] return_q = required_row["Returnee.Quarantined"].values[0] return_nq = required_row["Returnee.Not_Quarantined"].values[0] return_t = return_q + return_nq pcr_p = required_row["PCR.Positive"].values[0] pcr_n = required_row["PCR.Negative"].values[0] pcr_t = pcr_p + pcr_n rdt_p = required_row["RDT.Positive"].values[0] rdt_n = required_row["RDT.Negative"].values[0] rdt_t = rdt_p + rdt_n iframe = folium.Popup( folium.Html(table_html(district, palika, ward, return_q, pcr_p, rdt_p, return_nq, pcr_n, rdt_n, return_t, pcr_t, rdt_t), script=True, width=width)) # iframe = IFrame(table_html.format(district, palika, ward, return_q, return_nq, return_t, pcr_p, pcr_n, pcr_t, rdt_p, rdt_n, rdt_t), width=width, height=height) popups.append(iframe) h = folium.FeatureGroup(name='Tests and Returnees') h.add_child(MarkerCluster(locations=polygons, popups=popups)) geojs = folium.features.GeoJson(wards_df, name="Boundary") m.add_child(geojs) m.add_child(h) m.save(save_file)