def map_stats(request, type): maps = folium.Map(**MAPS_CONFIG) if type == 'claims': data = dict( Claim.objects.values_list('zone').order_by('zone').annotate( count=Count('id'))) claims, world = get_claims() for player, zones in sorted(claims.items(), key=lambda e: str(e[0])): extra = dict(line_color='#ffffff', line_weight=2) if player == request.user else {} choropleth = get_choropleth(player, zones, data, color='white', fill_color='YlOrRd', fill_opacity=0.50, line_opacity=1.00, nan_fill_opacity=0.00, nan_fill_color='grey', **extra) popup = folium.GeoJsonPopup(fields=("name", "province", "region", "claims", "url"), aliases=("Nom", "Province", "Région", "Prétendants", "Action")) popup.add_to(choropleth.geojson) choropleth.add_to(maps) elif type in ('troops', 'forts', 'taxes', 'prods'): data = dict(Territory.objects.values_list('zone', type)) territories, world = get_territories(request.user) for player, zones in sorted(territories.items(), key=lambda e: str(e[0])): extra = dict(line_color='#ffffff', line_weight=2) if player == request.user else {} choropleth = get_choropleth(player, zones, data, fill_color='RdYlGn', fill_opacity=0.50, line_opacity=1.00, nan_fill_opacity=0.00, nan_fill_color='grey', **extra) popup = folium.GeoJsonPopup( fields=("image", "name", "province", "region", "owner", "troops", "forts", "taxes", "prods", "url"), aliases=("", "Nom", "Province", "Région", "Propriétaire", "Troupes", "Forts", "Taxes", "Casernes", "Action")) popup.add_to(choropleth.geojson) choropleth.add_to(maps) folium.LayerControl().add_to(maps) maps = maps.get_root() maps.render() return {'maps': maps}
def map_forces(request): territories, world = get_territories(request.user) maps = folium.Map(**MAPS_CONFIG) for player, zones in sorted(territories.items(), key=lambda e: str(e[0])): style = lambda x, player=player: { "fillColor": (player.color or "white") if player else "transparent", "color": (player.color or "lightgrey") if player else "white", "weight": 1.00, "opacity": 0.25 } popup = folium.GeoJsonPopup( fields=("image", "name", "province", "region", "owner", "troops", "forts", "taxes", "prods", "url"), aliases=("", "Nom", "Province", "Région", "Propriétaire", "Troupes", "Forts", "Taxes", "Casernes", "Action")) tooltip = escape(str(player)) if player else None if player and player.image: tooltip = ( f'<img src="{player.image.url}" style="max-width: 50px; max-height: 25px; ' f'margin-right: 5px;"><span class="align-middle">{tooltip}</span>' ) folium.GeoJson( zones, tooltip=tooltip, style_function=style, popup=popup, name=escape(str(player)) if player else "Indépendant", show='stats' not in request.GET, ).add_to(maps) folium.LayerControl().add_to(maps) maps = maps.get_root() maps.render() return {'maps': maps}
def map_claims(request): claims, world = get_claims() maps = folium.Map(**MAPS_CONFIG) for player, zones in sorted(claims.items(), key=lambda e: str(e[0])): style = lambda x, player=player: { "fillColor": (player.color or "white") if player else "transparent", "color": (player.color or "lightgrey") if player else "white", "weight": 1.00, "opacity": 0.25 } popup = folium.GeoJsonPopup(fields=("name", "province", "region", "claims", "url"), aliases=("Nom", "Province", "Région", "Prétendants", "Action")) folium.GeoJson( zones, tooltip=escape(str(player)) if player else None, style_function=style, popup=popup, name=escape(str(player or "Non revendiqués")), show='stats' not in request.GET, ).add_to(maps) folium.LayerControl().add_to(maps) maps = maps.get_root() maps.render() return {'maps': maps}
def _add_outlier_points(self): """ Adds outliers marked with a trash icon. """ # Iterate over GeoJSON files. for idx in range(len(self.json_files)): # Skip if there are no outliers. if all(self.data[idx][self.data[idx]['type'] == 'occurrence'].outlier == "false"): pass # Make a layer for outliers. layer_outliers = folium.FeatureGroup( name=f"{self.names[idx]} outliers") # Get outliers as markers. mask1 = self.data[idx]['type'] == "occurrence" mask2 = self.data[idx]['outlier'] == 'true' markers = folium.GeoJson( data=self.data[idx][mask1 & mask2], popup=folium.GeoJsonPopup(fields=("record", ), aliases=("", )), marker=folium.Marker( icon=folium.Icon(color=COLORS[idx], icon="trash"))) # Add outliers to layer. layer_outliers.add_child(markers) # Add layer to map. self.imap.add_child(layer_outliers)
def _add_points(self): """ Adds markers for occurrence points on a separate layer. """ # Iterate over GeoJSON files. for idx in range(len(self.json_files)): # Make a layer for points. layer_points = folium.FeatureGroup( name=f"{self.names[idx]} occurrences") # Get points as markers. mask1 = self.data[idx]['type'] == "occurrence" mask2 = self.data[idx]['outlier'] == 'false' markers = folium.GeoJson( data=self.data[idx][mask1 & mask2], popup=folium.GeoJsonPopup(fields=("record", ), aliases=("", )), marker=folium.Marker(icon=folium.Icon(color=COLORS[idx]))) # Add markers to layer. layer_points.add_child(markers) # Add this layer to the map. self.imap.add_child(layer_points)
def _tooltip_popup(type, fields, gdf, **kwds): """get tooltip or popup""" import folium # specify fields to show in the tooltip if fields is False or fields is None or fields == 0: return None else: if fields is True: fields = gdf.columns.drop(gdf.geometry.name).to_list() elif isinstance(fields, int): fields = gdf.columns.drop(gdf.geometry.name).to_list()[:fields] elif isinstance(fields, str): fields = [fields] for field in ["__plottable_column", "__folium_color"]: if field in fields: fields.remove(field) # Cast fields to str fields = list(map(str, fields)) if type == "tooltip": return folium.GeoJsonTooltip(fields, **kwds) elif type == "popup": return folium.GeoJsonPopup(fields, **kwds)
def plot_popup(m, fields, aliases): folium.features.GeoJson(aurin_data, name='Tweet Statistics Popup', popup=folium.GeoJsonPopup(fields=fields, aliases=aliases), style_function=lambda style: { 'fillColor': '#00000000', 'color': '#00000000' }).add_to(m)
def draw_map(connection): # https://georgetsilva.github.io/posts/mapping-points-with-folium/ # https://geoffboeing.com/2015/10/exporting-python-data-geojson/ # https: // stackoverflow.com / questions / 60585689 / how - to - display - information - in -geojson - popup - python # https://stackoverflow.com/questions/50998176/6-millions-of-markers-in-folium-leaflet-map start_time = time.time() df = mapper.retrieve_points(connection) cols = df.columns raw_json = mapper.df_to_geojson(df, cols) locations = df[['latitude', 'longitude']] location_list = locations.values.tolist() print(df.head()) with open('searchdata.json', 'w') as fp: json.dump(raw_json, fp) print("--- %s seconds ---" % (time.time() - start_time)) print('Drawing Map...') start_time = time.time() m = folium.Map(location=[54.968220, -1.868530], zoom_start=7, prefer_canvas=True) # lat/long with open('searchdata.json') as access_json: read_content = json.load(access_json) geojson_obj = folium.GeoJson( 'searchdata.json', popup=folium.GeoJsonPopup(fields=cols.tolist())).add_to(m) Search(layer=geojson_obj, search_zoom=12, search_label='name', collapsed=False).add_to(m) folium.LayerControl().add_to(m) folium.plugins.LocateControl().add_to(m) m.save('map.html') # mapper.minify() print("--- %s seconds ---" % (time.time() - start_time)) print('\nOpen \'map.html\' in a browser to view generated map')
for city in data: latin_city = get_city_name(city) data_to_append[latin_city] = data[city] read_file.seek(0) for i in js['features']: city = i['properties']['name'] if city in data_to_append: i['properties'].update({'infected': data_to_append[city]}) else: i['properties'].update({'infected': 0}) json.dump(js, read_file) read_file.truncate() ua_map = fl.Map(location=[48.6992149, 31.2844733], zoom_start=7) fg = fl.FeatureGroup(name='Ukraine COVID-19 map') infected_max = max([int(x) for x in data.values()]) infected_min = min([int(x) for x in data.values()]) colormap = cm.linear.Reds_09.scale(infected_min, infected_max) fg.add_child(fl.GeoJson(data=open('UA.geojson', 'r').read(), popup=fl.GeoJsonPopup(fields=['name', 'infected'], aliases=['Region', 'Infected']), style_function=lambda x: {'fillColor': colormap(int(x['properties']['infected'])), 'fillOpacity': 0.7}, highlight_function=lambda x: {'stroke': True, 'color': 'Blue', 'opacity': 0.2, 'fillOpacity': 1})) ua_map.add_child(fg) ua_map.add_child(fl.LayerControl()) ua_map.save('index.html')
def generate_map(map_json, data): # Create a white image of 4 pixels, and embed it in a url. # white_tile = branca.utilities.image_to_url([[1, 1], [1, 1]]) m = folium.Map( [23.53, 78.3], maxZoom=7, minZoom=4, zoom_control=True, zoom_start=5, scrollWheelZoom=True, maxBounds=[[40, 68],[6, 97]], # tiles=white_tile, # attr='white tile', dragging=True ) popup = folium.GeoJsonPopup( fields=['st_nm'], aliases=['State'], localize=True, labels=True, style=''' background-color: white; border-radius: 3px; ''', ) g = folium.Choropleth( geo_data=map_json, data=data, columns=['st_nm', 'state_total'], # from dataframe `data` key_on='properties.st_nm', fill_color='Set3', fill_opacity=0.7, line_opacity=0.4, legend_name='FRT Systems', highlight=True, ).add_to(m) # hide legend - HACK for key in m._children: if key.startswith('color_map'): del(m._children[key]) for i in range(len(map_json['features'])): gs = folium.GeoJson( map_json['features'][i], style_function=lambda feature: { 'fillColor': '#ffff00', 'color': 'black', 'weight': 0.1, 'dashArray': '5, 5' } ) state = map_json['features'][i]['properties']['st_nm'] frt_count = data[data['state'] == state]['state_total'].iloc[0] popup_html = ''' <h3>{}</h3>\ <label>Total FRTs: </label><span>{}</span> '''.format(state, frt_count) popup = folium.IFrame(popup_html, width=200, height=120) folium.Popup(popup, max_width=200, parse_html=True).add_to(gs) gs.add_to(g) return m._repr_html_()
def create_covid_viz(): ''' Load and pre-process the geojson file ''' world_geojson = gpd.read_file(geojson_path) world_geojson.drop(columns=['ISO_A2'], inplace=True) ''' Load and pre-process the COVID-19 data ''' # Load the COVID-19 data df_covid = pd.read_csv( os.path.join(data_dir_path, 'covid_' + newest_dataset)) timestamp = df_covid['Last_Update'][0] # Replace some country names df_covid.replace(to_replace={'Country_Region': 'US'}, value='United States of America', inplace=True) df_covid.replace(to_replace={'Country_Region': 'Bahamas'}, value='The Bahamas', inplace=True) df_covid.replace(to_replace={'Country_Region': 'Congo (Brazzaville)'}, value='Republic of Congo', inplace=True) df_covid.replace(to_replace={'Country_Region': 'Congo (Kinshasa)'}, value='Democratic Republic of the Congo', inplace=True) df_covid.replace(to_replace={'Country_Region': 'Taiwan*'}, value='Taiwan', inplace=True) df_covid.replace(to_replace={'Country_Region': "Cote d'Ivoire"}, value='Ivory Coast', inplace=True) df_covid.replace(to_replace={'Country_Region': "Czechia"}, value='Czech Republic', inplace=True) world_geojson.replace(to_replace={'ADMIN': 'Macedonia'}, value='North Macedonia', inplace=True) # Change the name of 'ADMIN' column in the geojson DF to match the one in COVID DF world_geojson.rename(columns={'ADMIN': 'Country_Region'}, inplace=True) # Aggregate the data for countries that have regional information df_covid_agg = df_covid.groupby('Country_Region').agg({ 'Confirmed': 'sum', 'Deaths': 'sum', 'Recovered': 'sum', 'Active': 'sum', 'Incident_Rate': 'mean', 'Case_Fatality_Ratio': 'mean' }) world_geojson = world_geojson.sort_values('Country_Region').reset_index( drop=True) # Join the geojson with the DataFrame df_covid_joined = df_covid_agg.merge(world_geojson, how='right', on='Country_Region') # Count min and max values for specific columns min_dict, max_dict = {}, {} column_names = [ 'Confirmed', 'Deaths', 'Active', 'Incident_Rate', 'Case_Fatality_Ratio' ] for name in column_names: min_dict[name] = min(df_covid_joined[name]) max_dict[name] = max(df_covid_joined[name]) # Replace NaNs in the DataFrame with '-1' df_covid_joined.fillna(-1, inplace=True) # Add the data columns to geo json for future popup displaying world_geojson = world_geojson.assign( Confirmed=df_covid_joined['Confirmed'], Deaths=df_covid_joined['Deaths'], Active=df_covid_joined['Active'], Incident_Rate=df_covid_joined['Incident_Rate'], Case_Fatality_Ratio=df_covid_joined['Case_Fatality_Ratio']) print(world_geojson) # Set the correct index columns df_covid_joined.set_index('Country_Region', inplace=True) # Create a lists of evenly spaced attribute values over computed min-max intervals and assign corresponding colors to the DataFrame colormap_dict = {} bins = [] for name in column_names: # Work-around for geometric space not accepting zeros in the sequence tmp_min = min_dict[name] if min_dict[name] < 1: min_dict[name] = 1 inner_bins = np.geomspace(start=min_dict[name], stop=max_dict[name], num=10) min_dict[name] = tmp_min inner_bins = np.delete(inner_bins, 0) inner_bins = np.insert(inner_bins, 0, min_dict[name]) inner_bins = np.insert(inner_bins, 0, -1.) inner_bins = inner_bins.tolist() # Round the inner_bins values before appending to the bins list if name in ['Confirmed', 'Deaths', 'Active']: inner_bins = [int(round(bin, 0)) for bin in inner_bins] else: inner_bins = [round(bin, 2) for bin in inner_bins] bins.append(inner_bins) colormap_dict[name] = cm.StepColormap(colors=color_dict[name], index=inner_bins, vmin=min_dict[name], vmax=max_dict[name]) df_covid_joined[name + '_color'] = df_covid_joined[name].map( lambda x: colormap_dict[name].rgb_hex_str(x)) ''' Initialize the map ''' map_covid = folium.Map(location=[0, 0], zoom_start=4, max_bounds=True, tiles=None) base_map = folium.FeatureGroup(name='Basemap', overlay=True, control=False) folium.TileLayer(min_zoom=3, tiles='OpenStreetMap').add_to(base_map) base_map.add_to(map_covid) ''' Create the content of the map ''' # Create FeatureGroups to group the data feature_groups = [] for category, _ in color_dict.items(): group = folium.FeatureGroup(category, overlay=False) feature_groups.append(group) # Create the choropleths choropleth_confirmed = folium.GeoJson( data=world_geojson, zoom_on_click=False, name='Confirmed Cases', style_function=lambda x: { 'fillColor': df_covid_joined['Confirmed_color'][x['properties']['Country_Region' ]], 'fillOpacity': 0.7, 'color': 'black', 'weight': 0.5 }).add_to(feature_groups[0]) popup_confirmed = folium.GeoJsonPopup( fields=['Country_Region', 'Confirmed'], labels=False) popup_confirmed.add_to(choropleth_confirmed) choropleth_deaths = folium.GeoJson( data=world_geojson, name='Deaths', style_function=lambda x: { 'fillColor': df_covid_joined['Deaths_color'][x['properties']['Country_Region']], 'fillOpacity': 0.7, 'color': 'black', 'weight': 1 }).add_to(feature_groups[1]) popup_deaths = folium.GeoJsonPopup(fields=['Country_Region', 'Deaths'], labels=False) popup_deaths.add_to(choropleth_deaths) choropleth_active = folium.GeoJson( data=world_geojson, name='Active Cases', style_function=lambda x: { 'fillColor': df_covid_joined['Active_color'][x['properties']['Country_Region']], 'fillOpacity': 0.7, 'color': 'black', 'weight': 1 }).add_to(feature_groups[2]) popup_active = folium.GeoJsonPopup(fields=['Country_Region', 'Active'], labels=False) popup_active.add_to(choropleth_active) choropleth_incident_rate = folium.GeoJson( data=world_geojson, name='Incident Rate', style_function=lambda x: { 'fillColor': df_covid_joined['Incident_Rate_color'][x['properties'][ 'Country_Region']], 'fillOpacity': 0.7, 'color': 'black', 'weight': 1 }).add_to(feature_groups[3]) popup_incident_rate = folium.GeoJsonPopup( fields=['Country_Region', 'Incident_Rate'], labels=False) popup_incident_rate.add_to(choropleth_incident_rate) choropleth_case_fatality_ratio = folium.GeoJson( data=world_geojson, name='Case Fatality Ratio', style_function=lambda x: { 'fillColor': df_covid_joined['Case_Fatality_Ratio_color'][x['properties'][ 'Country_Region']], 'fillOpacity': 0.7, 'color': 'black', 'weight': 1 }).add_to(feature_groups[4]) popup_case_fatality_ratio = folium.GeoJsonPopup( fields=['Country_Region', 'Case_Fatality_Ratio'], labels=False) popup_case_fatality_ratio.add_to(choropleth_case_fatality_ratio) # Create the map legends templates legend_str_dict = {} for i, (k, v) in enumerate(color_dict.items()): legend_labels_dict = {} j = 0 for color in v: if j == 0: legend_labels_dict[color] = 'No data' elif j == len(v) - 1: legend_labels_dict[color] = '> ' + str(bins[i][j]) break else: legend_labels_dict[color] = str(bins[i][j]) + ' - ' + str( bins[i][j + 1]) j += 1 legend_str_dict[k] = legend_labels_dict template = utils.create_legend(caption='COVID-19 status as of: ' + str(timestamp) + ' UTC', legend_labels=legend_str_dict) macro = MacroElement() macro._template = Template(template) map_covid.get_root().add_child(macro) for feature_group in feature_groups: feature_group.add_to(map_covid) # Activate Layer Control folium.LayerControl(collapsed=True).add_to(map_covid) ''' Save completed map viz to an appropriate folder ''' map_covid.save( os.path.join(script_dir_path, '..', 'webapp', 'templates', 'COVID-19_viz.html')) print('Successfully created the COVID-19 viz!')
def make_interactive_map(data_file): DATA_DIR = "output" SUPPORTING_DATA = Path("awmc.unc.edu") SUPPORTING_DATA = SUPPORTING_DATA / "awmc" / "map_data" / "shapefiles" ROMAN_ROADS_SHP = SUPPORTING_DATA / "ba_roads" / "ba_roads.shp" PROVINCES_SHP = SUPPORTING_DATA / "cultural_data" / "political_shading" / "roman_empire_ad_117" / "shape" / "roman_empire_ad_117.shp" CITIES_DATA = Path("cities") / "Hanson2016_Cities_OxREP.csv" cities_rows = extract(CITIES_DATA) cities_dataframe = pandas.DataFrame(cities_rows) #https://cmdlinetips.com/2018/02/how-to-subset-pandas-dataframe-based-on-values-of-a-column/ roads_4326 = geopandas.read_file(ROMAN_ROADS_SHP).to_crs(epsg=4326) provinces_4326 = geopandas.read_file(PROVINCES_SHP).to_crs(epsg=4326) cities_geodataframe_4326 = geopandas.GeoDataFrame( cities_dataframe, geometry=geopandas.points_from_xy(cities_dataframe["Longitude (X)"], cities_dataframe["Latitude (Y)"]), crs="EPSG:4326").to_crs(epsg=4326) cities_geodataframe_4326.drop("Longitude (X)", inplace=True, axis=1) cities_geodataframe_4326.drop("Latitude (Y)", inplace=True, axis=1) #pprint(cities_geodataframe_4326) geopandas.options.use_pygeos = True # TODO https://nbviewer.jupyter.org/github/python-visualization/folium_contrib/blob/master/notebooks/HereMapsApiExplorer_no_creds.ipynb get this out of the display file output_maps = {} xmin, ymin, xmax, ymax = (0, 0, 10000, 10000) #for file in glob.glob(f"{DATA_DIR}/*.tsv"): df = makeDataframe(data_file, epsg=4326) #pprint(df) map_xmin, map_ymin, map_xmax, map_ymax = df.total_bounds xmin = max(xmin, map_xmin) ymin = max(ymin, map_ymin) xmax = min(xmax, map_xmax) ymax = min(ymax, map_ymax) output_maps[data_file] = df.to_json() # Create a map using the Map() function and the coordinates for Boulder, CO scrape_map = folium.Map( location=[41.9028, 12.4964], zoom_start=5, #tiles='https://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}{r}.png', #attr = '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors © <a href="https://carto.com/attributions">CARTO</a>', tiles= 'https://stamen-tiles-{s}.a.ssl.fastly.net/terrain-background/{z}/{x}/{y}.png', attr= 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> — Map data © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', ) # Display the map #cities = folium.features.GeoJson(cities_geodataframe_4326.to_json()).add_to(scrape_map) # Running the above crashes the tab # scrape_map.add_child(cities) #https://leafletjs.com/reference-1.6.0.html#path-option road_style = {'color': '#000000', 'opacity': 0.5} roads = folium.features.GeoJson( roads_4326.to_json(), name='Roads', style_function=lambda x: road_style).add_to(scrape_map) #https://stackoverflow.com/a/45081821 r = lambda: (random.randint(0, 255)) for map_json in output_maps: # https://github.com/python-visualization/folium/issues/1385 folium.features.GeoJson(output_maps[map_json], name=f"{map_json}", popup=folium.GeoJsonPopup([ "EDCS-ID", "EDCS Link", "raw dating", "province", "place", "Material", "cleaned inscription" ])).add_to(scrape_map) def province_style(arg): return { 'weight': 2, 'opacity': 1, 'color': '#ffffff', 'dashArray': 3, 'fillOpacity': 0.4, 'fillColor': "#{:02x}{:02x}{:02x}".format(r(), r(), r()) } provinces = folium.features.GeoJson( provinces_4326.to_json(), style_function=province_style).add_to(scrape_map) return scrape_map
fill_color="green", color="grey", fill=True, fill_opacity=0.5)) else: feat_group_large.add_child( folium.CircleMarker(location=[lat, long], radius=5, popup=popup, fill_color="red", color="grey", fill=True, fill_opacity=0.5)) feat_group_areas.add_child( folium.GeoJson( data=open("data/world.json", 'r', encoding='utf-8-sig').read(), style_function=lambda x: { 'fillColor': 'white' if x["properties"]["AREA"] < 150000 else "black" }, # try to obtain mean of area instead of trial and error with the cutoff value for fillcolor popup=folium.GeoJsonPopup(fields=["AREA"], localize=True, labels=True))) map.add_child(feat_group_underwater) map.add_child(feat_group_small) map.add_child(feat_group_large) map.add_child(feat_group_areas) map.add_child(folium.LayerControl()) map.save("Volcanoes.html")
# my_map.get_root().html.add_child(folium.Element(sub_html)) co_style = lambda x: {'color': '#FF1ACB35'} counties = folium.GeoJson(r"data/PA_counties.geojson", name="Pennsylvania County Boundaries", style_function=co_style).add_to(my_map) folium.features.GeoJsonPopup(fields=["NAMELSAD"], labels=False).add_to(counties) timber_style = lambda x: { 'color': '#1ACB35' if x['properties']['acres'] < 15 else '#CB391A' } timb_gjson = folium.GeoJson( r"data\PA_timbersale_labeled.geojson", name="Timber Harvest Noundaries", zoom_on_click=True, style_function=timber_style, popup=folium.GeoJsonPopup(fields=['ID', 'acres'])).add_to(my_map) url = "data\legend.png" FloatImage(url, bottom=6, left=6).add_to(my_map) my_map.add_child(folium.map.LayerControl()) #Display the map my_map my_map.save('demo_webmap.html') print('generated')
def gorhammap(): import folium import os import json m = folium.Map(location=[43.6819, -70.4490], tiles='OpenStreetMap', prefer_canvas=True, zoom_control=False, min_zoom=10) residentiallots = "/home/carter/PycharmProjects/campusParkingMap/flaskr/Resources/GeoJSON/Gorham/Residential Lots" commuterlots = "/home/carter/PycharmProjects/campusParkingMap/flaskr/Resources/GeoJSON/Gorham/Commuter Lots" stafflots = "/home/carter/PycharmProjects/campusParkingMap/flaskr/Resources/GeoJSON/Gorham/Staff Lots" commuterstyle = { 'fillColor': 'red', 'color': 'black', 'fillOpacity': '0.5' } residentialstyle = { 'fillColor': 'green', 'color': 'black', 'fillOpacity': '0.6' } staffstyle = {'fillColor': 'blue', 'color': 'black', 'fillOpacity': '0.6'} closedstyle = { 'fillColor': 'black', 'color': 'black', 'fillOpacity': '0.6' } gorhambancounter = 0 # Residential Lots resdirectory = os.fsencode(residentiallots) for file in os.listdir(resdirectory): filename = os.fsdecode(file) if filename.endswith(".json5"): with open(residentiallots + "/" + filename) as f: data = json.load(f) if data['features'][0]['properties']['lot_status'] == 'closed': folium.GeoJson(os.path.join(residentiallots, filename), style_function=lambda x: closedstyle, highlight_function=lambda x: { 'weight': 3, 'color': 'black', 'fillColor': 'grey' }, popup=folium.GeoJsonPopup( fields=[ 'lot_name', 'lot_type', 'lot_status', 'handicapped_spots' ], aliases=[ 'Lot Name:', 'Lot Type:', 'Lot Status:', 'Handicapped Spots:' ], class_name="respopup")).add_to(m) gorhambancounter += 1 else: folium.GeoJson(os.path.join(residentiallots, filename), style_function=lambda x: residentialstyle, highlight_function=lambda x: { 'weight': 3, 'color': 'green', 'fillColor': 'grey' }, popup=folium.GeoJsonPopup( fields=[ 'lot_name', 'lot_type', 'lot_status', 'handicapped_spots' ], aliases=[ 'Lot Name:', 'Lot Type:', 'Lot Status:', 'Handicapped Spots:' ], class_name="respopup")).add_to(m) continue # Commuter Lots commdirectory = os.fsencode(commuterlots) for file in os.listdir(commdirectory): filename = os.fsdecode(file) if filename.endswith(".json5"): with open(commuterlots + "/" + filename) as f: data = json.load(f) if data['features'][0]['properties']['lot_status'] == 'closed': folium.GeoJson(os.path.join(commuterlots, filename), style_function=lambda x: closedstyle, highlight_function=lambda x: { 'weight': 3, 'color': 'black', 'fillColor': 'grey' }, popup=folium.GeoJsonPopup( fields=[ 'lot_name', 'lot_type', 'lot_status', 'handicapped_spots' ], aliases=[ 'Lot Name:', 'Lot Type:', 'Lot Status:', 'Handicapped Spots:' ], class_name="commpopup")).add_to(m) gorhambancounter += 1 else: folium.GeoJson(os.path.join(commuterlots, filename), style_function=lambda x: commuterstyle, highlight_function=lambda x: { 'weight': 3, 'color': 'red', 'fillColor': 'grey' }, popup=folium.GeoJsonPopup( fields=[ 'lot_name', 'lot_type', 'lot_status', 'handicapped_spots' ], aliases=[ 'Lot Name:', 'Lot Type:', 'Lot Status:', 'Handicapped Spots:' ], class_name="commpopup")).add_to(m) continue # Staff Lots staffdirectory = os.fsencode(stafflots) for file in os.listdir(staffdirectory): filename = os.fsdecode(file) if filename.endswith(".json5"): with open(stafflots + "/" + filename) as f: data = json.load(f) if data['features'][0]['properties']['lot_status'] == 'closed': folium.GeoJson(os.path.join(stafflots, filename), style_function=lambda x: closedstyle, highlight_function=lambda x: { 'weight': 3, 'color': 'black', 'fillColor': 'grey' }, popup=folium.GeoJsonPopup( fields=[ 'lot_name', 'lot_type', 'lot_status', 'handicapped_spots' ], aliases=[ 'Lot Name:', 'Lot Type:', 'Lot Status:', 'Handicapped Spots:' ], class_name="staffpopup")).add_to(m) gorhambancounter += 1 else: folium.GeoJson(os.path.join(stafflots, filename), style_function=lambda x: staffstyle, highlight_function=lambda x: { 'weight': 3, 'color': 'blue', 'fillColor': 'grey' }, popup=folium.GeoJsonPopup( fields=[ 'lot_name', 'lot_type', 'lot_status', 'handicapped_spots' ], aliases=[ 'Lot Name:', 'Lot Type:', 'Lot Status:', 'Handicapped Spots:' ], class_name="staffpopup")).add_to(m) continue m.fit_bounds([[43.6785, -70.4521], [43.6856, -70.4455]]) m.save( "/home/carter/PycharmProjects/campusParkingMap/flaskr/static/GorhamMap.html" ) return gorhambancounter
def map( self, width='100%', height='100%', tiles='Cartodb Positron', ignore=[], **kwargs, ): ''' Plot overview map with folium Parameters: ---------- tiles: str tiles used, see `folium.Map?`` - "OpenStreetMap" - "Mapbox Bright" (Limited levels of zoom for free tiles) - "Mapbox Control Room" (Limited levels of zoom for free tiles) - "Stamen" (Terrain, Toner, and Watercolor) - "Cloudmade" (Must pass API key) - "Mapbox" (Must pass API key) - "CartoDB" (positron and dark_matter) ''' if ignore == 'all': ignore = self._units m = folium.Map( location=[self.lat_mid, self.lon_mid], width=width, height=height, zoom_start=11, tiles=tiles, ) # bathymetric contours contours_geojson = load_bathy_contours() tooltip = folium.GeoJsonTooltip( fields=['title'], aliases=['depth'], ) popup = folium.GeoJsonPopup( fields=['title'], aliases=['depth'], ) #colorscale = branca.colormap.linear.Greys_03.scale(levels[-1],levels[0]) def style_func(feature): return { 'color': feature['properties'] ['stroke'], #colorscale(feature['properties']['level-value']), 'weight': 3, #x['properties']['stroke-width'], #'fillColor': x['properties']['fill'], 'opacity': 1., #'popup': feature['properties']['title'], } folium.GeoJson( contours_geojson, name='geojson', style_function=style_func, tooltip=tooltip, popup=popup, ).add_to(m) # campaign details for uname, u in self.items(): if uname not in ignore: for d in u: folium.Polygon([(d.start.lat, d.start.lon), (d.end.lat, d.end.lon)], tooltip=uname + ' ' + d.label + '<br>' + str(d.start.time) + '<br>' + str(d.end.time), color=cnames[u['color']], dash_array='10 20', opacity=.5).add_to(m) folium.Circle( (d.start.lat, d.start.lon), tooltip=uname + ' ' + d.label + '<br>' + str(d.start.time), radius=2 * 1e2, color=cnames[u['color']], ).add_to(m) folium.Circle( (d.end.lat, d.end.lon), tooltip=uname + ' ' + d.label + '<br>' + str(d.end.time), radius=1e2, color=cnames[u['color']], ).add_to(m) # useful plugins MeasureControl().add_to(m) fmtr_lon = "function(dec) {var min= (dec-Math.round(dec))*60; " \ +"direction = (dec < 0) ? 'W' : 'E'; " \ +"return L.Util.formatNum(dec, 0) + direction + L.Util.formatNum(min, 2);};" fmtr_lat = "function(dec) {var min= (dec-Math.round(dec))*60; " \ +"direction = (dec < 0) ? 'S' : 'N'; " \ +"return L.Util.formatNum(dec, 0) + direction + L.Util.formatNum(min, 2);};" MousePosition(lat_formatter=fmtr_lon, lng_formatter=fmtr_lat).add_to(m) return m
test = gpd.read_postgis(request, engine, geom_col='geometry') test = sdf.merge(test.drop('geometry', axis=1), on='identifiant_geo') stest = test.to_crs('EPSG:4326') sextent = stest.total_bounds return ([test.drop('geometry', axis=1), stest]) st.title('GridInShape') st.markdown( '''L'application GridInShape projete les données carroyées [Filosofi 2015 de l'Insee](https://www.insee.fr/fr/statistiques/4176305) sur un fond choisi par l'utilisateur. Les calculs sont effectués au prorata des surfaces communes entre les carreaux et les territoires de l'utilisateurs. L'application accepte les formats ESRI Shapefile, geojson et Geopackage.''' ) shapefiles = st.file_uploader('Choisir le fond de carte', accept_multiple_files=True) res = calcul(shapefiles) m = folium.Map() Y1, X1, Y2, X2 = res[1].total_bounds folium.GeoJson(res[1].to_json(), name="geojson", popup=folium.GeoJsonPopup(fields=['identifiant_geo'])).add_to(m) m.fit_bounds([[X1, Y1], [X2, Y2]]) folium_static(m) st.dataframe(res[0]) csv = res[0].to_csv(index=False) b64 = base64.b64encode( csv.encode()).decode() # some strings <-> bytes conversions necessary here href = f'<a href="data:file/csv;base64,{b64}">Télécharger en CSV les résultats</a> (clic droit et exporter < sous >.csv)' st.markdown(href, unsafe_allow_html=True)