def heatmap(gdf, location, gradient=None): """ This is a function that creates a heatmap. Parameters ---------- gdf (geodata frame) : GeoDataFrame location (list): latitude and longitude of central map location (e.g. NYC = [40.693943, -74.025]) gradient (dict) (default:None): option to change the gradient, useful when combining other heatmaps Returns ------- a heatmap of where a specific class of data is _ by sensor """ emptymap = Map(location=location, zoom_start=12) # create heatmap hm = HeatMap( list(zip(gdf.latitude.values, gdf.longitude.values)), min_opacity=0.2, radius=10, blur=13, gradient=gradient, max_zoom=1, ) # add heatmap layer to empty layer emptymap.add_child(hm) return emptymap
def _add_layer(cls, map_object: Map, layer_document: MapLayerDocument) -> None: """ Create layer on a Folium Map. Method creates layer and adjusts it based on configuration. The layer is appended to the provided Folium Map. :param map_object: (Map) map object to create layer on :param layer_document: (MapLayerDocument) layer document configuration object. :return: None """ model = layer_document.model latitude_column = layer_document.latitude longtitude_column = layer_document.longtitude axis = model.axis axis_label = axis.name or axis.data_field feature_group = FeatureGroup(name=axis_label) data_source = layer_document.data_source for row in data_source.itertuples(): latitude = getattr(row, latitude_column.data_field) longtitude = getattr(row, longtitude_column.data_field) value = getattr(row, axis.data_field) coordinates = [latitude, longtitude] # model.figure.size *= 5 marker = cls._create_marker(layer_value=str(value), coordinates=coordinates, layer_figure=model.figure) feature_group.add_child(marker) map_object.add_child(feature_group)
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 build_heat_map(data, sample): heat_map = Map(**MAP_DEFAULT_START_PARAMS) HeatMap(data[['lat', 'long']], radius=10).add_to(heat_map) if 'lat' in sample.columns: heat_map.add_child( Circle(*sample[['lat', 'long']].values, radius=1.1e5)) return heat_map
def build_html_for(execution_date, conn, credentials): sql_query = build_query_for(execution_date.year, execution_date.month) logging.info(sql_query) df = sqlio.read_sql_query(sql_query, conn) if df.empty: logging.info('Query returned empty results set') return pickup_map = Map( location=[df['pickup_latitude'].mean(), df['pickup_longitude'].mean()], tiles='OpenStreetMap', zoom_start=12) mc = MarkerCluster() for row in df.itertuples(): mc.add_child( folium.Marker(location=[row.pickup_latitude, row.pickup_longitude], popup=str(row.pickup_latitude) + ',' + str(row.pickup_longitude))) pickup_map.add_child(mc) html_file_name = "{}-{}_pickups_map.html".format(execution_date.year, execution_date.month) pickup_map.save(outfile=html_file_name) upload_file_to_s3( html_file_name, "data-sprints-eng-test/outputs/monthly/{}".format(html_file_name), credentials, "text/html") os.remove(html_file_name)
def gen_map(self): # read database connection = sqlite3.connect("posts.db") cursor = connection.cursor() sql = f"""SELECT * FROM "{self.handle}" """ cursor.execute(sql) result = cursor.fetchall() connection.close() # Generate map, cluster class and create empty coordinates list if self.handle == "4x4theboiz": my_map = Map(location=[-25.25, 21.2], zoom_start=5) elif self.handle == "teampolarsteps": my_map = Map(location=[52.35, 5.3], zoom_start=9) elif self.handle == "cityofcapetown": my_map = Map(location=[-34.1, 18.420], zoom_start=10) elif self.handle == "backpackingtours": my_map = Map(location=[10, 100], zoom_start=3) elif self.handle == "tony_ontheroad": my_map = Map(location=[38.5, -2.75], zoom_start=6) elif self.handle == "rolling_sloane": my_map = Map(location=[55, 2.64], zoom_start=4) elif self.handle == "cape_secrets": my_map = Map(location=[-33.4, 18.8], zoom_start=8) else: my_map = Map(location=[0, 0], zoom_start=2) mc = MarkerCluster() coords = [] # For each location convert address to coordinates, create popup and marker, # add to marker cluster for i in range(0, len(result), 1): popup_content = f"{result[i][0]} <br> " \ f"<a href={result[i][1]} > See Post" p = Popup(popup_content, max_width=400) mk = Marker([result[i][2], result[i][3]], p) mc.add_child(mk) lat_lon = (result[i][2], result[i][3]) coords.append(lat_lon) # Add Polyline with coords if self.handle == "4x4theboiz": polyline = PolyLine(coords, color="red", weight=2, opacity=0.7) polyline.add_to(my_map) elif self.handle == "tony_ontheroad": polyline = PolyLine(coords, color="red", weight=2, opacity=0.7) polyline.add_to(my_map) else: pass # Add Marker Cluster with mc my_map.add_child(mc) # Save the Map Instance Into a HTML file map_name = f"templates/map_{self.handle}.html" my_map.save(map_name)
def test_color_line(): m = Map([22.5, 22.5], zoom_start=3) color_line = folium.ColorLine([[0, 0], [0, 45], [45, 45], [45, 0], [0, 0]], [0, 1, 2, 3], colormap=['b', 'g', 'y', 'r'], nb_steps=4, weight=10, opacity=1) m.add_child(color_line) m._repr_html_()
def test_color_line(): m = Map([22.5, 22.5], zoom_start=3) color_line = folium.ColorLine( [[0, 0], [0, 45], [45, 45], [45, 0], [0, 0]], [0, 1, 2, 3], colormap=['b', 'g', 'y', 'r'], nb_steps=4, weight=10, opacity=1) m.add_child(color_line) m._repr_html_()
def create(cls, base_object: Map, *args, **kwargs) -> Map: """ Add LayerControl feature group to provided folium map. :param base_object: (Map) map that layer control should be appended to. :return: base_object(Map) - folium map object with appended layer control. """ base_object.add_child(LayerControl()) return base_object
def _init_map(self, zoom: int, live_marker: bool): map = Map( location=list(self._current_view_coordinates()), zoom_start=zoom, min_zoom=3, ) map.add_child(LatLngPopup()) if live_marker: map.add_child(ClickForMarker(popup="Point")) return map
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 create_map(self): """ Creates a map of earthquakes. """ map1 = Map(tiles="Stamen Terrain") for i in self.locations: if self.place_damaged[i[0], i[1]] and self.place_damaged[i[0], i[1]] > 0.5: if self.place_damaged[i[0], i[1]] > 5\ : a = 'darkred' to_write = 'The earthquake damage here is really high.' elif self.place_damaged[i[0], i[1]] > 3.5: a = 'red' to_write = 'Might cause some destructions.' elif self.place_damaged[i[0], i[1]] > 1.5: a = 'orange' to_write = "Some ground shaking but would't cause some big troubles" else: a = 'yellow' to_write = "Almost nothing changed, but probably make some inconvenience to people" if len(self.date) == 1: sized = 4 elif len(self.date) == 2: sized = 50 elif len(self.date) == 3: sized = 1500 map1.add_child( Circle(location=[i[1], i[0]], popup=to_write, radius=10000 + sized * self.locations[i[0], i[1]], color=a, fill=True, fill_color=a)) map_name = "templates/Map_" + str(int(self.date[0])) if len(self.date) >= 2: map_name += '_' + str(int(self.date[1])) if len(self.date) == 3: map_name += "_" + str(int(self.date[2])) map_name += '.html' map1.save(map_name)
def add_graph_markers_continent(countries: [vaccine_classes.Location], continent_filename: str, folium_map: folium.Map) -> None: """Use plotly to generate graphs for each continent and add markers for each graph to the map. Preconditions: - vaccine_filename != '' - coordinate_filename != '' """ continents = process_vaccine_data.create_continent_locations( countries, continent_filename) feature_group = folium.FeatureGroup(name='Continental Markers and Graphs') for continent in continents: if continent.vaccine_data != {}: dates = list(continent.vaccine_data.keys()) dates.sort() total_vaccinations = [] for date in dates: total_vaccinations.append(continent.vaccine_data[date]) fig = go.Figure() fig.add_trace(go.Scatter(x=dates, y=total_vaccinations)) fig.update_xaxes(title_text='Date') fig.update_yaxes(title_text='Total Vaccinations') title = f'Total Vaccinations in {continent.name} Over Time' fig.update_layout(title_text=title) fig.write_image(file='datasets/graph.jpg', format='jpg', width=500, height=410) encoded = base64.b64encode(open('datasets/graph.jpg', 'rb').read()) html = '<img src="data:image/jpg;base64,{}">'.format iframe = folium.IFrame(html(encoded.decode('UTF-8')), width='510px', height='430px') feature_group.add_child( folium.Marker(location=continent.coordinates, popup=folium.Popup(iframe, max_width=2650), icon=folium.Icon(icon='globe', color='red'))) folium_map.add_child(feature_group)
def map_points_circles(df, feature, date): print(feature.title(), 'at time:', date) # Create a map this_map = Map(prefer_canvas=True) # Check for the inputs to be on the dataframe # Getting data data = df[df['datetime'] == date] # Create a color map color_var = str(feature) #what variable will determine the color cmap = LinearColormap(['blue', 'red'], vmin=data[color_var].quantile(0.05), vmax=data[color_var].quantile(0.95), caption=color_var) # Add the color map legend to your map this_map.add_child(cmap) def plotDot(point): '''Takes a series that contains a list of floats named latitude and longitude and this function creates a CircleMarker and adds it to your this_map''' CircleMarker(location=[point.latitude, point.longitude], fill_color=cmap(point[color_var]), fill=True, fill_opacity=0.4, radius=40, weight=0).add_to(this_map) # Iterate over rows data.apply(plotDot, axis=1) # Set the boundaries this_map.fit_bounds(this_map.get_bounds()) # Show plot return this_map
def compute_map(df): lat = list(df['lat']) lng = list(df['lng']) company_name = list(df['company_name']) map = Map(location=[15.2993, 74.1240], zoom_start=10) fgv = FeatureGroup() for lt, ln, name in zip(lat, lng, company_name): if not math.isnan(lt): fgv.add_child( CircleMarker(location=[lt, ln], radius=6, popup=name, fill_color="green", fill=True, color='grey', fill_opacity=0.7)) pass map.add_child(fgv) map.save(map_name)
def generate_web_map_html(filename: str) -> None: map = Map(location=[48.7767982, -121.8109970]) volcanoes_feature_group = get_volcanoes_feature_group() population_feature_group = get_population_feature_group() map.add_child(volcanoes_feature_group) map.add_child(population_feature_group) map.add_child(LayerControl()) map.save(filename)
def readJobFile(): start_loc = getlnglat('北京')['result']['location'] m = Map(location=[start_loc['lat'], start_loc['lng']], zoom_start=8) path = r'C:\Users\IBM_ADMIN\AppData\Local\Programs\Python\Python35\mydata\testjob' loc_file_list = os.listdir(path) for job_file in loc_file_list: if job_file.startswith(u'北京') or 1 == 1: job_file = os.path.join(path, job_file) with open(job_file, 'r') as f: for line in f: jobinfo = {}.fromkeys( ('company', 'position', 'location', 'salary')) lineinfo = line.split('|') jobinfo['company'] = lineinfo[0] jobinfo['position'] = lineinfo[1] jobinfo['address'] = lineinfo[2] jobinfo['salary'] = lineinfo[3] try: loc = getlnglat( jobinfo['company'])['result']['location'] maker = Marker(location=[loc['lat'],loc['lng']], popup=Popup('%s\n%s\n%s' % \ (jobinfo['company'], jobinfo['position'], jobinfo['salary']) ), icon=Icon()) m.add_child(maker) except: info = sys.exc_info() print(info[0], ':', info[1]) print(jobinfo['company']) pass m.save('51job.html')
def init_map(path, data): """ str, list -> folium map Creates a folium map .html file in the direction path. """ map = Map() data_group = FeatureGroup(name='Data Layer') geolocator = Nominatim(user_agent='shumakov') geocode = RateLimiter(geolocator.geocode, min_delay_seconds=0.01) for row in data: if not row[0] or not row[1]: continue pos = geolocator.geocode(row[1]) data_group.add_child( CircleMarker(location=[pos.latitude, pos.longitude], radius=7, popup=row[0], fill_color='red', color='white', fill_opacity=0.5)) map.add_child(data_group) map.save(path) return map
def test_unit(): feature_group = FeatureGroup(name='Teltonika') m = Map( location=[25.09841, 55.16275], zoom_start=2, tiles= 'https://api.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoidGFsazJ0cGMiLCJhIjoiY2ptenozdm0yMWlyNTNwcGhwbzc3dG9rNCJ9.NzVTxRk8eVz6g_BrbjonWg', attr='Mapbox') Marker(location=[25.09955, 55.16263], popup='Mt. Hood Meadows', icon=Icon(icon='dashboard')).add_to(feature_group) Marker(location=[25.10124, 55.16332], popup='Timberline Lodge', icon=Icon(color='green')).add_to(feature_group) Marker(location=[25.10255, 55.16545], popup='''<p>Asset Name: Teltonika</p> <p><img src="https://html-online.com/editor/tinymce4_6_5/plugins/emoticons/img/smiley-cool.gif" alt="cool" /></p> <p>Speed: <span style="color: #ff0000;">12 km/hr</span></p> <p> </p> <p> </p>''', icon=Icon(color='red', icon='screenshot')).add_to(feature_group) m.add_child(LatLngPopup()) feature_group.add_to(m) LayerControl().add_to(m) m.add_child(MeasureControl()) m.save('osm.html')
def plot_bar_graphs(df_years, html_link, name, color): print('>plotting map...') listOfMedians = prepare_for_data(df_years) barGraphMap = Map(location = latlng, zoom_start = 10, tiles = 'Stamen Terrain') for x,y,df,file,station,ttip in zip(coords['Lat_DD'], coords['Long_DD'], listOfMedians, file_names, coords['Station Number'], coords['Station label']): bar = vincent.GroupedBar(df) bar.axis_titles(x = "Index", y = name) bar.width = 900 bar.height = 250 bar.legend(title='Year') bar.to_json(file) vis1 = os.path.join('/Users/fetch/Desktop/ProjectDirectory', file) folium.Marker(location=[x,y], icon = DivIcon( icon_size=(28,25), icon_anchor=(7, 20), html='<div style="font-family: Rockwell; font-size: 9pt; color :#00664b">'+str(station)+'</div>', ), popup=folium.Popup(max_width=1100).add_child( folium.Vega(json.load(open(vis1)), width= 1000, height=300)) ).add_to(barGraphMap) barGraphMap.add_child(folium.CircleMarker([x,y], fill_color = color, color = color, radius = 22, tooltip = ttip)) barGraphMap.save(html_link+'.html')
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 create_map(data, file_name="index.html"): map = Map( location=[data[col].mean() for col in ["latitude", "longitude"]], tiles="Stamen Toner", zoom_start=2, ) fg_nodes_locations = FeatureGroup(name="Locations") fg_nodes_counts = FeatureGroup(name="Counts") circles = [ { "radius": 5, "stroke": False, "fill": True, "fill_color": "crimson", "fill_opacity": opacity, "location": [latitude, longitude], "popup": Popup( html=f""" <style> tbody {{ text-align: center; }} table, tr, td {{ border-collapse: collapse; border: 1px solid black; }} </style> <h3>{ip}</h3> <table> <tbody> <tr> <td><strong>ISP</strong></td> <td>{org}</td> </tr> <tr> <td><strong>Completed requests</strong></td> <td>{completed_requests}</td> </tr> </tbody> </table> """, max_width=300, ), } for ip, latitude, longitude, org, completed_requests, opacity in [ named_tuple[2:] for named_tuple in data.itertuples(index=False) ] ] q1, q2, q3, q4 = nodes_counts_quantiles() def opacity(scaled_nodes_count): # print(scaled_nodes_count) if scaled_nodes_count < q1: return 0 elif q1 <= scaled_nodes_count < q2: return 0.1 elif q2 <= scaled_nodes_count < q3: return 0.25 elif q3 <= scaled_nodes_count < q4: return 0.5 else: return 0.75 def style_function(feature): fillOpacity = opacity(feature["properties"]["scaled_nodes_count"]) return {"fillColor": "blue", "weight": 0, "fillOpacity": fillOpacity} fg_nodes_counts.add_child( GeoJson( data=open("data/enriched_world.json", encoding="utf-8-sig").read(), style_function=style_function, ) ) for circle in circles: fg_nodes_locations.add_child(CircleMarker(**circle)) map.add_child(fg_nodes_counts) map.add_child(fg_nodes_locations) map.add_child(LayerControl()) map.save(file_name)
from datawrangling.geomunging import g3half from pprint import pprint from folium import LayerControl, Map, FeatureGroup from folium.plugins import HeatMap # create map object m = Map(tiles='openstreetmap',min_zoom=7, max_zoom=14, zoom_start=7,\ min_lat=40, max_lat=48,min_lon=-114, max_lon=-128, \ max_bounds=True) fg = FeatureGroup('Heat Map') # add list of coordinates to map object fg.add_child(HeatMap(list(zip(g3half.lat.values, g3half.lon.values)))) m.add_child(fg) LayerControl().add_to(m) m.save(r'templates\g3halfeventheat.html')
import json import urllib.request import urllib.request from folium import Map, CircleMarker, Marker map = Map() earthquake_API = urllib.request.urlopen("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2014-01-02&endtime=2014-01-03") earthquake_API = earthquake_API.read().decode('utf-8') earthquake = json.loads(earthquake_API) for i in earthquake["features"]: map.add_child(CircleMarker(location=[-180, 180], popup="Test", color = "brown", fill_opacity = 0.3, radius=20, fill_color = "red")) break map.save('Map_1.html')
def make_map(data_df, loc_df): OK_COORDINATES = (26.43, 127.8) # base map my_map = Map(location=OK_COORDINATES, zoom_start=10.12, min_zoom=8, max_zoom=13, tiles='cartodb positron') # tiles = [”OpenStreetMap”, ”Stamen Terrain”, “Stamen Toner”, “Stamen Watercolor”, ”CartoDB positron”, “CartoDB dark_matter”, ”Mapbox Bright”, “Mapbox Control Room” ] tile_options = ['cartodb positron', 'stamen terrain'] tile_names = ["simple map", "terrain map"] for name, opt in zip(tile_names, tile_options): TileLayer(opt).add_to(my_map, name=name) # cluster object cluster = MarkerCluster(control=False) my_map.add_child(cluster) group_list = [] for age_id in range(10): if age_id == 9: age_str = 'N/A' else: age_str = '%d0s' % (age_id + 1) group = FeatureGroupSubGroup(cluster, age_str) my_map.add_child(group) group_list.append(group) # add a marker for every record in the filtered data, use a clustered view for ind, d in data_df.iterrows(): # make pop-up string place = d['place'] age = d['age'] gender = d['gender'] conf_date = d['confirm_date'] status = d['status'] if age == 'N/A': age_id = 9 else: age_id = int(age[0]) - 1 pop_str = 'date:%s, age:%s' % (conf_date, age) if gender == 'Male': icon = Icon(color='blue', icon='male', prefix='fa') elif gender == 'Female': icon = Icon(color='red', icon='female', prefix='fa') else: icon = Icon(color='black', icon='question-circle', prefix='fa') # get coordinates try: lat_value = loc_df[loc_df.place == place].lat.values[0] lng_value = loc_df[loc_df.place == place].lng.values[0] except: lat_value = loc_df[loc_df.place == '県外'].lat.values[0] lng_value = loc_df[loc_df.place == '県外'].lng.values[0] pop_str = 'date:%s, age:%s, place=%s' % (conf_date, age, 'outside Okinawa') #print(place, lat_value, lng_value) # create marker with coordinates & pop-up info marker = Marker(location=[lat_value, lng_value], popup=pop_str, icon=icon) # add marker to gorup group_list[age_id].add_child(marker) LayerControl().add_to(my_map) my_map.save("covid19_okinawa_map.html") #display(my_map) return my_map
def get_prediction(self): """ Logical assumption about nearest earthquakes based on last month - 2 month information. """ now = datetime.datetime.now() now = list(map(int, str(now.date()).split('-'))) now.reverse() days = 0 if now[-2] in [2, 4, 6, 8, 9, 11]: for day in range(now[-3], 31): days += 1 self.get_earthquakes_for_text( [day, int(now[-2]) - 1, int(now[-1])]) elif now[-2] == 3: for day in range(now[-3], 28): days += 1 self.get_earthquakes_for_text( [day, int(now[-2]) - 1, int(now[-1])]) elif now[-2] == 1: for day in range(now[-3], 31): days += 1 self.get_earthquakes_for_text([day, 12, int(now[-1]) - 1]) else: for day in range(now[-3], 30): days += 1 self.get_earthquakes_for_text( [day, int(now[-2]) - 1, int(now[-1])]) for day in range(1, int(now[-3])): days += 1 self.get_earthquakes_for_text([day, int(now[-2]), int(now[-1])]) map1 = Map() for place in self.places: if place in self.place_damaged: if self.place_damaged[place] - self.place_min_damage[place\ ] > self.place_max_damage[place] - self.place_damaged[place]: self.place_damaged[place] = ( self.place_damaged[place] + self.place_min_damage[place]) / 2 elif place in self.place_damaged: self.place_damaged[place] = ( self.place_damaged[place] + self.place_min_damage[place]) / 2 self.chance[place] = len(self.places[place]) / days if self.chance[place] > 0.1: if self.place_damaged[place] > 0.5: if self.chance[place] * 100 > 100: self.chance[place] = 0.99 to_write = """"With chance {}% there would be earthquake in {} with probable power cl\ ose to {}""".format( str(self.chance[place] * 100)[0:5], place, str(self.place_damaged[place])[0:5]) if self.chance[place] > 0.8: chances = 'darkred' elif self.chance[place] > 0.6: chances = 'red' elif self.chance[place] > 0.4: chances = 'orange' else: chances = 'yellow' a = self.places[place][0].coordinates map1.add_child( Circle(location=[a[1], a[0]], popup=to_write, radius=10000, color=chances, fill=True, fill_color=chances)) map1.save('templates/Map_prediction.html')
file_reader(path) # run function with path df = pd.DataFrame(file_dict) # create a DataFrame from list df.to_excel("locations_collection.xlsx", index=False) # save df as Excel file df.to_csv('locations_collection.csv', index=False) # save df as CSV file my_loc = geocoder.ip('me') # get my location # create basic map locations_map = Map( location=[my_loc.lat, my_loc.lng], height='100', tiles='OpenStreetMap', # loads map from open street maps zoom_start=10) # zoom factor locations_map.add_child( Marker(location=[my_loc.lat, my_loc.lng], tooltip="Mein Standort", icon=folium.Icon(color='blue'))) def map_add_details(data): for i in pd.Series(data): name = i['name'] address = i['address'] description = i['desc'] building_location = i['location'].split(",") year_build = i['year_build'] directory = i['dir'] hyperlink_format = '<a href="{link}">{text}</a>' # format for hyperlinks hyperlink = hyperlink_format.format( link=directory, text='öffnen') # to get individual hyperlinks folium.features.RegularPolygonMarker(
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) add_volcanoes(map) add_cities(map) map.add_child(LayerControl()) map.save('Map1.html')
DataCluster=[DataClusterList] DataPoint=[DataPointList] else: DataCluster.append(DataClusterList) DataPoint.append(DataPointList) data=DataCluster pins=pd.DataFrame(DataPoint) pins.columns = [ 'Latitude','Longitude','Description'] ################################################################ stops_map1 = Map(location=[48.1459806, 11.4985484], zoom_start=5) marker_cluster = FastMarkerCluster(data).add_to(stops_map1) sFileNameHtml=Base+'/02-Krennwallner/06-Report/01-EDS/02-Python/Billboard1.html' stops_map1.save(sFileNameHtml) webbrowser.open('file://' + os.path.realpath(sFileNameHtml)) ################################################################ stops_map2 = Map(location=[48.1459806, 11.4985484], zoom_start=5) for name, row in pins.iloc[:100].iterrows(): Marker([row["Latitude"],row["Longitude"]], popup=row["Description"]).add_to(stops_map2) sFileNameHtml=Base+'/02-Krennwallner/06-Report/01-EDS/02-Python/Billboard2.html' stops_map2.save(sFileNameHtml) webbrowser.open('file://' + os.path.realpath(sFileNameHtml)) ################################################################ stops_heatmap = Map(location=[48.1459806, 11.4985484], zoom_start=5) stops_heatmap.add_child(HeatMap([[row["Latitude"], row["Longitude"]] for name, row in pins.iloc[:100].iterrows()])) sFileNameHtml=Base+'/02-Krennwallner/06-Report/01-EDS/02-Python/Billboard_heatmap.html' stops_heatmap.save(sFileNameHtml) webbrowser.open('file://' + os.path.realpath(sFileNameHtml)) ################################################################ print('### Done!! ############################################') ################################################################