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 plotRoutesWithLayers(G, dfRoutes, myMap, mapfile): for index, route in dfRoutes.iterrows(): designedTtb = route[const.RoutesCols.designedTtb.name] tupleList = list( zip(designedTtb[const.RoutesTtbCols.StationOrder.name], designedTtb[const.RoutesTtbCols.StationCode.name])) dfDesignedTtb = pd.DataFrame(tupleList, columns=[ const.RoutesTtbCols.StationOrder.name, const.RoutesTtbCols.StationCode.name ]) dfDesignedTtb = dfDesignedTtb.set_index( const.RoutesTtbCols.StationOrder.name) dfDesignedTtb.sort_index() plotRouteToBase(G, dfDesignedTtb, myMap) routeDesc = 'route %s, direction %s' % ( route[const.RoutesCols.RouteNo.name], route[const.RoutesCols.StationDirection.name]) routeLayer = plotRouteToOverLay(G, dfDesignedTtb, routeDesc) routeLayer.add_to(myMap) folium.GeoJson('%s/hcmc.geojson' % const.dataFolder, control=False, show=True, name='HCMC').add_to(myMap) LayerControl().add_to(myMap) myMap.save(mapfile)
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 plotClosenessCentralities(G, myMap, mapfile): nodeCentrals = [[ node, G.nodes[node][const.GNodeAttribs.Lat.name], G.nodes[node][const.GNodeAttribs.Lng.name], G.nodes[node][const.GNodeAttribs.ccHops.name], G.nodes[node][const.GNodeAttribs.ccDist.name], G.nodes[node][const.GNodeAttribs.ccTime.name] ] for node in G.nodes()] dfNdCentrals = pd.DataFrame( nodeCentrals, columns=[ const.GNodeAttribs.StationId.name, const.GNodeAttribs.Lat.name, const.GNodeAttribs.Lng.name, const.GNodeAttribs.ccHops.name, const.GNodeAttribs.ccDist.name, const.GNodeAttribs.ccTime.name ]) folium.GeoJson('%s/hcmc.geojson' % const.dataFolder, control=False, show=True, name='HCMC').add_to(myMap) ndAttrib = const.GNodeAttribs.ccHops myMap = plotNodeFeature(G, dfNdCentrals, ndAttrib, myMap) ndAttrib = const.GNodeAttribs.ccDist myMap = plotNodeFeature(G, dfNdCentrals, ndAttrib, myMap) ndAttrib = const.GNodeAttribs.ccTime myMap = plotNodeFeature(G, dfNdCentrals, ndAttrib, myMap) LayerControl().add_to(myMap) myMap.save(mapfile)
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 main(): """ None -> None The main fuction that starts all module """ year = greeting() # Change location for your preferences dct = file_pars('data/locations.csv', year) population('data/world.json') counter = 0 global fg_list fg_list = [] for location in dct: title_str = "" for title in dct[location]: title_str += title try: latitude, longitude = lct_to_crd(location) html_crtr(latitude, longitude, title_str) counter += 1 print("one more") except Exception: print("Error 429") print("Finish", counter) # Adding to the html map movie layer fg_m.add_to(html_map) # Adding to the html map population layer fg_pp.add_to(html_map) # Saving map LayerControl().add_to(html_map) html_map.save('Map_movie.html')
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 save_map(date): valencia = [39.4561165311493, -0.3545661635] mapa = Map(location=valencia, tiles='OpenStreetMap', zoom_start=10) GeoJson(open('voronoi.json'), name='Diagrama de Voronoi').add_to(mapa) GeoJson(open('estaciones_de_recarga_' + date + '.json'), name='Estaciones de Recarga').add_to(mapa) LayerControl().add_to(mapa) mapa.save('valencia_' + date + '.html')
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 makeSingleFDOutlineMap(output_dir, bg_filepath, fd_filepath, geojson_key, map_filename, data, column, bg_info_col_name, casual_name, color="YlOrRd"): """ Creates choloropleth map of single value with toggleable fire district outlines. Inputs: """ # Change block group to string type for mapping data['Block_Group'] = data['Block_Group'].astype(str) data['Block_Group'] = data['Block_Group'].str[:12] fmap = folium.Map(location=[29.72, -95.60], tiles='cartodbpositron', zoom_start=10) folium.Choropleth(geo_data=bg_filepath, data=data, columns=['Block_Group', column], key_on=geojson_key, name=casual_name+" Map", fill_color=color, fill_opacity=1, line_opacity=0.2, nan_fill_color='White', legend_name=bg_info_col_name).add_to(fmap) style_function = lambda x: {'fillColor': '#ffffff', 'color':'black', 'fillOpacity': 0.1, 'weight': 2} highlight_function = lambda x: {'fillColor': '#000000', 'color':'#000000', 'fillOpacity': 0.30, 'weight': 2} # Create data frame of admin dist to polygon fd_geo_df = gpd.read_file(fd_filepath, driver='GeoJSON') fd_geo_df = fd_geo_df[['Fire_Districts.AdminDist', 'geometry']] # Add block group and fire district outlines folium.GeoJson( fd_geo_df, show=False, style_function = style_function, highlight_function = highlight_function, tooltip=folium.GeoJsonTooltip( fields=['Fire_Districts.AdminDist'], aliases=['District Number'], localize=True ), name='Fire District').add_to(fmap) bg_geo_df = make_bg_geo_data(bg_filepath, data) folium.GeoJson( bg_geo_df, highlight_function=highlight_function, style_function = lambda x: { 'color': 'gray', 'weight': 1, 'fillOpacity': 0 }, tooltip=folium.GeoJsonTooltip( fields=['Block_Group', column], aliases=['Block Group', bg_info_col_name], localize=True ), name='Block Group Information').add_to(fmap) LayerControl(collapsed=False).add_to(fmap) fmap.save(output_dir+"/"+map_filename+".html")
def makeInteractiveMap(output_dir, data, bg_filepath, fd_filepath): fmap = folium.Map(location=[29.72, -95.60], name="Map", tiles='cartodbpositron', zoom_start=10, control=False, overlay=False) for column in columns: data[column] = data[column].round().astype(int) folium_del_legend(folium.Choropleth(geo_data=bg_filepath, overlay=False, show = False, name=column, data=data, threshold_scale = [0, 5, 10, 20, 30, 40, 50, 60, 80, 101], columns=['Block_Group', column], key_on='feature.properties.Name', fill_color='YlOrRd', fill_opacity=1, line_opacity=0.2, nan_fill_color='White', legend_name=column)).add_to(fmap) # Adds a legend - doesn't change existing values though colormap = branca.colormap.linear.YlOrRd_09.scale(0, 90) colormap.caption = 'Proportion out of Total Calls' colormap.add_to(fmap) # Add block group outline with open(bg_filepath) as f: bg = json.load(f) folium.GeoJson( bg, style_function = lambda x: { 'color': 'gray', 'weight': 1, 'fillOpacity': 0 }, name='Block Group Boundaries').add_to(fmap) style_function = lambda x: {'fillColor': '#ffffff', 'color':'black', 'fillOpacity': 0.1, 'weight': 2} highlight_function = lambda x: {'fillColor': '#000000', 'color':'#000000', 'fillOpacity': 0.30, 'weight': 2} # Create data frame of admin dist to polygon fd_geo_df = gpd.read_file(fd_filepath, driver='GeoJSON') fd_geo_df = fd_geo_df[['Fire_Districts.AdminDist', 'geometry']] # Add block group and fire district outlines folium.GeoJson( fd_geo_df, show=False, style_function = style_function, highlight_function = highlight_function, tooltip=folium.GeoJsonTooltip( fields=['Fire_Districts.AdminDist'], aliases=['District Number'], localize=True ), name='Fire District').add_to(fmap) LayerControl(collapsed=False).add_to(fmap) fmap.save(output_dir+"/interactive-map.html")
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 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 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 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 plotBetweennessCentralities(G, dfStopAttribs, ndAttrib, myMap, mapfile): folium.GeoJson('%s/hcmc.geojson' % const.dataFolder, control=False, show=True, name='HCMC', style_function=lambda x: { 'fillColor': '#00000000', 'lineColor': '#00000000' }).add_to(myMap) #ndAttrib = const.GNodeAttribs.cbHops myMap = plotNodeFeature(G, dfStopAttribs, ndAttrib, myMap) LayerControl().add_to(myMap) myMap.save(mapfile)
class AverageMap: #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 (1999-2016)').add_to(m) for i in range(0, len(marker_coord)): popup = folium.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)
def plotNodeStrengths(G, myMap, mapfile): nodeStrengths = [[ node, G.nodes[node][const.GNodeAttribs.Lat.name], G.nodes[node][const.GNodeAttribs.Lng.name], G.nodes[node][const.GNodeAttribs.totDeg.name], G.nodes[node][const.GNodeAttribs.nLines.name], G.nodes[node][const.GNodeAttribs.nServices.name] ] for node in G.nodes()] dfNdAttribs = pd.DataFrame( nodeStrengths, columns=[ const.GNodeAttribs.StationId.name, const.GNodeAttribs.Lat.name, const.GNodeAttribs.Lng.name, const.GNodeAttribs.totDeg.name, const.GNodeAttribs.nLines.name, const.GNodeAttribs.nServices.name ]) folium.GeoJson('%s/hcmc.geojson' % const.dataFolder, control=False, show=True, name='HCMC').add_to(myMap) ndAttrib = const.GNodeAttribs.totDeg myMap = plotNodeFeature(G, dfNdAttribs, ndAttrib, myMap) ndAttrib = const.GNodeAttribs.nLines myMap = plotNodeFeature(G, dfNdAttribs, ndAttrib, myMap) ndAttrib = const.GNodeAttribs.nServices myMap = plotNodeFeature(G, dfNdAttribs, ndAttrib, myMap) ''' for index, route in dfRoutes.iterrows(): designedTtb = route[const.RoutesCols.designedTtb.name] tupleList = list(zip(designedTtb[const.RoutesTtbCols.StationOrder.name], designedTtb[const.RoutesTtbCols.StationCode.name])) dfDesignedTtb = pd.DataFrame(tupleList, columns=[const.RoutesTtbCols.StationOrder.name, const.RoutesTtbCols.StationCode.name]) dfDesignedTtb = dfDesignedTtb.set_index(const.RoutesTtbCols.StationOrder.name) dfDesignedTtb.sort_index() plotRoutesToLayer(G, dfDesignedTtb, netLayer) ''' LayerControl().add_to(myMap) myMap.save(mapfile)
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 plotBetweennessCentralities_v2(G, dfBetwCentrals, bcList, minVal, maxVal, myMap, mapfile): folium.GeoJson( '%s/hcmc.geojson' % const.dataFolder, control=False, show=True, name='HCMC', #style_function=lambda x: {'fillColor': '#00000000', 'lineColor': '#00000000'} ).add_to(myMap) colourmap = cm.linear.Reds_09.scale(minVal, maxVal) colourmap.caption = 'Fraction of stop pairs' for bcAttrib in bcList: myMap = plotNodeFeature(G, dfBetwCentrals, bcAttrib, myMap, colourmap) LayerControl().add_to(myMap) myMap.save(mapfile)
def plotTopRoutes(G, dfRoutes, myMap, dfTopRoutes_0710, dfTopRoutes_1215, dfTopRoutes_1720, mapfile): for index, route in dfRoutes.iterrows(): designedTtb = route[const.RoutesCols.designedTtb.name] tupleList = list( zip(designedTtb[const.RoutesTtbCols.StationOrder.name], designedTtb[const.RoutesTtbCols.StationCode.name])) dfDesignedTtb = pd.DataFrame(tupleList, columns=[ const.RoutesTtbCols.StationOrder.name, const.RoutesTtbCols.StationCode.name ]) dfDesignedTtb = dfDesignedTtb.set_index( const.RoutesTtbCols.StationOrder.name) dfDesignedTtb.sort_index() plotRouteToBase(G, dfDesignedTtb, myMap) minVal = min(dfTopRoutes_0710['nPairs'].min(), dfTopRoutes_1215['nPairs'].min(), dfTopRoutes_1720['nPairs'].min()) maxVal = max(dfTopRoutes_0710['nPairs'].max(), dfTopRoutes_1215['nPairs'].max(), dfTopRoutes_1720['nPairs'].max()) colourmap = cm.linear.Reds_09.scale(minVal, maxVal) routeLayer = plotSelectedRoutesToOverLay(G, dfRoutes, dfTopRoutes_0710, 'departure time 0700', colourmap) routeLayer.add_to(myMap) routeLayer = plotSelectedRoutesToOverLay(G, dfRoutes, dfTopRoutes_1215, 'departure time 1200', colourmap) routeLayer.add_to(myMap) routeLayer = plotSelectedRoutesToOverLay(G, dfRoutes, dfTopRoutes_1720, 'departure time 1700', colourmap) routeLayer.add_to(myMap) folium.GeoJson('%s/hcmc.geojson' % const.dataFolder, control=False, show=True, name='HCMC').add_to(myMap) LayerControl().add_to(myMap) myMap.save(mapfile)
def main(): # tokyo_geo = '../tokyoGeoJson/tokyo.json' tokyo_geo = '../JapanCityGeoJson/geojson/13/tokyo23.json' tokyo_data = pd.read_csv(addedcode_tokyo_cases) tokyo_data['Municipality_code'] = tokyo_data['Municipality_code'].astype(str) tokyo_data['Num_cases'] = tokyo_data['Num_cases'].astype(int) # print(tokyo_data[['Municipality_code', 'Num_cases']]) # m = folium.Map(location=[48, -102], zoom_start=3) # 東京都港区芝公園を設定 tokyo23_location = [35.658593, 139.745441] # m = folium.Map(location=tokyo23_location, # tiles='https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}.png', # attr='OpenStreetMap', # zoom_start=11) m = Map(location=tokyo23_location, tiles='cartodbpositron', attr='OpenStreetMap', zoom_start=11) choropleth = Choropleth( geo_data=tokyo_geo, data=tokyo_data, columns=['Municipality_code', 'Num_cases'], # key_on='feature.properties.code', key_on='feature.id', name='choropleth', fill_opacity=0.7, line_opacity=0.2, # line_color='red', fill_color='OrRd', # bins=[0, 100, 200, 300, 400, 500] # nan_fill_color="blue" ).add_to(m) print(type(choropleth.geojson)) print(type(choropleth.color_scale)) # 地図をhtml形式で出力 LayerControl().add_to(m) m.save(outfile="choropleth_map.html")
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 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 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 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()
def show(self, map): if self.layered == False: LayerControl(collapsed=False).add_to(map) self.layered = True map.save('nycLayeringEssential.html') return os.path.abspath('nycLayeringEssential.html')
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')
show=False).add_to(map) townHallVoronoi = voronoiFeatureCollection(townHalls, mask=dresdenBorder) geoFeatureCollectionToFoliumFeatureGroup(townHallVoronoi, 'Olive ', "cityhall voronoi", show=False).add_to(map) doctorsVoronoi = voronoiFeatureCollection(healthGroups["doctors"], mask=dresdenBorder) pharmacyVoronoi = voronoiFeatureCollection(healthGroups["pharmacies"], mask=dresdenBorder) geoFeatureCollectionToFoliumFeatureGroup(doctorsVoronoi, 'IndianRed ', "doctors voronoi", show=False).add_to(map) geoFeatureCollectionToFoliumFeatureGroup(pharmacyVoronoi, 'Crimson', "pharmacy voronoi", show=False).add_to(map) else: logging.info("skipped voronoi diagram generation") LayerControl().add_to(map) fileName = "out/maps/patternMap_Pieschen.html" logging.info("Starting to save map in {} (this might take a while)".format( fileName)) map.save(fileName) logging.info("Map saved in {}".format(fileName))