def add_marker(html, group, tooltip): if group == 'NAM': Marker(location=coords, popup=html, tooltip=tooltip, icon=Icon(color='green', icon='map-marker', prefix='fa')).add_to(nam_group) elif group == 'EMEA': Marker(location=coords, popup=html, tooltip=tooltip, icon=Icon(color='purple', icon='map-marker', prefix='fa')).add_to(emea_group) elif group == 'APA': Marker(location=coords, popup=html, tooltip=tooltip, icon=Icon(color='red', icon='map-marker', prefix='fa')).add_to(asia_group)
def map_it(df, lattitude, longitude): map_city = Map(location=[lattitude, longitude], zoom_start=15) for i, row in df.iterrows(): name = {"location": [row["lat"], row["long"]], "tooltip": row["name"]} if row["category"] == "Starbucks": icon = Icon(color="black", prefix="fa", icon="coffee", icon_color="white") elif row["category"] == "Preschool": icon = Icon(color="red", prefix="fa", icon="child", icon_color="white") elif row["category"] == "Vegan_Restaurant": icon = Icon(color="green", prefix="fa", icon="leaf", icon_color="white") else: icon = Icon(color="lightblue", prefix="fa", icon="futbol-o", icon_color="black") Marker(**name, icon=icon).add_to(map_city) return map_city
def bicycling(origin, destination, alternative="bicycling"): """ Recoge las cordenadas y dibuja el mapa con direcciones (en bici) """ coordenadas = waypoints(origin=origin, destination=destination, alternative="bicycling") stopsdest = db.bicimad.find({ "coordinates": { "$geoWithin": { "$centerSphere": [[coordenadas[2]["lng"], coordenadas[2]["lat"]], 0.00007885743614075527] } } }).limit(1) stopsorig = db.bicimad.find({ "coordinates": { "$geoWithin": { "$centerSphere": [[coordenadas[1]["lng"], coordenadas[1]["lat"]], 0.00007885743614075527] } } }).limit(1) wpsneardest = [] wpsnearorig = [] for i in stopsdest: wpsneardest.append(i) for i in stopsorig: wpsnearorig.append(i) wpsneardest = wpsneardest[0]["coordinates"] wpsnearorig = wpsnearorig[0]["coordinates"] mapa = Map(location=[coordenadas[2]["lat"], coordenadas[2]["lng"]], zoom_start=14) chincheta2 = Marker( location=[coordenadas[1]["lat"], coordenadas[1]["lng"]], tooltip="origen", popup="o") chinchetad = Marker( location=[coordenadas[2]["lat"], coordenadas[2]["lng"]], tooltip="destino", popup="d") bicimador = Marker(location=[wpsnearorig[1], wpsnearorig[0]], tooltip="orbici", popup="bo", icon=Icon(icon='heart', color='#f7b5f5')) bicimaddest = Marker(location=[wpsneardest[1], wpsneardest[0]], tooltip="destbici", popup="bd", icon=Icon(icon="heart", color="#f7b5f5")) chincheta2.add_to(mapa) chinchetad.add_to(mapa) bicimador.add_to(mapa) bicimaddest.add_to(mapa) PolyLine(coordenadas[3], color="red", weight=2.5, opacity=1).add_to(mapa) return mapa
def routeBuild(self): map = Map(self.coordList[0], zoom_start=9) popup_str = "Широта:{0:3f} Долгота:{1:3f}" lat1, lon1 = self.coordList[0] lat2, lon2 = self.coordList[len(self.coordList) - 1] PolyLine(self.coordList, color="red", weight=3, opacity=1).add_to(map) Marker([lat1, lon1], popup=popup_str.format(lat1, lon1), icon=Icon(color="blue")).add_to(map) Marker([lat2, lon2], popup=popup_str.format(lat2, lon2), icon=Icon(color="green")).add_to(map) map.save("map.html")
def create_popup_and_icon(query_list, host_url): # generate icon number_of_points = len(query_list) if number_of_points < 5: icon_color = "blue" elif number_of_points < 10: icon_color = "green" elif number_of_points < 20: icon_color = "yellow" elif number_of_points < 30: icon_color = "orange" else: icon_color = "red" # generate popup sources = [row[3] for row in query_list] alter, auto, geo = ( sources.count("altertravel"), sources.count("autotravel"), sources.count("geocaching"), ) text = Html( '<img src="{}popup.png?geo={}&alter={}&auto={}" alt="popup_pie">'. format(host_url, geo, alter, auto), script=True, ) return Popup(html=text), Icon(color=icon_color, icon="info-sign")
def create_map(df_collisions, df_stations, boroughs): geo_map = Map(location=[40.74527, -73.988573], tiles=None, zoom_start=12, control_scale=True) close_distance = 200 # meters # collisions TileLayer('Stamen Terrain', name='Collision Data').add_to(geo_map) for borough in boroughs: feature_group = FeatureGroup(name=borough.capitalize()) marker_cluster = MarkerCluster().add_to(feature_group) df_collisions[df_collisions['borough'] == borough].apply( lambda r: Marker( location=[r['latitude'], r['longitude']], tooltip=f"{r['cyclist_injured'] + r['cyclist_killed']} cyclists injured/killed", icon=Icon(color='darkblue', icon='exclamation-circle', prefix='fa')).add_to(marker_cluster), axis=1) feature_group.add_to(geo_map) # bike stations quartiles = df_stations['close_collisions'].quantile([0.25, 0.5, 0.75]).tolist() feature_group = FeatureGroup(name='Bike Stations') df_stations.apply(lambda r: CircleMarker( location=(r['latitude'], r['longitude']), radius=2, color=get_color(r['close_collisions'], quartiles), tooltip=f"Bike Station {int(r['id'])}: {int(r['close_collisions'])} collisions within {close_distance}m", fill=True).add_to(feature_group), axis=1) feature_group.add_to(geo_map) LayerControl(collapsed=False).add_to(geo_map) geo_map.save('templates/map.html')
def map_api_call(): url = "https://api.odcloud.kr/api/15077586/v1/centers?page=1&perPage=300&serviceKey=" + get_apikey( "serviceKey", "secret.json") result = requests.get(url=url) json_result = json.loads(str(result.text)) m = Map(location=[36.5053542, 127.7043419], zoom_start=8) marker_cluster = MarkerCluster().add_to(m) for idx in range(json_result["currentCount"]): address = json_result["data"][idx]["address"] centerName = json_result["data"][idx]["centerName"] facilityName = json_result["data"][idx]["facilityName"] lat = json_result["data"][idx]["lat"] lng = json_result["data"][idx]["lng"] iframe = centerName + ": <br> " + facilityName + ":<br> " + address popup = folium.Popup(iframe, min_width=200, max_width=200) Marker(location=[lat, lng], popup=popup, tooltip=centerName + " : " + facilityName, icon=Icon(color='green', icon='flag')).add_to(marker_cluster) account_info = get_apikey("Account", "secret.json") return render_template(template_name_or_list="index.html", map=m._repr_html_(), account_info=account_info)
def markers(dataframe, etiqueta, icono, color_f, color_i): ''' This functions make markers with the selected dataframe. Parameters: -DataFrame: the dataframe with the location. -Etiqueta: name for the label. -icon: the shape of the icon. -color_f: background color. -Color_i: color for the icon. ''' df = dataframe for i in df["location"]: dicc = { "location" : [i.get("coordinates")[1], i.get("coordinates")[0]], "tooltip" : etiqueta } ic = Icon (color = color_f, prefix = "fa", icon = icono, icon_color = color_i) Marker(**dicc, icon = ic).add_to(san_f)
def add_marker_icon(mymap, lat, lon, color, type_icon, icon_text, icon_color, tooltip, add, add_distance=False, dist=''): ''' Adds or returns a marker based on some parameters Args: mymap(Folium map) lat(float): Latitude for marker lon(float): Longitude for marker color(str): color code for marker (used in case type_icon is 'fa') type_icon(str): 'fa' to used fontawesome, 'custom' to used a picture. icon_text(str): type of fontawesome or location for picture icon_color(str): color of symbol in marker if type_icon is 'fa'. tooltip(str): text to add to marker add(boolean): True if marker directly added to map. False just to return marker (for later group adding) add_distance(boolean): by default False, meaning no distance added to tooltip. True means distance is added to tooltip dist(float): distance to be added to tooltip if add_distance is True Returns: marker(Folium Marker): if add is False ''' if type_icon == 'fa': icon = Icon( color=color, prefix="fa", icon=icon_text, icon_color=icon_color, ) elif type_icon == 'custom': #https://ocefpaf.github.io/python4oceanographers/blog/2015/11/02/icons/ icon = folium.features.CustomIcon(icon_text, icon_size=(50, 50)) else: pass loc = [lat, lon] if add_distance: tooltip = f'{tooltip}\n {dist} km' else: pass marker = Marker(location=loc, icon=icon, tooltip=tooltip) if add: marker.add_to(mymap) else: return marker
def mapsites(df, col=None): """Maps site measurements and labels them by site name and date. If a numeric column name is optionally entered then the icons will be color coded according to value quartile, with green as the lowest quartile up to dark red as the top quartile.""" m = Map(location=[41.76, -83.26]) if col: crange = df[col].describe() for i in df.index: lat = df.loc[i, 'Latitude (decimal deg)'] long = df.loc[i, 'Longitude (decimal deg)'] site = df.loc[i,'Site'] date = df.loc[i, 'Date'] if col: val = df.loc[i, col] if val <= crange['25%']: color = 'green' elif val <= crange['50%']: color = 'orange' elif val <= crange['75%']: color = 'red' else: color = 'darkred' Marker([lat, long], popup=(lat,long), tooltip=(site, date), icon=Icon(color=color)).add_to(m) else: Marker([lat, long], popup=(lat,long), tooltip=(site, date)).add_to(m) return m
def make_map(features, center_name, coverage): print('> Making map...') init_location = [customer.loc[0, 'latitude'], customer.loc[0, 'longitude']] time_map = folium.Map(location=init_location, control_scale=True, zoom_start=11) center[center.name == center_name].apply(lambda row: folium.Marker(location=[row['latitude'], row['longitude']], icon=Icon(color='black', icon='fa-wrench', prefix='fa')).add_to(time_map), axis=1) time_map.choropleth( geo_data=coverage, fill_color='yellow', fill_opacity=0.1 ) TimestampedGeoJson( data={'type': 'Feature', 'features': features}, period='P1D', duration='P1D', auto_play=False, loop=False, max_speed=10, loop_button=True, date_options='YYYY/MM/DD', time_slider_drag_update=True).add_to(time_map) print('> Done.') return time_map
def test_location(): map = folium.Map(location=[36.5053542, 127.7043419]) lon, lat = getLatLng("대전광역시 유성구 유성대로 978") Marker(location=[lon, lat], popup="test location", icon=Icon(color='green', icon='flag')).add_to(map) return map._repr_html_()
def plot_stops(folium_map: FoliumMap, clustered: bool = True): """ Plot all the stops onto ``folium_map``. ``clustered`` determines if the stop will be clustered/expanded upon zoom. Could use customized color in the future for better rendering effect. """ if clustered: parent = MarkerCluster().add_to(folium_map) else: parent = folium_map for stop in ctrl_stops.all_data: ridership = ctrl_ridership_stop.get_stop_data_by_id(stop.stop_id) popup = Popup(f"{stop.name}<br>Weekday ridership: {ridership.weekday if ridership else '(unavailable)'}" f"<br>Wheelchair Accessible: {stop.wheelchair_accessible}", min_width=250, max_width=800) if stop.wheelchair_accessible: icon_c = "green" else: icon_c = "lightred" Marker( stop.coordinate, popup=popup, icon=Icon(color=icon_c, icon_color="white", icon="bus", angle=0, prefix="fa") ).add_to(parent)
def draw_map_once_function_call(): # df = pd.read_csv("vac.csv") # df = pd.read_csv("vac210315.csv") # df = pd.read_csv("csv/vac210331.csv") df = pd.read_csv("csv/test.csv") m = Map(location=[36.5053542, 127.7043419], zoom_start=8) marker_cluster = MarkerCluster().add_to(m) addr_list = [] for idx in range(len(df)): addr_list.append(df.loc[idx, "address"]) # but one call func not multiple call # lon_list, lat_list = getLatLng_list(addr_list) for idx, addr in enumerate(addr_list): location_name = df.loc[idx, "location_name"] telephone = df.loc[idx, "telephone"] print(telephone) latitude = df.loc[idx, "latitude"] longitude = df.loc[idx, "longitude"] iframe = location_name + ":<br> " + addr + ": <br> " + telephone print(idx, ": ", iframe) popup = folium.Popup(iframe, min_width=200, max_width=200) Marker(location=[latitude, longitude], popup=popup, tooltip=location_name, icon=Icon(color='green', icon='flag')).add_to(marker_cluster) account_info = get_apikey("Account", "secret.json") return render_template(template_name_or_list="index.html", map=m._repr_html_(), account_info=account_info)
def add_target_marker(self, target): # adding marker to map Marker( location=self._get_coordinates(target), popup=target, icon=Icon() ).add_to(self.m)
def html_crtr(latitude, longitude, titles): """ float, float, str -> None Function creates the httml file that has markers of movies by location """ global html_map Marker(location=[latitude, longitude], popup=titles, icon=Icon()).add_to(fg_m)
def add_markers(map_object: Map, file_name: str): probes = get_probes(file_name) [ Marker(probe.coordinates, create_pop_up(probe), icon=Icon(color="darkblue", prefix="fa", icon="wifi")).add_to(map_object) for probe in probes ]
def mapping(df, lattitude, longitude): map_ = Map(location=[lattitude,longitude],zoom_start=15) for i, row in df.iterrows(): name = { "location":[row["lat"], row["long"]], "tooltip" : row["name"] } if row["category"] == "Coffee Shop": icon = Icon(color = "green", prefix = "fa", icon = "coffee", icon_color = "black" ) elif row["category"] == "Cafeteria": icon = Icon(color = "green", prefix = "fa", icon = "coffee", icon_color = "black" ) elif row["category"] == "High School": icon = Icon(color = "darkblue", prefix = "fa", icon = "graduation-cap", icon_color = "black" ) elif row["category"] == "Middle School": icon = Icon(color = "blue", prefix = "fa", icon = "flag", icon_color = "black" ) else: icon = Icon(color = "lightblue", prefix = "fa", icon = "flag-o", icon_color = "black" ) Marker(**name,icon = icon ).add_to(map_) return map_
def add_random_markers(feature_group: FeatureGroup) -> FeatureGroup: for i in range(random.randint(5, 10)): feature_group.add_child(child=Marker(location=[ 51.7522202 + random.uniform(-0.1, 0.1), -1.25596 + random.uniform(-0.1, 0.1) ], popup="Marker", icon=Icon())) return feature_group
def __init__(self, color: str, icon_type: str, inside_color: str = "white"): self._color = color self._inside_color = inside_color self._icon_type = icon_type if self._has_color_option(): self._icon = Icon( color=self._color, icon_color=self._inside_color, icon=self._icon_type, prefix="fa", ) else: self._icon = Icon( color="lightgray", icon_color="lightgray", icon=self._icon_type, prefix="fa", )
def create_stations_map(df): m1 = StudyMap.create_map() for station_type in df.StationType.unique().tolist(): mask = (df["StationType"] == station_type) df2 = df.loc[mask] # markers that will be added to the cluster... # marker_cluster = MarkerCluster(name=station_type).add_to(m1) for idx, row in df2.iterrows(): location = [row.geometry.y, row.geometry.x] popup = StudyMap.create_popups_from_template( location, POPUP_TEMPLATE, row.StationName, row.StationCode, row.StationType, row.Status, row.ReserveName, row.ActiveDates, row.StationType ) # Give color to marker based on station_type def get_color(station_type): switcher = { "Meteorological": "blue", "Nutrients": "green", "Water Quality": "red", } color = switcher.get(station_type, "gray") return color # icon_name = "check-circle" if row.Status == "Active" else "times-circle" icon_name = "glyphicon-ok" if row.Status == "Active" else "glyphicon-remove" icon = Icon( icon=icon_name, color=get_color(row.StationType), icon_color='white' ) Marker( location=location, popup=popup, tooltip=f"{row.StationType} - {row.StationCode}", icon=icon, draggable=False ).add_to(m1) # Create the layer control and add to map control = LayerControl(position='topright') control.add_to(m1) return m1
def create_marker(gdf, name_map): for i, row in gdf.iterrows(): #popup distrito distrito = { "location": [row["latitud"], row["longitud"]], "tooltip": row["name"] } icon = Icon(color="blue", prefix="fa", icon="coffee", icon_color="black") Marker(**distrito, icon=icon).add_to(name_map)
def folium_planes(df_planes,lat,lon): map_2 = Map(location=[f'{lat}',f'{lon}'],zoom_start=14.5) for i,row in df_planes.iterrows(): distrito = { "location" : [row["latitud"],row["longitud"]], "tooltip" : row["name"] } if row["categoria"] == "historic site": icon = Icon(color = "lightblue", prefix = "fa", icon = "eye", icon_color = "black") elif row["categoria"] == "nightclub": icon = Icon(color = "lightred", prefix = "fa", icon = "glass", icon_color = "black") elif row["categoria"] == "food": icon = Icon(color = "beige", prefix = "fa", icon = "cutlery", icon_color = "black") elif row["categoria"] == "hotels": icon = Icon(color = "cadetblue", prefix = "fa", icon = "h-square", icon_color = "white") else: icon = Icon(color = "lightblue", prefix = "fa", icon = "eye", icon_color = "black") Marker(**distrito, icon = icon).add_to(map_2) return map_2
def create_map(user_coords: list, closest_points: list) -> None: """ creates map and saves it """ mp = Map(location=[user_coords[0], user_coords[1]], zoom_start=15) markers = FeatureGroup() closest_dict = create_dictionary(closest_points) for key in closest_dict: markers.add_child( Marker(location=[key[0], key[1]], popup=closest_dict[key], icon=Icon())) your_location = FeatureGroup() your_location.add_child( Marker(location=[user_coords[0], user_coords[1]], popup='You are here', icon=Icon())) mp.add_child(markers) mp.add_child(your_location) mp.add_child(LayerControl()) mp.save('map1.html')
def get_the_map(closer_places, the_place, tags): final_map = Map(location=the_place, zoom_start=15) counter = 0 for coordinates in closer_places: loc = coordinates icon = Icon(color="green", prefix="fa", icon="flag", icon_color="black", tooltip=tags[counter]) counter += 1 marker = Marker(location=loc, icon=icon) marker.add_to(final_map) loc = the_place icon_2 = Icon(color="red", prefix="fa", icon="space-shuttle", icon_color="black", tooltip="The place") marker = Marker(location=loc, icon=icon_2) marker.add_to(final_map) return final_map
def final_location(coordinates_, map_lnd): """ Places the final location on the map Args: coordinates_ (list): coordinates of the final location map_lnd (folium.Map): the map where the data has to be placed. """ icono = Icon(color="white", prefix="fa", icon="trophy", icon_color="black") loc = {"location": coordinates_, "tooltip": "Gaming Company"} marker_company = Marker(**loc, icon=icono) marker_company.add_to(map_lnd)
def generate_map(name_and_coordinates:dict): """ generates map """ mp = Map( zoom_start=15) markers = FeatureGroup() for screen_name in name_and_coordinates: markers.add_child(Marker(location=[name_and_coordinates[screen_name][0], name_and_coordinates[screen_name][1]], popup=screen_name, icon=Icon())) mp.add_child(markers) mp.add_child(LayerControl()) return mp._repr_html_()
def nearby(df_places, map_lnd): """ Places what is near the final location on the map Args: df_places(df): the dataframe with the coordinates information map_lnd (folium.Map): the map where the data has to be placed. """ for i, row in df_places.iterrows(): p = {"location": row["coordinates"], "tooltip": row["name"]} if row['place'] == 'starbucks': icon = Icon(color="green", prefix="fa", icon="coffee", icon_color="black") elif row['place'] == 'school': icon = Icon(color="red", prefix="fa", icon="book", icon_color="black") elif row['place'] == 'party': icon = Icon(color="pink", prefix="fa", icon="glass", icon_color="black") elif row['place'] == 'vegan': icon = Icon(color="blue", prefix="fa", icon="cutlery", icon_color="black") else: icon = Icon(color="orange", prefix="fa", icon="futbol-o", icon_color="black") Marker(**p, icon=icon).add_to(map_lnd)
def plot_stops_given_with_color(folium_map: FoliumMap, stops: List[Tuple[MMTStopsAtCross, Optional[str]]]): """ Plot ``stops`` as markers onto ``folium_map``. The :class:`str` in the sub-element is the color to be used on the stop marker. If this is ``None``, then "blue" will be used. """ for stop, color in stops: popup = Popup(stop.cross_name, min_width=250, max_width=800) Marker( stop.coordinate, popup=popup, icon=Icon(color=color or "blue", icon_color="white", icon="bus", angle=0, prefix="fa") ).add_to(folium_map)
def add_market(x, y, q, z): for i, row in pd.DataFrame(y).iterrows(): parque = Marker(location=[ row['location']['coordinates'][1], row['location']['coordinates'][0] ], tooltip=row['name'], icon=Icon(color=z, prefix="fa", icon=q, icon_color="black")) parque.add_to(x) return x