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 createMarkers(map,df,x,y,markers_name,comment_cols,comment_names,color_var,radius,colors,popup =True,indivMarkers = True): feature_group = FeatureGroup(name=markers_name) marker_cluster = MarkerCluster(name = 'Point clusters').add_to(map) for i in comment_cols: if df[i].dtype == object: df[i] = df[i].str.replace("'","'") for index, row in df.iterrows(): if index % 1000 == 0: print(index,' markers added to the map!') x1,y1 = row[x],row[y] # x1_r,y1_r = "{0:.2f}".format(x1),"{0:.2f}".format(y1) popup_text = createPopupText(comment_names) comment_list = [row[i] for i in comment_cols] popup_text = popup_text.format(*comment_list) if "'" in popup_text: popup_text = popup_text.replace("'"," ") color = colors[list(df[color_var].unique()).index(row[color_var])] if popup == True: marker = folium.Circle(location = ([y1,x1]), fill=True,fill_opacity = 1,fill_color = color, color = color,radius = radius,popup = popup_text) folium.Circle(location = ([y1,x1]), fill=True,fill_opacity = 1,fill_color = color, color = color,radius = radius,popup = popup_text).add_to(marker_cluster) elif popup == False: marker = folium.Circle(location = ([y1,x1]), fill=True,fill_opacity = 1,fill_color = color, color = color,radius = radius) folium.Circle(location = ([y1,x1]), fill=True,fill_opacity = 1,fill_color = color, color = color,radius = radius).add_to(marker_cluster) feature_group.add_child(marker) if indivMarkers == True: map.add_child(feature_group)
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 get_population_feature_group() -> FeatureGroup: population_feature_group = FeatureGroup('Population') population_feature_group.add_child( GeoJson( data=open('world.json', mode='r', encoding='utf-8-sig').read(), style_function=lambda x: { 'fillColor': 'green' if x['properties']['POP2005'] < 10000000 else 'orange' if 10000000 <= x['properties']['POP2005'] < 20000000 else 'red' })) return population_feature_group
def map_multiple_outputs_points(directory: str, map_center=None, save_path=None): """ Creates a folium map of single or multiple outputs from the LP model. Circle markers communicate both location of station and forecast demand (diameter). Good for outputs from LP model that outputs points - not hexes. """ station_locations = open_station_locations() if not map_center: m_lat = station_locations[:1]['latitude'] m_long = station_locations[:1]['longitude'] else: m_lat = map_center[0] m_long = map_center[1] m = Map( location=[m_lat, m_long], tiles='cartodbpositron', zoom_start=9 ) colors = ['blue', 'crimson', 'violet', 'orange', 'yellow', 'black'] cnt = 0 for file in os.listdir(directory): open_path_1 = f'data/GIS/LP_outputs/{file}' print(file) name = file.rstrip('.csv') proposed_stations_1 = open_lp_proposed_stations(lp_proposed_stations_path=open_path_1) proposed_stations_1.set_index('id', inplace=True) proposed_stations_1 = join_dfs(station_locations, proposed_stations_1) feature_group = FeatureGroup(name=name) for i, row in proposed_stations_1.iterrows(): if row['demand'] == 0: pass else: c = CircleMarker( radius=row['demand'], location=[row["latitude"], row["longitude"]], tooltip=f"Station ID: {row.name} \n Demand: {row['demand']} kWh", color=colors[cnt], fill=True, fill_color=colors[cnt] ) c.add_to(feature_group) feature_group.add_to(m) cnt += 1 LayerControl('bottomright', collapsed=False).add_to(m) if save_path: m.save(save_path) return m
def draw_refuse_routes_map(self, refuse_routes_file_path: string = 'resource/data/Hav_Refuse_Routes_WGS84' '/Hav_Refuse_Routes_WGS84.json'): geo_map = Map(location=[42.795390191429625, -71.07516023514027], zoom_start=12) data = self.preprocess.get_refuse_routes_data(refuse_routes_file_path) keys_pool = [ 'MONDAY - Red Week', 'TUESDAY - Red Week', 'WEDNESDAY - Red Week', 'THURSDAY - Red Week', 'FRIDAY - Red Week', 'MONDAY - Blue Week', 'TUESDAY - Blue Week', 'WEDNESDAY - Blue Week', 'THURSDAY - Blue Week', 'FRIDAY - Blue Week', 'MERCANTILE - Every Friday' ] for key in keys_pool: feature_group = FeatureGroup(name=key, show=True) if key.endswith('Red Week'): color = 'red' elif key.endswith('Blue Week'): color = 'blue' else: color = 'black' for each in data[key]: geo_json = GeoJson( data=each, style_function=lambda feature, color=color: { 'fillColor': '#A9A9A9', 'color': color, 'weight': 3, }, highlight_function=lambda feature, color=color: { 'fillColor': '#FFBFFF', 'color': color, 'weight': 4, }, tooltip=key, overlay=True ) geo_json.add_to(feature_group) feature_group.add_to(geo_map) LayerControl().add_to(geo_map) cur_time = time.strftime('%m_%d_%Y_%H_%M_%S', time.localtime()) file_name = 'refuse_routes_{}.html'.format(cur_time) geo_map.save(os.path.join(self.refuse_routes_directory_path, file_name))
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 add_volcanoes(map): map = map volcanoes = read_excel('volcanoes.xlsx').iloc[1:, [1, 2, 4, 5, 6]] latitudes, longitudes = volcanoes['Latitude'], volcanoes['Longitude'] name = volcanoes['Volcano Name'] country = volcanoes['Country'] elevation = volcanoes['Elev'] fg_volcanoes = FeatureGroup(name='Volcanoes', show=False) def color_by_elevation(elev): if type(elev) == str: return 'white' if elev <= -4000: return 'darkblue' if elev <= -2000: return 'cadetblue' if elev <= 0: return 'lightblue' if elev <= 2000: return 'orange' if elev <= 4000: return 'red' if elev <= 6000: return 'darkred' else: return 'black' for i in range(len(volcanoes)): i += 1 if isnan(elevation[i]): elevation[i] = 'Unknown' if name[i] == 'Unnamed': html = f'Volcano name:{name[i]}<br>Height: {elevation[i]} m<br> {country[i]}' else: html = f'Volcano name:<b4> <a href="https://www.google.com/search?q={name[i]} volcano" target="_blank">{name[i]}</a><br> \ Height: {elevation[i]} m<br> {country[i]}' iframe = IFrame(html=html, width=200, height=100) coords = (latitudes[i], longitudes[i]) fg_volcanoes.add_child( CircleMarker(location=coords, popup=Popup(iframe), color="gry", fill_color=color_by_elevation(elevation[i]), fill_opacity=0.9, radius=6)) i -= 1 map.add_child(fg_volcanoes)
def 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 get_volcanoes_feature_group() -> FeatureGroup: feature_group = FeatureGroup(name="Volcanoes") data = pandas.read_csv("./Volcanoes_USA.txt") latitudes = list(data['LAT']) longitudes = list(data['LON']) elevation = list(data['ELEV']) for lat, lon, elev in zip(latitudes, longitudes, elevation): feature_group.add_child( CircleMarker(location=(lat, lon), color='grey', weight=1, radius=6, popup=Popup(str(elev) + "m", parse_html=True), fill_color=get_elevation_color(elev))) return feature_group
def from_ip_to_geo(filename): reader = geoip2.database.Reader( 'C://Users//mmmel//Desktop//GeoLite2-City_20201229//GeoLite2-City.mmdb' ) dict_from_csv = from_csv_to_dict(filename) respose = reader.city('82.61.121.164') map = folium.Map( location=[respose.location.latitude, respose.location.longitude], zoom_start=4) inbound_node = FeatureGroup(name="inbound") outbound_node = FeatureGroup(name="outbound") for key, value in dict_from_csv.items(): respose = reader.city(key) pprint(respose.city) pprint(respose.location.latitude) pprint(respose.location.longitude) for i in range(1): if value[i][3] is False: folium.Marker( location=[ respose.location.latitude, respose.location.longitude ], popup=respose.subdivisions.most_specific.name, icon=folium.Icon(color="red")).add_to(outbound_node) else: folium.Marker( location=[ respose.location.latitude, respose.location.longitude ], popup=respose.subdivisions.most_specific.name, icon=folium.Icon(color="blue")).add_to(inbound_node) inbound_node.add_to(map) outbound_node.add_to(map) LayerControl().add_to(map) map.save('C://Users//mmmel//Desktop//index.html') webbrowser.open('C://Users//mmmel//Desktop//index.html')
def add_heatmap_to_map(self, show=False, **kwargs): # add feature group self.fgs['heatmap'] = FeatureGroup('Heatmap', show=show).add_to(self.map) for drive in self.land: obj = drive.get_heatmap(**kwargs) obj.add_to(self.fgs['heatmap'])
def restaurantmap(df_yelp, df_citycoor): latitude = 39.0902 longitude = -95.7129 yelp_map = folium.Map(location=[latitude, longitude], zoom_start=4) for restaurant in [ "McDonald's", 'Starbucks', 'Subway', 'Taco Bell', 'Chick-fil-A', 'Burger King', "Wendy's", "Dunkin'", "Domino's Pizza", 'Panera Bread', 'Pizza Hut', 'Chipotle Mexican Grill', 'Sonic Drive-In', 'KFC', "Applebee's Grill + Bar", 'Olive Garden Italian Restaurant', "Arby's", 'Little Caesars', 'Buffalo Wild Wings', 'Dairy Queen' ]: restaurcnt = df_yelp[df_yelp['name'] == restaurant].groupby( 'city').size().reset_index() restaurcnt.rename(index=str, columns={0: "count"}, inplace=True) colordict = {0: 'lightblue', 1: 'lightgreen', 2: 'orange', 3: 'red'} feature_group = FeatureGroup(name=restaurant, show=False) #find cities in citycoor dataframe and add the latitude and longitude to restaurcnt restaurcnt = pd.merge(restaurcnt, df_citycoor, left_on='city', right_on='City', how='left') for lat, lon, count, city in zip(restaurcnt['latitude'], restaurcnt['longitude'], restaurcnt['count'], restaurcnt['city']): folium.CircleMarker( [lat, lon], radius=.4 * count, popup=('City: ' + str(city).capitalize() + '<br>' 'Count of restaurant: ' + str(count) + '<br>'), color='b', key_on=count, threshold_scale=[0, 1, 2, 3], #fill_color=colordict[], fill=True, fill_opacity=0.7).add_to(feature_group) feature_group.add_to(yelp_map) folium.LayerControl(collapsed=False).add_to(yelp_map) return yelp_map
def mapper_area(df, geo_json_data, a, units): # Initialize the map m = folium.Map() # Scale the size of the circles scale = {0: 4, 1: 10, 2: 16, 3: 24, 4: 32} default_radius = 10 # Add a clickable marker for each facility cm_map = FeatureGroup(name="Facilities") for index, row in df.iterrows(): try: quantile = row["quantile"] folium.CircleMarker( location=[row["FAC_LAT"], row["FAC_LONG"]], popup=row["FAC_NAME"] + ": " + formatter(int(row[a])) + " " + units + "<p><a href='" + row["DFR_URL"] + "' target='_blank'>Link to ECHO detailed report</a></p>", # + "<p><a href='"+row["DFR_URL"]+"' target='_blank'>Link to ECHO detailed report</a></p>", radius=default_radius if (np.isnan(quantile)) else scale[quantile], color="black", weight=1, fill_color="orange" if (int(row[a]) > 0) else "grey", fill_opacity=.4, tooltip=row["FAC_NAME"] + ": " + formatter(int(row[a])) + " " + units + "").add_to(cm_map) except KeyError: breakpoint() #folium.GeoJsonTooltip(fields=["District"]).add_to(gj) cm_map.add_to(m) gj = folium.GeoJson( geo_json_data, name="Congressional District", ) gj.add_to(m) m.keep_in_front(cm_map) bounds = m.get_bounds() m.fit_bounds(bounds) folium.LayerControl().add_to(m) return m
def test_get_obj_in_upper_tree(): m = Map() fg = FeatureGroup().add_to(m) marker = Marker(location=(0, 0)).add_to(fg) assert get_obj_in_upper_tree(marker, FeatureGroup) is fg assert get_obj_in_upper_tree(marker, Map) is m # The search should only go up, not down: with pytest.raises(ValueError): assert get_obj_in_upper_tree(fg, Marker) with pytest.raises(ValueError): assert get_obj_in_upper_tree(marker, Popup)
def plotNodeFeature(G, dfNdAttribs, ndAttrib, myMap, colourmap=None): feature = FeatureGroup(name=ndAttrib.value, show=False) if colourmap == None: minVal = dfNdAttribs[ndAttrib.name].min() maxVal = dfNdAttribs[ndAttrib.name].max() colourmap = cm.linear.Reds_09.scale(minVal, maxVal) colourmap.caption = ndAttrib.value # sorts nodes by value so that nodes with larger values plot later # this ensures that circles with darker colour (larger value) always on top thus more visible. dfNdAttribs = dfNdAttribs.sort_values(by=[ndAttrib.name]) for idx, row in dfNdAttribs.iterrows(): node = row[const.GNodeAttribs.StationId.name] deg = row[ndAttrib.name] coordCrnStn = [ row[const.GNodeAttribs.Lat.name], row[const.GNodeAttribs.Lng.name] ] html = """<html> {ndAttrib} {val} </html><br> StationId {stnid}<br> {ndDesc} """.format( ndAttrib=ndAttrib.value, val=float("{:.3f}".format(deg)), stnid=G.nodes[node][const.GNodeAttribs.StationId.name], ndDesc=G.nodes[node][const.GNodeAttribs.StationDesc.name]) folium.CircleMarker(location=coordCrnStn, radius=5, color=colourmap(deg), weight=2, opacity=0.5, fill_color=colourmap(deg), fill_opacity=.7, tooltip=html).add_to(feature) myMap.add_child(colourmap) feature.add_to(myMap) return myMap
def create_map(result): row = next(result.iterrows())[1] m = Map(location=[row.latitude, row.longitude], zoom_start=13, tiles='Stamen Terrain') feature_group = FeatureGroup(name='Some icons') for index, row in result.iterrows(): x = "not planned" if str(row.openHouse) != "nan": x = datetime.datetime.strptime(row.openHouse, "%Y-%m-%dT%H:%M:%S.000z") x = x.strftime('%b %d %Y %H:%M:%S') Marker(location=[row.latitude, row.longitude], icon=DivIcon( icon_size=(150,36), icon_anchor=(7,20), html = '<strong style="text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000;">'+ '<font size="4" color="'+row['color']+'">'+str(round(row['milprice'],2))+'</>' ), popup=f"<h4>{row.street}</> <br> "+ f"<h4> Size: {str(row['size'])} m<sup>2</sup> </> <br> "+ f"<h4> Rooms: {str(int(row.rooms))} </> <br> "+ f"<h4> Floor: {str(row.floor)}</> <br> "+ f"<h4> Expense: {str(row.expense)}</> <br> "+ f"<h4> Change: -{str(row.priceChangePercentTotal)}% </> <br> "+ f"<a class='btn-floating btn-large waves-effect waves-light red'"+ f"href='add/{row.guid}'>"+ "<i class='material-icons'>add</i></a> <br>"+ f"<h4> Open House: {x} </> <br> "+ f"<a href='{row.url}' target='_blank'>link</a>" )\ .add_to(feature_group) feature_group.add_to(m) LayerControl().add_to(m) m.save(map_file)
def add_activities(self, activities, line_color='purple', show=True): self.fgs['activities'] = FeatureGroup('Hiking/Skiing', show=show).add_to(self.map) # add activities to map for activity in activities: obj = activity.get_line(line_color=line_color, weight=1).add_to(self.fgs['activities']) if activity.is_hiking: obj = activity.get_marker().add_to(self.fgs['activities'])
def add_photos_to_map(self, clustered=True, maxClusterRadius=20, disableClusteringAtZoom=15, zoomToBoundsOnClick=False, spiderfyOnMaxZoom=True, icon_color='#b3334f', groupby=None, **kwargs): # add feature group self.fgs['photos'] = FeatureGroup('Photos', show=True).add_to(self.map) # create photo cluster object if clustered: dst = MarkerCluster( maxClusterRadius=maxClusterRadius, disableClusteringAtZoom=disableClusteringAtZoom, showCoverageOnHover=False, zoomToBoundsOnClick=zoomToBoundsOnClick, spiderfyOnMaxZoom=spiderfyOnMaxZoom, **kwargs).add_to(self.fgs['photos']) else: dst = self.fgs['photos'] # add photos to cluster object for idx, photo in self.photos.iterrows(): xy = photo[self.GPS_INDEX].values.astype(float) if groupby is not None: gallery = photo[groupby] else: gallery = None popup = ImagePopup(photo.imgur_id, caption=photo.caption, aspect=photo.image_aspect, gallery=gallery).popup icon = BeautifyIcon( 'camera', border_width=0, text_color=icon_color, border_color=icon_color, background_color='transparent', inner_icon_style='font-size:20px;padding-top:-1px;') Marker( xy, popup=popup, tooltip=photo.caption, icon=icon, ).add_to(dst)
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 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 add_layer(dataset, layername, mapname, color): """Plots predictions on a Leaflet map Creates a FeatureGroup to hold all of the points. FeatureGroup is added to the map as a layer. Args: dataset: a dataframe with the data to be plotted modelname: name of the model to be used as the layer name mapname: name of the map to be plotted on color: color used for the points in the layer Returns: a layer of points added to the map """ feature_group = FeatureGroup(name=layername) for point in dataset['geometry']: CircleMarker(location=[point.y, point.x], radius=4, color=color, fill_color=color).add_to(feature_group) feature_group.add_to(mapname)
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 test_deep_copy(): m = Map() fg = FeatureGroup().add_to(m) Marker(location=(0, 0)).add_to(fg) m_copy = deep_copy(m) def check(item, item_copy): assert type(item) is type(item_copy) assert item._name == item_copy._name for attr in item.__dict__.keys(): if not attr.startswith('_'): assert getattr(item, attr) == getattr(item_copy, attr) assert item is not item_copy assert item._id != item_copy._id for child, child_copy in zip(item._children.values(), item_copy._children.values()): check(child, child_copy) check(m, m_copy)
def __init__(self, name, color, df): """ Constructs all the necessary attributes for the EWBLayer object. Parameters ---------- name : str name of the layer color : str color of the layer df : dataframe dataframe containing the data of the layer """ self.name = name self.color = color self.df = df self.points = [] self.featureGroup = FeatureGroup(name=name)
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 plotRouteToOverLay(G, dfTimetable, routeDesc): routeLayer = FeatureGroup(name=routeDesc, show=False) for iidx in range(len(dfTimetable.index)): stnOrder = dfTimetable.index[iidx] crnStnCode = dfTimetable.at[stnOrder, const.RoutesTtbCols.StationCode.name] coordCrnStn = [ G.nodes[crnStnCode][const.GNodeAttribs.Lat.name], G.nodes[crnStnCode][const.GNodeAttribs.Lng.name] ] # adds marker to bus stops folium.Marker( location=coordCrnStn, tooltip='StationId %d, %s' % (G.nodes[crnStnCode][const.GNodeAttribs.StationId.name], G.nodes[crnStnCode][const.GNodeAttribs.StationDesc.name]), icon=folium.Icon(prefix='fa', icon='bus')).add_to(routeLayer) if iidx == 0: continue # gets pathPoints between crnStnCode and preStnCode prevStnOrder = dfTimetable.index[iidx - 1] preStnCode = dfTimetable.at[prevStnOrder, const.RoutesTtbCols.StationCode.name] edgeRoutes = G.edges[preStnCode, crnStnCode][const.GEdgeAttribs.routes.name] pathPoints = edgeRoutes[const.GEdgeRouteCols.pathPoints.name][0] # notes that coordinates of each path point are in long,lat order, thus need to convert this to lat,long order points = [(point[1], point[0]) for point in pathPoints] # adds polyline of this route to map folium.PolyLine(points, color='red', weight=3, opacity=.3, popup='route info').add_to(routeLayer) return routeLayer
def draw_heat_map(geo_map: Map, requests: dict): show = True requests_list = sorted(requests.items(), key=lambda item: item[0]) for request_type in requests_list: if show: feature_group = FeatureGroup(name=request_type[0], show=True) show = False else: feature_group = FeatureGroup(name=request_type[0], show=False) mc = MarkerCluster() for request in request_type[1]: # print(request[2]) popup_info = 'Request Type: \n' + request[3] + '\nAddress: ' + request[2] mc.add_child(Marker(location=[request[0], request[1]], popup=popup_info)) mc.add_to(feature_group) feature_group.add_to(geo_map) LayerControl().add_to(geo_map)
def foliumMap(): map_l = folium.Map(location=[55.9486, -3.2008], tiles='Stamen Terrain', zoom_start=14) venues_layer = FeatureGroup(name='Venues') transport_layer = FeatureGroup(name='Transport Hubs') walking_layer = FeatureGroup(name='Walking Tours') districts_layer = FeatureGroup(name='Districts') crowdedness_layer = FeatureGroup(name='Crowdedness Zones') parking_layer = FeatureGroup(name='Street Parking Zones') v = plotVenue() for i in v: folium.Marker( i[3:], popup=folium.Popup('Name: ' + str(i[0]) + '<br>' + 'Show : ' + str(i[1]) + '<br>' + 'Genre: ' + str(i[2]), max_width=450)).add_to(venues_layer) t = plotTransport() for i in t: folium.Marker(i[2:], popup=folium.Popup('Name: ' + str(i[0]) + '<br>' + 'Type: ' + str(i[1]), max_width=450), icon=folium.Icon(color='red')).add_to(transport_layer) w = plotWalkingTours() for i in w: walkingtours = json.load(i[4]) gj = folium.GeoJson(walkingtours, style_function=lambda feature: {'color': 'Red'}) gj.add_child( folium.Popup('Walking Tour: ' + str(i[0]) + '<br>' + 'Show 1: ' + str(i[1]) + '<br>' + 'Show 2: ' + str(i[2]) + '<br>' + 'Show 3: ' + str(i[3]), max_width=450)) gj.add_to(walking_layer) d = plotDistricts() for i in d: districts = json.load(i[1]) gj = folium.GeoJson( districts, style_function=lambda feature: {'fillColor': 'Yellow'}) gj.add_child(folium.Popup(str(i[0]), max_width=450)) gj.add_to(districts_layer) c = plotCrowdedness() for i in c: crowdedness = json.load(i[1]) #folium.GeoJson(crowdedness, style_function=lambda feature: {'fillColor':'Red'}) gj = folium.GeoJson( crowdedness, style_function=lambda feature: {'fillColor': 'Red'}) gj.add_child( folium.Popup('Crowdedness Zone ' + str(i[0]), max_width=450)) gj.add_to(crowdedness_layer) p = plotParkingZone() for i in p: crowdedness = json.load(i[4]) gj = folium.GeoJson( crowdedness, style_function=lambda feature: {'fillColor': 'Green'}) gj.add_child( folium.Popup('Parking Zone: ' + str(i[0]) + '<br>' + 'Start time: ' + str(i[1]) + '<br>' + 'End time: ' + str(i[2]) + '<br>' + 'Disabled only: ' + str(i[3]), max_width=450)) gj.add_to(parking_layer) venues_layer.add_to(map_l) transport_layer.add_to(map_l) walking_layer.add_to(map_l) districts_layer.add_to(map_l) crowdedness_layer.add_to(map_l) parking_layer.add_to(map_l) LayerControl().add_to(map_l) return map_l.get_root().render()
def show_map(coords: list, web_engine_view: QWebEngineView, pop_up: str = None, university=None, kindergarden=None, schools=None, highschools=None, transport=None, charging=None, bicycle=None, groceries=None, services=None, sports=None): icon_size = (45, 45) small_icon = (40, 40) max_width = 400 bytes_io = BytesIO() map_builder = Map(location=coords, tiles="CartoDB positron", zoom_start=16) map_icon = CustomIcon(up(up(__file__)) + "/images/marker.png", icon_size=icon_size) if kindergarden: kindergarden_cluster = MarkerCluster( name='barnehage', show=False).add_to(map_builder) for pois in kindergarden: pois_icon = CustomIcon(up(up(__file__)) + "/images/kindergarden.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(kindergarden_cluster) if schools: schools_cluster = MarkerCluster(name="barneskole", show=False).add_to(map_builder) for pois in schools: pois_icon = CustomIcon(up(up(__file__)) + "/images/schools.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(schools_cluster) if highschools: highschools_cluster = MarkerCluster(name='vidregåendeskole', show=False).add_to(map_builder) for pois in highschools: pois_icon = CustomIcon(up(up(__file__)) + "/images/highschools.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(highschools_cluster) if university: university_cluster = MarkerCluster(name='hogskole_universitet', show=False).add_to(map_builder) for pois in university: pois_icon = CustomIcon(up(up(__file__)) + "/images/university.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(university_cluster) if transport: transport_cluster = MarkerCluster(name='holdeplass', show=False).add_to(map_builder) for pois in transport: pois_icon = CustomIcon(up(up(__file__)) + "/images/transport.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(transport_cluster) if charging: charging_cluster = MarkerCluster(name='ladeplass', show=False).add_to(map_builder) for pois in charging: pois_icon = CustomIcon(up(up(__file__)) + "/images/charging.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(charging_cluster) if bicycle: bicyle_cluster = MarkerCluster(name='bysykler', show=False).add_to(map_builder) for pois in bicycle: pois_icon = CustomIcon(up(up(__file__)) + "/images/bicycle.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(bicyle_cluster) shops_cluster = MarkerCluster(name="butikker", show=False).add_to(map_builder) if groceries: for pois in groceries: pois_icon = CustomIcon(up(up(__file__)) + "/images/groceries.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(shops_cluster) if services: for pois in services: pois_icon = CustomIcon(up(up(__file__)) + "/images/services.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(shops_cluster) if sports: sports_cluster = MarkerCluster(name='sportsaktiviteter', show=False).add_to(map_builder) for pois in sports: pois_icon = CustomIcon(up(up(__file__)) + "/images/sports.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(sports_cluster) if pop_up: Marker(coords, icon=map_icon, popup=Popup(pop_up, max_width=max_width)).add_to(map_builder) else: Marker(coords, icon=map_icon).add_to(map_builder) TileLayer('CartoDB dark_matter').add_to(map_builder) TileLayer('OpenStreetMap').add_to(map_builder) TileLayer( 'https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', attr= '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> ' 'contributors, Tiles style by <a href="https://www.hotosm.org/" ' 'target="_blank">Humanitarian OpenStreetMap Team</a> hosted by ' '<a href="https://openstreetmap.fr/" target="_blank">OpenStreetMap ' 'France</a>', name='openstreetmap_hot').add_to(map_builder) TileLayer('Stamen Toner').add_to(map_builder) TileLayer( 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/' 'tile/{z}/{y}/{x}', attr='Tiles © Esri — Source: Esri, i-cubed, USDA, ' 'USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, ' 'UPR-EGP, and the GIS User Community', name='esri_worldimagery').add_to(map_builder) TileLayer( 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/' 'tile/{z}/{y}/{x}', attr='Tiles © Esri — Source: Esri, DeLorme, ' 'NAVTEQ, USGS, Intermap, iPC, NRCAN, Esri Japan, METI, ' 'Esri China (Hong Kong), Esri (Thailand), TomTom, 2012', name='esri_worldstreetmap').add_to(map_builder) TileLayer( 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/' 'tile/{z}/{y}/{x}', attr='Tiles © Esri — Esri, DeLorme, NAVTEQ, ' 'TomTom, Intermap, iPC, USGS, FAO, NPS, NRCAN, GeoBase, ' 'Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri ' 'China (Hong Kong), and the GIS User Community', name='esri_worldtopomap').add_to(map_builder) TileLayer( 'https://tileserver.memomaps.de/tilegen/{z}/{x}/{y}.png', attr='Map <a href="https://memomaps.de/">memomaps.de</a> ' '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' 'map data © <a href="https://www.openstreetmap.org/copyright">' 'OpenStreetMap</a> contributors', name='openvkarte').add_to(map_builder) TileLayer( 'https://{s}.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png', attr= '<a href="https://github.com/cyclosm/cyclosm-cartocss-style/releases" ' 'title="CyclOSM - Open Bicycle render">CyclOSM</a> | Map data: © ' '<a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> ' 'contributors', name='cyclosm').add_to(map_builder) TileLayer( 'http://tile.mtbmap.cz/mtbmap_tiles/{z}/{x}/{y}.png', attr= '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> ' 'contributors & USGS', name='mtbmap').add_to(map_builder) railway_feature = FeatureGroup('jernbane_tbane', show=False) TileLayer( 'https://{s}.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png', attr= 'Map data: © <a href="https://www.openstreetmap.org/copyright' '">OpenStreetMap</a> contributors | Map style: © <a href=' '"https://www.OpenRailwayMap.org">OpenRailwayMap</a> (<a href=' '"https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)', name='openrailwaymap').add_to(railway_feature) railway_feature.add_to(map_builder) safecast_feature = FeatureGroup('miljø', show=False) TileLayer( 'https://s3.amazonaws.com/te512.safecast.org/{z}/{x}/{y}.png', attr= 'Map data: © <a href="https://www.openstreetmap.org/copyright">' 'OpenStreetMap</a> contributors | Map style: © ' '<a href="https://blog.safecast.org/about/">SafeCast</a> ' '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)', name='safecast').add_to(safecast_feature) safecast_feature.add_to(map_builder) trails_feature = FeatureGroup('turstil', show=False) TileLayer( 'https://tile.waymarkedtrails.org/hiking/{z}/{x}/{y}.png', attr= 'Map data: © <a href="https://www.openstreetmap.org/copyright">' 'OpenStreetMap</a> contributors | Map style: © ' '<a href="https://waymarkedtrails.org">waymarkedtrails.org</a> ' '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)', name='waymarkedtrails_hiking').add_to(trails_feature) trails_feature.add_to(map_builder) cycling_feature = FeatureGroup('sykkelsti', show=False) TileLayer( 'https://tile.waymarkedtrails.org/cycling/{z}/{x}/{y}.png', attr= 'Map data: © <a href="https://www.openstreetmap.org/copyright">' 'OpenStreetMap</a> contributors | Map style: © ' '<a href="https://waymarkedtrails.org">waymarkedtrails.org</a> ' '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)', name='waymarkedtrails_cycling').add_to(cycling_feature) cycling_feature.add_to(map_builder) slopes_feature = FeatureGroup('bakker_helning', show=False) TileLayer( 'https://tile.waymarkedtrails.org/slopes/{z}/{x}/{y}.png', attr= 'Map data: © <a href="https://www.openstreetmap.org/copyright">' 'OpenStreetMap</a> contributors | Map style: © ' '<a href="https://waymarkedtrails.org">waymarkedtrails.org</a> ' '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)', name='waymarkedtrails_slopes').add_to(slopes_feature) slopes_feature.add_to(map_builder) LayerControl().add_to(map_builder) map_builder.save(bytes_io, close_file=False) web_engine_view.setHtml(bytes_io.getvalue().decode()) web_engine_view.show()