def render_example6(): # Generate some in-memory data. bermuda = dlx.dicts_to_geojson([dict(lat=32.299507, lon=-64.790337)]) biosfera = dlx.geojson_to_geobuf( dlx.dicts_to_geojson([dict(lat=29.015, lon=-118.271)])) with open("data/KCNeighborhood.json", 'r') as f: statesData = json.load(f) return [ dl.Map( center=[39, -98], zoom=4, children=[ dl.TileLayer(), dl.GeoJSON(data=bermuda), # in-memory geojson (slowest option) dl.GeoJSON( data=biosfera, format="geobuf" ), # in-memory geobuf (smaller payload than geojson) dl.GeoJSON( data=statesData, id="capitals"), # geojson resource (faster than in-memory) ], style={ 'width': '100%', 'height': '50vh', 'margin': "auto", "display": "block" }, id="map"), html.Div(id="state"), html.Div(id="capital") ]
def scene__update_map_by_parameters(signal, start_date, end_date): if signal is None: raise PreventUpdate logging.info( f'scene__update_map_by_parameters - start_date: {start_date}; end_date: {end_date}' ) start_date, end_date = __convert_dates_from_str_to_date( start_date, end_date) # if start date is greater than end date or limit is None, then the callback returns an empty object if start_date > end_date: return dicts_to_geojson([]) # convert the dates from datetime to str again in order to pass the xaxis range to build the figure xaxis_range = [ start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d') ] # get data from cache df_sd_ds_ym_long_lat = cache.get('scene:df_sd_ds_ym_long_lat') # when user selects an invalid range, the df has len equals to 0, # then the callback returns an empty object to avoid error message if len(df_sd_ds_ym_long_lat.index) == 0: return dicts_to_geojson([]) # get a sub set from the df according to the selected date range sub_df = df_sd_ds_ym_long_lat[__get_logical_date_range( df_sd_ds_ym_long_lat, xaxis_range)] # build the geojson object with a list of markers return __get_geojson_data(sub_df)
def get_map(run_by, paved_status, lighted_status, spaces_range): df = lots[(lots["operator"].isin(run_by)) & (lots["is_paved"].isin(paved_status)) & (lots["light"].isin(lighted_status)) & (lots["available_spaces"] >= spaces_range[0]) & (lots["available_spaces"] <= spaces_range[1])] titles = df[df.columns[0]] lat = df[df.columns[7]] long = df[df.columns[8]] avg_lat = sum(lat) / len(lat) avg_long = sum(long) / len(long) print(len(df)) points = [] for i in range(0, len(lat) - 1): points.append(dict(lat=lat[i], lon=long[i])) return dl.Map(center=[avg_lat, avg_long], zoom=7, children=[ dl.TileLayer(), dl.GeoJSON(data=dlx.dicts_to_geojson(points)) ], style={ 'width': '100%', 'height': '50vh', 'margin': "auto", "display": "block" }, id="map-object")
def get_data(dataframe): df = dataframe.drop_duplicates(subset='ChargePoint_ID') dicts = df.to_dict('records') for item in dicts: item["tooltip"] = f'{item["Address"]}, {item["PostalCode"]}, {item["ChargePoint_ID"]}' # bind tooltip item['Selected'] = 'Not Selected' geojson = dlx.dicts_to_geojson( dicts, lon="Longitude", lat="Latitude") # convert to geojson geobuf = dlx.geojson_to_geobuf(geojson) # convert to geobuf return geobuf
def get_data(nbhid, years_range): # filter_df = df[(df['CREATION YEAR'] <= years_range[1]) & # (df['CREATION YEAR'] >= years_range[0])] df_nbh = df[df["nbhid"] == nbhid] # pick one state df_nbh = df_nbh[['LATITUDE', 'LONGITUDE', 'NEIGHBORHOOD', 'DAYS TO CLOSE']] # use only relevant columns dicts = df_nbh.to_dict('rows') for item in dicts: item["tooltip"] = "{:.1f}".format(item[color_prop]) # bind tooltip item["popup"] = item["NEIGHBORHOOD"] # bind popup geojson = dlx.dicts_to_geojson(dicts, lat="LATITUDE", lon="LONGITUDE") # convert to geojson geobuf = dlx.geojson_to_geobuf(geojson) # convert to geobuf return geobuf
def get_data(color_prop): df = read_data().dropna(subset=[color_prop]) # drop irrelevant columns df = df[['lat', 'lon', 'alt', 'station', 'date', color_prop]] dicts = df.to_dict('rows') for item in dicts: item["tooltip"] = "Measured at %s : %2.1f" % (item["date"], item[color_prop]) item["popup"] = "%s, altitude %4.0f" % (item["station"], item["alt"]) geojson = dlx.dicts_to_geojson(dicts, lon="lon", lat="lat") geobuf = dlx.geojson_to_geobuf(geojson) # convert to geobuf return geobuf
def get_project_points(cpa: str): df_cpa = project_outcomes[project_outcomes['cpa_name'] == cpa] if cpa else project_outcomes df_cpa = df_cpa[[ 'project_nickname', 'cpa_name', 'coordinate_x', 'coordinate_y' ]].dropna().drop_duplicates() dicts = df_cpa.to_dict('rows') for item in dicts: item['tooltip'] = item['project_nickname'] item['popup'] = item['cpa_name'] geojson = dlx.dicts_to_geojson(dicts, lat='coordinate_x', lon="coordinate_y") return dlx.geojson_to_geobuf(geojson)
def get_data(cpa: int): df_cpa = df[df['cpa_name'] == cpa] if cpa else df df_cpa = df_cpa[[ 'project_nickname', 'cpa_name', 'coordinate_x', 'coordinate_y' ]].dropna() dicts = df_cpa.to_dict('rows') for item in dicts: item['tooltip'] = item['project_nickname'] item['popup'] = item['cpa_name'] geojson = dlx.dicts_to_geojson(dicts, lat='coordinate_x', lon="coordinate_y") geobuf = dlx.geojson_to_geobuf(geojson) return geobuf
def get_data(state): df_state = df[df["state_id"] == state] # pick one state df_state = df_state[['lat', 'lng', 'city', 'population', 'density']] # drop irrelevant columns df_state = df_state[df_state[color_prop] > 0] # drop abandoned cities df_state[color_prop] = np.log( df_state[color_prop]) # take log as the values varies A LOT dicts = df_state.to_dict('rows') for item in dicts: item["tooltip"] = item["city"] # bind tooltip item["popup"] = item["city"] # bind popup geojson = dlx.dicts_to_geojson(dicts, lon="lng") # convert to geojson geobuf = dlx.geojson_to_geobuf(geojson) # convert to geobuf return geobuf
def get_data(variable): df = get_df().dropna(subset=[variable]) # drop irrelevant columns df = df[['latitude', 'longitude', 'altitude', 'name', 'observation_time_local', variable]] dicts = df.to_dict('records') for item in dicts: item["tooltip"] = "Measured at %s : %2.1f" % ( item["observation_time_local"], item[variable]) item["popup"] = "%s, altitude: %4.0f m" % ( item["name"], item["altitude"]) geojson = dlx.dicts_to_geojson(dicts, lon="longitude", lat="latitude") geobuf = dlx.geojson_to_geobuf(geojson) return geobuf
def create_map(title='', data=[], size=6): geojson = dicts_to_geojson([{ **d, **dict(tooltip=d['name']) } for d in data]) dd_options = [dict(value=c['name'], label=c['name']) for c in data] dd_defaults = [o['value'] for o in dd_options] dd_defaults = list(set(dd_defaults)) point_to_layer = assign("""function(feature, latlng, context){ return L.circleMarker(latlng); // sender a simple circle marker. }""") map = Map(children=[ TileLayer(), GeoJSON(data=geojson, hideout=dd_defaults, id='geojson', zoomToBounds=True, options=dict(pointToLayer=point_to_layer)) ], style={ 'width': '100%', 'height': '50vh', 'margin': 'auto', 'display': 'block' }, id='map') return html.Div(html.Div([ html.Div(html.Div( [ html.H4(title, className='subtitle is-4 has-text-centered is-bold'), map, ], className='content', ), className='card-content'), ], className='card', style={'background-color': 'rgb(244, 244, 244)'}), className='column is-' + str(size))
def download__update_map_by_parameters(signal, start_date, end_date, limit): if signal is None: raise PreventUpdate logging.info(f'download__update_map_by_parameters - start_date: {start_date}; ' f'end_date: {end_date}; limit: {limit}') start_date, end_date = __convert_dates_from_str_to_date(start_date, end_date) # if start date is greater than end date or limit is None, # then the callback returns an empty object if start_date > end_date or limit is None: return dicts_to_geojson([]) sub_df = __create_sub_df_based_on_parameters( # get data from cache cache.get('download:df_download'), start_date, end_date, limit ) # build the geojson object with a list of markers return __get_geojson_data(sub_df)
def __get_geojson_data(df): # create a tooltip and popup df['tooltip'] = df.apply( lambda row: f"({row['latitude']}, {row['longitude']})", axis=1 ) df['popup'] = df.apply( lambda row: ( f"Number: {row['number']}<br>" f"Collection: {row['collection']}<br>" f"Year-month: {row['year_month']}<br>" f"Latitude: {row['latitude']}<br>" f"Longitude: {row['longitude']}" ), axis=1 ) # create the markers based on the dataframe geojson = dicts_to_geojson(df.to_dict('rows'), lat='latitude', lon='longitude') return geojson
def __get_geojson_data(df): # create a tooltip and popup df['tooltip'] = df.apply( lambda row: f"({row['latitude']}, {row['longitude']})", axis=1 ) df['popup'] = df.apply( lambda row: ( f"E-mail: {row['email']}<br>" f"Name: {row['name']}<br>" f"Number: {row['number']}<br>" f"Date: {row['date']}<br>" f"Latitude: {row['latitude']}<br>" f"Longitude: {row['longitude']}" ), axis=1 ) # create the markers based on the dataframe geojson = dicts_to_geojson(df.to_dict('rows'), lat='latitude', lon='longitude') return geojson
def get_data(df, color_prop="income"): if len(df) > 0: transform_3857_to_4326 = Transformer.from_crs('epsg:3857', 'epsg:4326') df['lat'], df['lon'] = transform_3857_to_4326.transform( df.x.to_array(), df.y.to_array() ) # drop irrelevant columns df = df[['lat', 'lon', 'sex', 'education', 'income']] if isinstance(df, cudf.DataFrame): dicts = df.to_pandas().to_dict('rows') else: dicts = df.to_dict('rows') for item in dicts: # bind tooltip item["tooltip"] = "{:.1f}".format(item[color_prop]) # bind popup item["popup"] = item["income"] # convert to geojson geojson = dlx.dicts_to_geojson(dicts, lat="lat", lon="lon") # convert to geobuf return geojson return ''
encoded_kuk_sound = base64.b64encode(open(kuk_sound, 'rb').read()) encoded_quaa_sound = base64.b64encode(open(quaa_sound, 'rb').read()) encoded_moan_sound = base64.b64encode(open(moan_sound, 'rb').read()) app = dash.Dash(__name__, suppress_callback_exceptions=True, external_stylesheets=[dbc.themes.BOOTSTRAP]) app.title = 'SQURL' server = app.server # Find Lat Long center to set map center lat_center = sum(squirrel_census['lat']) / len(squirrel_census['lat']) long_center = sum(squirrel_census['lon']) / len(squirrel_census['lon']) data = dlx.geojson_to_geobuf(dlx.dicts_to_geojson(squirrel_data)) ns = Namespace("myNamespace", "mySubNamespace") nz = Namespace("dlx", "scatter") # get map style url = 'https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png' attribution = '© <a href="https://stadiamaps.com/">Stadia Maps</a> ' app.layout = html.Div( children=[ # HEADER html.Div( children=[ html.H1('SQURL', id='header-text'),
def update_local_table(at, data, viewport_ids, selected_row_id, data_state, local_map): # TODO don't pass entire map. just need to see if it exists if (not at) or (at != "local_tab"): raise PreventUpdate ctx = dash.callback_context input_id = ctx.triggered[0]["prop_id"].split(".")[0] dff = pd.DataFrame(data) if dff.empty: return [], [], [], None, None, {} else: if "Per Capita" in dff: color_column = "Per Capita" elif "Per Student" in dff: color_column = "Per Student" else: color_column = "Amount" (styles, legend, df_color, max_y) = du.discrete_background_color_bins(dff, columns=[color_column]) styles = styles + [{ "if": { "column_id": c }, "width": 100, "font-family": "Sparks-Bar-Extrawide", "font-size": "18px", "padding-right": "15px", "padding-left": "15px", } for c in ["sparkline_Per Capita", "sparkline_Per Student"]] bar_charts = [] if (not df_color.empty) and (len(dff["id"].unique()) > 1): dff[color_column + "_color"] = df_color dff = dff[dff["id"].isin(viewport_ids)] bar_charts = du.make_bar_charts(dff, color_column, "ID name", clip=max_y) # update map dff_state = pd.DataFrame(data_state) dff_lat_lng = df_lat_lng[df_lat_lng["state_id"] == dff_state["ST"].iat[0]] dff_state["name"] = dff_state["ID name"].str[:-4] dff_state = pd.merge( dff_state, dff_lat_lng, how="left", left_on=["County name", "name"], right_on=["county_name", "city"], ) dff_state = dff_state.dropna() dicts = dff_state.to_dict("row") for item in dicts: item["popup"] = "${:.0f} per capita {}".format( item[color_column], item["name"]) item["tooltip"] = item["name"] # bind popup geojson_data = dlx.dicts_to_geojson(dicts, lon="lng") # convert to geojson geobuf = dlx.geojson_to_geobuf(geojson_data) # convert to geobuf colors = colorlover.scales[str(5)]["seq"]["Blues"] hideout = dict( colorscale=colors, color_prop=color_column, popup_prop="name", min=0, max=max_y, circle_options=dict(radius=10), ) if selected_row_id and selected_row_id != []: selected_row = dff_state[dff_state["id"].isin(selected_row_id)] lat = selected_row.iloc[0]["lat"] lng = selected_row.iloc[0]["lng"] hideout = dict( colorscale=colors, color_prop=color_column, popup_prop="name", min=0, max=max_y, open=selected_row_id[0], circle_options=dict(radius=10), ) return ( styles, bar_charts, legend, hideout, geobuf, { "zoom": 12, "center": [lat, lng] }, ) else: return styles, bar_charts, legend, hideout, geobuf, {}
import dash_html_components as html import dash_leaflet as dl import dash_leaflet.express as dlx from dash import Dash from dash.dependencies import Output, Input from dash_extensions.javascript import arrow_function # Generate some in-memory data. bermuda = dlx.dicts_to_geojson([dict(lat=32.299507, lon=-64.790337)]) biosfera = dlx.geojson_to_geobuf( dlx.dicts_to_geojson([dict(lat=29.015, lon=-118.271)])) # Create example app. app = Dash() app.layout = html.Div([ dl.Map( center=[39, -98], zoom=4, children=[ dl.TileLayer(), dl.GeoJSON(url="/assets/rfmp4.json" ), # geojson resource (faster than in-memory) ], style={ 'width': '100%', 'height': '50vh', 'margin': "auto", "display": "block" }, id="map"), html.Div(id="state"), html.Div(id="capital")
import pandas as pd import numpy as np from dash.dependencies import Output, Input df = pd.read_csv('gridcities.csv') color_prop = 'population' df_state = df.dropna() df_state = df_state[['lat', 'lng', 'city', 'population', 'density']] # drop irrelevant columns dicts = df_state.to_dict('rows') for item in dicts: item["tooltip"] = item["city"] # bind tooltip geojson = dlx.dicts_to_geojson(dicts, lon="lng") # convert to geojson geobuf = dlx.geojson_to_geobuf(geojson) # convert to geobuf with open('geobuf.pkl', 'wb') as f: pickle.dump(geobuf, f, pickle.HIGHEST_PROTOCOL) geojson = dl.GeoJSON( data=geobuf, id="geojson", format="geobuf", zoomToBounds=True, # when true, zooms to bounds when data changes cluster=True, # when true, data are clustered clusterToLayer=dlx.scatter.cluster_to_layer, # how to draw clusters zoomToBoundsOnClick= True, # when true, zooms to bounds of feature (e.g. cluster) on click options=dict(
import dash_core_components as dcc import dash_html_components as html import dash_leaflet as dl import examples.scatter_rt_js as rjs import dash_leaflet.express as dlx from dash.dependencies import Input, Output from dash_transcrypt import inject_js, module_to_props # Create some markers. points = [ dict(lat=55.5 + random.random(), lon=9.5 + random.random(), value=random.random()) for i in range(100) ] data = dlx.dicts_to_geojson(points) # Create geojson. js = module_to_props(rjs) # compiles the js geojson = dl.GeoJSON( data=data, options=dict(pointToLayer=rjs.point_to_layer), # pass function as prop hideout=dict(scale=10), id="geojson") # pass variables to function # Create the app. app = dash.Dash() app.layout = html.Div([ dl.Map([dl.TileLayer(), geojson], center=(56, 10), zoom=8, style={'height': '50vh'}), dcc.Slider(min=1, max=100, value=10, id="slider")
app = dash.Dash() with open( r"C:\Users\julien_schroder\Desktop\JM_FinaleMaps_Repo\Points4326.geojson" ) as f: points = geojson.load(f) with open( r"C:\Users\julien_schroder\Desktop\JM_FinaleMaps_Repo\Routes4326.geojson" ) as g: routes = geojson.load(g) dRoutes = FeatureCollection([f for f in routes['features']]) dPoints = FeatureCollection([f for f in points['features']]) biosfera = dlx.geojson_to_geobuf( dlx.dicts_to_geojson([dict(lat=29.015, lon=-118.271)])) app.layout = html.Div([ dl.Map( center=[39, -98], zoom=4, children=[ dl.TileLayer(), dl.GeoJSON(data=dPoints, id='capitals', cluster=True), # in-memory geojson (slowest option) dl.GeoJSON(data=dRoutes, id='states' ), # in-memory geobuf (smaller payload than geojson) ], style={ 'width': '100%', 'height': '100vh', 'margin': "auto",