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 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 __init__(self, geo: GeoPoint, popup_path: str, *args, **kwargs): self.geo = geo weather = Jinja2Processor(popup_path, casts=geo.get_weather()).content self.marker = Marker(location=[self.geo.latitude, self.geo.longitude], popup=Popup(weather), *args, **kwargs)
def map_points(df, lat_col='latitude', lon_col='longitude', zoom_start=11, plot_points=False, pt_radius=15, draw_heatmap=False, heat_map_weights_col=None, heat_map_weights_normalize=True, heat_map_radius=15): """Creates a map given a dataframe of points. Can also produce a heatmap overlay Arguments: df: dataframe containing points to maps lat_col: Column containing latitude (string) lon_col: Column containing longitude (string) zoom_start: Integer representing the initial zoom of the map plot_points: Add points to map (boolean) pt_radius: Size of each point draw_heatmap: Add heatmap to map (boolean) heat_map_weights_col: Column containing heatmap weights heat_map_weights_normalize: Normalize heatmap weights (boolean) heat_map_radius: Size of heatmap point Returns: folium map object """ # center map in the middle of points middle_lat = df[lat_col].mean() + 0.2 middle_lon = df[lon_col].mean() curr_map = Map(location=[middle_lat, middle_lon], tiles='Cartodb Positron', zoom_start=zoom_start) # add points to map if plot_points: for _, row in df.iterrows(): if row['station_type'] == 'aq': Marker([row[lat_col], row[lon_col]], popup=row['station'], icon=folium.Icon(color='green')).add_to(curr_map) else : Marker([row[lat_col], row[lon_col]], popup=row['station'], icon=folium.Icon(color='blue')).add_to(curr_map) # add heatmap if draw_heatmap: # convert to (n, 2) or (n, 3) matrix format if heat_map_weights_col is None: # cols_to_pull = [lat_col, lon_col] heat_df = [[row[lat_col], row[lon_col]] for index, row in df.iterrows()] else: # if we have to normalize if heat_map_weights_normalize: df[heat_map_weights_col] = \ df[heat_map_weights_col] / df[heat_map_weights_col].sum() heat_df = [[row[lat_col], row[lon_col], row[heat_map_weights_col]] for index, row in df.iterrows()] HeatMap(heat_df).add_to(curr_map) return curr_map
class GeoMarker: def __init__(self, geo: GeoPoint, popup_path: str, *args, **kwargs): self.geo = geo weather = Jinja2Processor(popup_path, casts=geo.get_weather()).content self.marker = Marker(location=[self.geo.latitude, self.geo.longitude], popup=Popup(weather), *args, **kwargs) def mark(self, map_: Map) -> None: self.marker.add_to(map_)
def print_heat_map_pred(df, lat_a, lon_a, lat_b, lon_b): start_lat = round((lat_a + lat_b) / 2, 7) start_lon = round((lon_b + lon_a) / 2, 7) heat_map = folium.Map(location=[start_lat, start_lon], tiles='cartodbpositron', zoom_start=15) HeatMap(data=df[['lat', 'lon', 'weights']], radius=16).add_to(heat_map) heat_map.add_child( Marker(location=[lat_a, lon_a], icon=folium.Icon(color='red'))) heat_map.add_child( Marker(location=[lat_b, lon_b], icon=folium.Icon(color='red'))) return heat_map
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 locate(city, marker , services=[], companies=[]): start_lat = city["coordinates"][1] start_lon = city["coordinates"][0] heat_m = folium.Map(location=[start_lat, start_lon],tiles='cartodbpositron', zoom_start=15) Marker([marker["lat"], marker["long"]], icon=folium.Icon(color='red')).add_to(heat_m) colors = ['green', 'black', 'darkpurple', 'pink', 'blue', 'darkgreen'] for j,s in enumerate(services): for i in range(s.shape[0]): heat_m.add_child(Marker([s.loc[i]["location"]["lat"], s.loc[i]["location"]["lng"]], icon=folium.Icon(color=colors[j]))) for j,c in enumerate(companies): j += 4 for i in range(c.shape[0]): heat_m.add_child(Marker([c.loc[i]["latitude"], c.loc[i]["longitude"]], icon=folium.Icon(color=colors[j]))) return heat_m
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 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
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 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 add_target_marker(self, target): # adding marker to map Marker( location=self._get_coordinates(target), popup=target, icon=Icon() ).add_to(self.m)
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 create_map(data): if not data: raise PreventUpdate df = pd.DataFrame(data) qtd_sem_latlon = df[["address_lat", "address_lon"]].isna().max(axis=1).sum() df = df.dropna(subset=["address_lat", "address_lon"]) map = Map( location=df[["address_lat", "address_lon"]].mean().values, height="89%", tiles= "https://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png", attr="toner-bcg", ) marker_cluster = MarkerCluster().add_to(map) for _, row in df.iterrows(): Marker( location=[row["address_lat"], row["address_lon"]], popup=box(**row), ).add_to(marker_cluster) return f"{qtd_sem_latlon} imóveis sem latitude ou longitude", map._repr_html_( )
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 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 produce_map(year): """ This function generates a map of the US and displays all the data for a given year in popups and a color gradient """ year_file = yearly_map(year) state_geo = os.path.join('data', 'us_states.json') state_data = pd.read_csv(year_file) marker_year = 'StateLonandLat'+str(year)+'.csv' marker_data = os.path.join('data',marker_year) marker_coord = pd.read_csv(marker_data) #establishes the center of map based on longitude and latitude m = Map(location=[50.246366, -110], zoom_start=4) #sets the color scheme, data used for legend, and legend labels Choropleth(geo_data=state_geo,name='choropleth',data=state_data, columns=['State', 'Death Rate'], key_on='feature.id', fill_color='BuPu', fill_opacity=0.7, line_opacity=0.5, legend_name='Average Death Rate in '+str(year) ).add_to(m) #create markers and places them within corresponding state for i in range(0,len(marker_coord)): #popup contains data about causes fo death popup = Popup(marker_coord.iloc[i]['state'],max_width=350) Marker([marker_coord.iloc[i]['lon'],marker_coord.iloc[i]['lat']], popup=popup).add_to(m) LayerControl().add_to(m) map = str(year)+'.html' m.save(map) webbrowser.open('file://'+os.path.realpath(map))
def build_ski_marker(location, data, width=475, height=250, icon_color='#966fd6', chart_kw={}): centroid = data[['latitude', 'longitude']].iloc[0].values tooltip = 'Skiing in {:s}'.format(location) chart = build_ski_chart(location, data, width=width - 75, height=height - 25, **chart_kw) popup = Popup(max_width=width).add_child( VegaLite(chart.to_json(), width=width, height=height)) icon_kw = dict(icon_shape='circle', border_width=0, text_color='white', border_color='white', background_color='black', inner_icon_style='font-size:11px; padding-top: 1px;') icon = BeautifyIcon('line-chart', **icon_kw) marker = Marker(location=centroid, icon=icon, tooltip=tooltip, popup=popup) return marker
def visualize_map(self, df, theme=None): dark_attr = "https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png" positron_attr = "https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png" osm_attr = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" if theme == 'dark': map = Map(location=[34.0522, -118.2437], control_scale=True, zoom_start=12, attr=dark_attr, tiles="cartodbdark_matter") elif theme == 'positron': map = Map(location=[34.0522, -118.2437], control_scale=True, zoom_start=12, attr=positron_attr, tiles="cartodbpositron") else: map = Map(location=[34.0522, -118.2437], control_scale=True, zoom_start=12, attr=osm_attr, tiles="openstreetmap") cluster = MarkerCluster().add_to(map) locations = df[['latitudes', 'longitudes']].values.tolist() for point in range(len(locations)): Marker(locations[point], popup=df['listing_name'][point]).add_to(cluster) return map
def getMap(): # initialize the map to the starting location and add starting location # this library will base location off user IP address. It works locally, but # not once the app is deployed (different IP address) g = geocoder.ip('me') start_coords = g.latlng themap = Map(location=start_coords, tiles="OpenStreetMap", zoom_start=15) folium.Marker(location=start_coords, popup='Your Location', icon=folium.Icon(color='red', icon='hi')).add_to(themap) # get nearby restaurant data startloc = str(start_coords[0]) + "," + str(start_coords[1]) df = getRestaurantData(startloc) data = cleanDataframe(df) # add restaurants to the map for (y, x) in data.iterrows(): loc = [] loc.append(x['latitude']) loc.append(x['longitude']) color = "green" if (x['rating'] < 4.0): color = "orange" popup_text = "{}<br> Cuisine: {}<br> Average Rating: {}<br> Number of Reviews: {}" popup_text = popup_text.format(x["name"], x["descriptors"], x["rating"], x['review_count']) themap.add_child( Marker(location=loc, popup=popup_text, icon=folium.Icon(color=color))) return themap._repr_html_()
def get_marker(self, width=450, height=250, icon_color='#966fd6', chart_kw={}): chart = self.build_chart(width=width - 75, height=height - 25, **chart_kw) popup = Popup(max_width=width).add_child( VegaLite(chart.to_json(), width=width, height=height)) icon_kw = dict(icon_shape='circle', border_width=0, text_color='white', border_color='white', background_color='green', inner_icon_style='font-size:11px; padding-top: 1px;') icon = BeautifyIcon('line-chart', **icon_kw) location = self.data.iloc[0][['latitude', 'longitude']].values marker = Marker(location=location, icon=icon, tooltip=self.semantic, popup=popup) return marker
def as_map(self, img_name=None): if img_name == None: coord_index = self.meta_keys.index('GPS') coord_list = [ self.metadata[key][coord_index][0:2] + [key] for key in self.metadata.keys() ] print(coord_list) cood_t = list(map(list, zip(*coord_list))) center = [(max(cood_t[0]) + min(cood_t[0])) / 2, (max(cood_t[1]) + min(cood_t[1])) / 2] print(center) print(coord_list) img_map = Map( location=center, zoom_start=13, width='100%', height='100%', tiles='https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', attr='Google') for x, y, img in coord_list: Marker(location=[x, y], popup='', tooltip=img).add_to(img_map) return (img_map._repr_html_()) return ('')
def multi_map(input_file): os.chdir(geomap_root) # Check if Geolite file exists geolite_check() file_path = os.path.abspath(os.pardir) input_file = f"{file_path}/{input_file}" with open(input_file) as f: line = [line.strip() for line in f.readlines()] ip_map = Map([40, -5], tiles="OpenStreetMap", zoom_start=3) try: geo_reader = geoip2.database.Reader("GeoLite2-City.mmdb") for addr in line: response = geo_reader.city(addr) if response.location: logger.success(f"[+] Mapping {addr}") lat = response.location.latitude lon = response.location.longitude Marker([lat, lon], popup=addr).add_to(ip_map) ip_map.save("multi_map.html") except ValueError as err: print(f"[error] {err}") except geoip2.errors.AddressNotFoundError: logger.warning("[-] Address is not in the geoip database.") except FileNotFoundError: geolite_check()
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 update_map(): m_1 = folium.Map(location=[40.415157, -3.689048], tiles='openstreetmap', zoom_start=10) y, x = connect("datamad1019", "swimming-pools") aggResult = x.find({}) df2 = pd.DataFrame(list(aggResult)) df2.head() mc = MarkerCluster() for idx, row in df2.iterrows(): if not math.isnan(row['Location']["cordinates"][1]) and not math.isnan( row['Location']["cordinates"][0]): link = '<a href=' + f'{row["Google_link"]}' + 'target="_blank">' + 'Satellite View' + '</a>' mc.add_child( Marker([ row['Location']["cordinates"][1], row['Location']["cordinates"][0] ], popup=folium.Popup(link))) m_1.add_child(mc) embed_map(m_1, "./templates/map.html") print( "New map generated. Please restart application to see new swimming pools." ) return m_1
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 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_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)