def get_event_layer(eq_data, sizes, colors, opacities): """Return a LayerGroup that contains earthquakes represented as circles. Keyword arguments: eq_data -- EarthquakeData object containing the quakes to be drawn. sizes -- An array containing a size for each data point colors -- An array containing a color for each data point opacities -- An array containing an opacity for each data point """ quake_circles = [ dl.Circle(center=[quake['LATITUDE'], quake['LONGITUDE']], radius=sizes[idx], color=colors[idx], fillOpacity=opacities[idx], weight=2, children=[ dl.Popup(dcc.Markdown( list( map( lambda x: '**{}**: {} '.format( x.replace('[', r'\['), quake[x]), quake.keys()))), className='earthquake-popup') ]) for idx, quake in eq_data.data.reset_index().iterrows() ] return dl.LayerGroup(id='layer-id', children=quake_circles)
def update_map(rows, viewData): dff = pd.DataFrame.from_dict(viewData) # get the lat and lon of the selected row lat = dff.iat[rows[0], 13] lon = dff.iat[rows[0], 14] return [ dl.Map( style={ 'width': '1000px', 'height': '500px' }, center=[30.75, -97.48], zoom=10, children=[ dl.TileLayer(id="base-layer-id"), # Marker with tool tip and popup dl.Marker(position=[lat, lon], children=[ dl.Tooltip(dff.iat[rows[0], 4]), dl.Popup([ html.H1("Animal Name"), html.P(dff.iat[rows[0], 9]) ]) ]) ]) ]
def get_old_fire_positions(dpt_code=None): # As long as the user does not click on a department, dpt_code is None and we return no fire marker if not dpt_code: return None # We read the csv file that locates the old fires and filter for the department of interest old_fire_positions = pd.read_csv( Path(__file__).parent.joinpath('data', 'historic_fires.csv'), ',') # Below it allows us to filter by department with a click on the map old_fire_positions = old_fire_positions[old_fire_positions['Département'] == int(dpt_code)].copy() icon = { "iconUrl": '../assets/pyro_oldfire_icon.png', "iconSize": [50, 50], # Size of the icon "iconAnchor": [ 25, 45 ], # Point of the icon which will correspond to marker's and popup's location "popupAnchor": [0, -20 ] # Point from which the popup should open relative to the iconAnchor } # We build a list of dictionaries containing the coordinates of each fire fire_markers = [] for i, row in old_fire_positions.iterrows(): lat = row['latitude'] lon = row['longitude'] location = row['location'] date = dt.datetime.strptime(row['acq_date'], '%Y-%m-%d')\ .strftime('%d %b %Y') if row['daynight'] == 'D': daynight = 'Diurne' elif row['daynight'] == 'N': daynight = 'Nocturne' else: daynight = None fire_markers.append( dl.Marker( id= f'historic_fire_{i}', # Set an id for each marker to receive callbacks position=(lat, lon), icon=icon, children=[ dl.Tooltip(f"Date: {date}"), dl.Popup([ html.H4(f'Incendie du {date}'), html.P(f'Commune : {location}'), html.P(f'Type : {daynight}') ]) ])) return fire_markers
def build_historic_markers(dpt_code=None): """ This function reads through the 'historic_fires.csv' file stored in the /data folder. It takes as input a department code (as a character string), which will correspond to the department on which the user chooses to click and it returns past fires (as markers on the map) for this area. More precisely, it returns a dl.LayerGroup object that gathers all relevant past fire markers. """ # As long as the user does not click on a department, dpt_code is None and we return no fire marker if not dpt_code: return None # We read the csv file that locates the old fires old_fire_positions = pd.read_csv(Path(__file__).parent.joinpath('data', 'historic_fires.csv'), ',') # The line below allows us to filter for the department of interest old_fire_positions = old_fire_positions[old_fire_positions['Département'] == int(dpt_code)].copy() icon = {"iconUrl": '../assets/pyro_oldfire_icon.png', "iconSize": [50, 50], # Size of the icon "iconAnchor": [25, 45], # Point of the icon which will correspond to marker's and popup's location "popupAnchor": [0, -20] # Point from which the popup should open relative to the iconAnchor } # We build a list of dictionaries containing the coordinates of each fire fire_markers = [] for i, row in old_fire_positions.iterrows(): lat = row['latitude'] lon = row['longitude'] location = row['location'] date = datetime.datetime.strptime(row['acq_date'], '%Y-%m-%d')\ .strftime('%d %b %Y') if row['daynight'] == 'D': daynight = 'Diurne' elif row['daynight'] == 'N': daynight = 'Nocturne' else: daynight = None fire_markers.append(dl.Marker(id=f'historic_fire_{i}', # Set an id for each marker to receive callbacks position=(lat, lon), icon=icon, children=[dl.Tooltip(f"Date: {date}"), dl.Popup([html.H4(f'Incendie du {date}'), html.P(f'Commune : {location}'), html.P(f'Type : {daynight}')]) ] ) ) # We gather all markers stored in the fire_markers list in a dl.LayerGroup object, which is returned return dl.LayerGroup(children=fire_markers, id='historic_fires_markers')
def build_popup(feature=None): """ This function extract info to display from the geojson object It takes as argument the geojson clicked by user It returns the popup with the appropriate info for each markers on the map. """ if feature is not None: coord = 'Coordonnées de la caméra : {}'.format( feature['geometry']['coordinates']) return [dl.Popup(coord)]
def build_sites_markers(sites_with_live_alerts, dpt_code=None): """ This function reads the site markers by making the API, that contains all the information about the sites equipped with detection units. It then returns a dl.MarkerClusterGroup object that gathers all relevant site markers. NB: certain parts of the function, which we do not use at the moment and that were initially designed to bind the display of site markers to a click on the corresponding department, are commented for now but could prove useful later on. """ # Building alerts_markers objects and wraps them in a dl.LayerGroup object icon = { "iconUrl": '../assets/pyro_site_icon.png', "iconSize": [50, 50], # Size of the icon "iconAnchor": [25, 45], # Point of the icon which will correspond to marker's location "popupAnchor": [0, -20 ] # Point from which the popup should open relative to the iconAnchor } # We build a list of markers containing the info of each site/camera markers = [] for row in camera_positions: # We do not output a marker if the site is associated with a live alert being displayed if row['name'].replace('_', ' ').title() in sites_with_live_alerts: continue else: site_id = row['id'] lat = round(row['lat'], 4) lon = round(row['lon'], 4) site_name = row['name'].replace('_', ' ').title() markers.append( dl.Marker( id= f'site_{site_id}', # Necessary to set an id for each marker to receive callbacks position=(lat, lon), icon=icon, children=[ dl.Tooltip(site_name), dl.Popup([ html.H2(f'Site {site_name}'), html.P(f'Coordonnées : ({lat}, {lon})'), html. P(f"Nombre de caméras : {len(site_devices.get(row['name']))}" ) ]) ])) # We group all dl.Marker objects in a dl.MarkerClusterGroup object and return it return markers
def build_sites_markers(dpt_code=None): # As long as the user does not click on a department, dpt_code is None and we return no device # if not dpt_code: # return None # We read the csv file that locates the cameras and filter for the department of interest camera_positions = pd.read_csv( Path(__file__).parent.joinpath('data', 'cameras.csv'), ';') # camera_positions = camera_positions[camera_positions['Département'] == int(dpt_code)].copy() # Building alerts_markers objects and wraps them in a dl.LayerGroup object icon = { "iconUrl": '../assets/pyro_site_icon.png', "iconSize": [50, 50], # Size of the icon "iconAnchor": [25, 45], # Point of the icon which will correspond to marker's location "popupAnchor": [0, -20] } # Point from which the popup should open relative to the iconAnchor # We build a list of markers containing the info of each site/camera markers = [] for i, row in camera_positions.iterrows(): lat = row['Latitude'] lon = row['Longitude'] site_name = row['Tours'] nb_device = row['Nombres Devices'] markers.append( dl.Marker( id= f'site_{i}', # Necessary to set an id for each marker to reteive callbacks position=(lat, lon), icon=icon, children=[ dl.Tooltip(site_name), dl.Popup([ html.H2(f'Site {site_name}'), html.P(f'Coordonnées : ({lat}, {lon})'), html.P(f'Nombre de caméras : {nb_device}') ]) ])) # We group all dl.Marker objects in a dl.LayerGroup object markers_cluster = dl.MarkerClusterGroup(children=markers, id='sites_markers') return markers_cluster
def update_events(start_date, end_date, agregation_option,routes): # Events Layer Map df = df_events.copy() df = df[(df[agregation_option].isin(routes)) & (df['Reported Date'].between(start_date, end_date))] df['color'] = [select_df_color[agregation_option][r] for r in df[agregation_option]] map_events_children = [] for row in df.itertuples(): map_events_children.append(dl.Marker(position = [row.geometry.y, row.geometry.x], children = dl.Popup('Reported Date: {}'.format(row._1.date() ) ) ) ) return dl.LayerGroup(map_events_children),
def get_location_uncertainty_layer(eq_data, visible): """Return a map layer with uncertainties visualized for each data point. Keyword arguments: eq_data -- An Earthquake data object containing the data visible on the map visible -- A boolean indicating whether to display the uncertainties in location of each data point """ if eq_data.data.shape[0] == 0 or not visible: return dl.LayerGroup(id='location-uncertainties') location_uncertainties = eq_data.get_location_uncertainties() reset_data = eq_data.data.reset_index() uncertainties = [] if type(location_uncertainties) == int: uncertainties = [ dl.Circle(center=[quake['LATITUDE'], quake['LONGITUDE']], radius=location_uncertainties, color='black', fillOpacity=0, dashArray='5, 5', weight=1.5, children=[ dl.Popup(dcc.Markdown( list( map( lambda x: '**{}**: {} '.format( x.replace('[', r'\['), quake[x]), quake.keys()))), className='earthquake-popup') ]) for _, quake in reset_data.iterrows() ] else: uncertainties += [ dl.Polyline(positions=[[ quake['LATITUDE'], quake['LONGITUDE'] ], location_uncertainties[idx + direction * reset_data.shape[0]]], color='black', dashArray='5, 5', weight=1.5) for direction in range(4) for idx, quake in reset_data.iterrows() ] return dl.LayerGroup(id='location-uncertainties', children=uncertainties)
def build_sites_markers(dpt_code=None): """ This function reads the site markers by making the API, that contains all the information about the sites equipped with detection units. It then returns a dl.MarkerClusterGroup object that gathers all relevant site markers. NB: certain parts of the function, which we do not use at the moment and that were initially designed to bind the display of site markers to a click on the corresponding department, are commented for now but could prove useful later on. """ # As long as the user does not click on a department, dpt_code is None and we return no device # if not dpt_code: # return None # We filter for the department of interest # camera_positions = camera_positions[camera_positions['Département'] == int(dpt_code)].copy() # Building alerts_markers objects and wraps them in a dl.LayerGroup object icon = { "iconUrl": '../assets/pyro_site_icon.png', "iconSize": [50, 50], # Size of the icon "iconAnchor": [25, 45], # Point of the icon which will correspond to marker's location "popupAnchor": [0, -20] # Point from which the popup should open relative to the iconAnchor } # We build a list of markers containing the info of each site/camera markers = [] for row in camera_positions: site_id = row['id'] lat = row['lat'] lon = row['lon'] site_name = row['name'] # nb_device = row['Nombres Devices'] markers.append(dl.Marker(id=f'site_{site_id}', # Necessary to set an id for each marker to receive callbacks position=(lat, lon), icon=icon, children=[dl.Tooltip(site_name), dl.Popup([html.H2(f'Site {site_name}'), html.P(f'Coordonnées : ({lat}, {lon})'), html.P(f'Nombre de caméras : {4}')])])) # We group all dl.Marker objects in a dl.MarkerClusterGroup object and return it return dl.MarkerClusterGroup(children=markers, id='sites_markers')
def update_map(viewData, derived_virtual_selected_rows): """ functionality for updating map. map always shows location of the animal at top of table's current page """ dff = df if viewData is None else pd.DataFrame(viewData) selected_animal = None # if there are no selected rows yet, map default displays first animal of table's current page if not derived_virtual_selected_rows: selected_animal = dff.iloc[0] # else there is a selected row, map displays that animal else: selected_animal = dff.iloc[derived_virtual_selected_rows[0]] latitude = selected_animal[12] longitude = selected_animal[13] animal_breed = selected_animal[3] animal_name = selected_animal[8] return [ dl.Map( style={ 'width': '700px', 'height': '500px' }, center=[latitude, longitude], zoom=10, children=[ dl.TileLayer(id="base-layer-id"), # Marker with tool tip and popup dl.Marker( position=[latitude, longitude], children=[ # show breed of animal on hovering over marker dl.Tooltip(animal_breed), # show animal name on clicking marker dl.Popup([html.H1("Animal Name"), html.P(animal_name)]) ]) ]) ]
def plot_coordinate(value='11 Cadogan Gardens'): search_data = df[df['Hotel_Name'] == value] lat = search_data.lat.values[0] lng = search_data.lng.values[0] name = search_data.Hotel_Name.values[0] address_ = search_data.Hotel_Address.values[0] markers = [ dl.Marker( position=[lat, lng], children=[dl.Popup('Name: ' + name + ', Address: ' + address_, )]) ] return html.Div([ dl.Map([dl.TileLayer(), dl.LayerGroup(id="layer")] + [dl.LayerGroup(markers)], center=[lat, lng], zoom=14, id="map", style=MAP_STYLE), ]),
import dash_leaflet as dll import dash from dash.dependencies import Input, Output import dash_html_components as html app = dash.Dash(__name__) app.scripts.config.serve_locally = True app.css.config.serve_locally = True app.layout = html.Div([ dll.Map( id='leaflet-map', center=[51.505, -0.09], zoom=13, children=[ dll.TileLayer(id='tile-layer'), dll.Marker( position=[51.505, -0.09], children=[dll.Popup(children="Foo Bar")] ) ] ) ]) if __name__ == '__main__': app.run_server(debug=True)
def build_alerts_elements(img_url, alert_status, alert_metadata): # Fetching alert status and reusable metadata alert_lat = alert_metadata["lat"] alert_lon = alert_metadata["lon"] alert_id = str(alert_metadata["id"]) if alert_status == 1: # Building the button that allows users to zoom towards the alert marker alert_button = dbc.Button(children="Départ de feu, cliquez-ici !", color="danger", block=True, id='alert_button') # Building alerts_markers objects and wraps them in a dl.LayerGroup object icon = { "iconUrl": '../assets/pyro_alert_icon.png', "iconSize": [50, 50], # Size of the icon "iconAnchor": [ 25, 45 ], # Point of the icon which will correspond to marker's and popup's location "popupAnchor": [ 0, -20 ] # Point from which the popup should open relative to the iconAnchor } alerts_markers = [ dl.Marker( id="alert_marker_{}".format( alert_id), # Setting a unique id for each alerts_markers position=(alert_lat, alert_lon), icon=icon, children=[ dl.Popup([ html.H2("Alerte détectée"), html.P("Coordonées : {}, {} ".format( alert_lat, alert_lon)), html.Button( "Afficher les données de détection", id=("display_alert_frame_btn{}".format(alert_id) ), # Setting a unique btn id n_clicks=0, className="btn btn-danger"), # Adding an alert acknowledgement checkbox which has value False by default # And takes value True once checked dcc.Markdown("---"), html.Div( id='acknowledge_alert_div_{}'.format(alert_id), children=[ dbc.FormGroup([ dbc.Checkbox( id='acknowledge_alert_checkbox_{}'. format(alert_id), className="form-check-input"), dbc.Label( "Confirmer la prise en compte de l'alerte", html_for='acknowledge_alert_checkbox_{}' .format(alert_id), className="form-check-label") ], check=True, inline=True) ]) ]) ]) ] alerts_markers_layer = dl.LayerGroup(children=alerts_markers, id='alerts_markers') else: alert_button = "" alerts_markers_layer = "" return img_url, alert_button, alerts_markers_layer
def load_results(n_clicks, postal): #df = get_results('CCBDEV7') df = data if postal is not None: df = df[df.POSTAL.isin([postal])] #df[['ACCT_ID','PREM_ID','ETOR_NUM']] = df[['ACCT_ID','PREM_ID','ETOR_NUM']].astype('int64') #df[['PREMLAT','PREMLONG']] = df[['PREMLAT','PREMLONG']].astype(float) positions = df[['PREMLAT', 'PREMLONG']].values.tolist() premiseId = df[['PREM_ID']].values.tolist() accountId = df[['ACCT_ID']].values.tolist() etorNoList = df[['ETOR_NUM']].values.tolist() Row_list = [] # Iterate over each row for index, rows in df.iterrows(): # Create list for the current row my_list = [rows.PREMLAT, rows.PREMLONG] Row_list.append(my_list) marker = [] for row, premise, account, etorNo in zip(Row_list, premiseId, accountId, etorNoList): etor = int(''.join(map(str, etorNo))) if etor < 11: marker_temp = dl.Marker( position=row, icon={ "iconUrl": "/assets/smile3.png", "iconSize": [35, 35] }, children=[ dl.Tooltip("Premise - " + ' '.join(map(str, premise))), dl.Popup([ html.H1("Details"), html.P("Customer Outage Experience"), html.P("Location = " + ' '.join(map(str, row))), html.P("Premise Id = " + ' '.join(map(str, premise))), html.P("Account Id = " + ' '.join(map(str, account))), ]) ]) marker.append(marker_temp) elif etor > 10 and etor < 21: marker_temp = dl.Marker( position=row, icon={ "iconUrl": "/assets/sad.png", "iconSize": [35, 35] }, children=[ dl.Tooltip("Premise - " + ' '.join(map(str, premise))), dl.Popup([ html.H1("Details"), html.P("Customer Outage Experience"), html.P("Location = " + ' '.join(map(str, row))), html.P("Premise Id = " + ' '.join(map(str, premise))), html.P("Account Id = " + ' '.join(map(str, account))), ]) ]) marker.append(marker_temp) elif etor > 20: marker_temp = dl.Marker( position=row, icon={ "iconUrl": "/assets/angry.png", "iconSize": [35, 35] }, children=[ dl.Tooltip("Premise - " + ' '.join(map(str, premise))), dl.Popup([ html.H1("Details"), html.P("Customer Outage Experience"), html.P("Location = " + ' '.join(map(str, row))), html.P("Premise Id = " + ' '.join(map(str, premise))), html.P("Account Id = " + ' '.join(map(str, account))), ]) ]) marker.append(marker_temp) cluster = dl.MarkerClusterGroup( id="markers", children=marker, options={"polygonOptions": { "color": "red" }}) result = [ dl.TileLayer(url="https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"), dl.LocateControl( options={'locateOptions': { 'enableHighAccuracy': True }}), cluster ] return [result]
def render_example1(): comment = """ Marker with default icon, marker with custom icon, circle marker (fixed pixel radius), circle (fixed physical radius), polyline, polygon and rectangle, all supporting tooltips and popups. """ return [ html.H1("Example 1: Basic components"), html.P(comment), dl.Map( id=MAP_ID, style={ 'width': '1000px', 'height': '500px' }, center=[56.05, 10.25], zoom=10, children=[ dl.TileLayer(id=BASE_LAYER_ID), # Marker with tool tip and popup. dl.Marker(position=[56, 9.8], children=[ dl.Tooltip("Marker tooltip"), dl.Popup([ html.H1("Marker popup"), html.P("with inline html") ]) ]), # Marker with custom icon. dl.Marker(position=[55.94, 9.96], icon={ "iconUrl": "/assets/149059.svg", "iconSize": [25, 25] }, children=[dl.Tooltip("Marker with custom icon")]), # Circle marker (with fixed radius in pixel). dl.CircleMarker(center=[56.05, 10.15], radius=20, children=[dl.Popup('Circle marker, 20px')]), # Circle with fixed radius in meters. dl.Circle(center=[56.145, 10.21], radius=2000, color='rgb(255,128,0)', children=[dl.Tooltip('Circle, 2km radius')]), # Polyline marker. dl.Polyline(id='polyline', positions=[[56.06, 10.0], [56.056, 10.01], [56.064, 10.028], [56.0523, 10.0717], [56.044, 10.073]], children=[dl.Tooltip('Polyline')]), # Polygon marker. dl.Polygon(id='polygon', positions=[[56.013, 9.84], [56.0544, 9.939], [56.003, 10.001]], children=[dl.Tooltip('Polygon')]), # Rectangle marker. dl.Rectangle(id='rectangle', bounds=[[55.9, 10.2], [56.0, 10.5]], children=[dl.Tooltip('Rectangle')]) ]), dcc.RadioItems(id=BASE_LAYER_DROPDOWN_ID, options=[{ "label": i, "value": mapbox_url.format(id=i, access_token=mapbox_token) } for i in mapbox_ids], labelStyle={'display': 'inline-block'}, value=mapbox_url.format(id="light-v9", access_token=mapbox_token)), html.P("Coordinate (click on map):"), html.Div(id=COORDINATE_CLICK_ID), ]
def build_alerts_elements(img_url, alert_status, alert_metadata, map_style): """ This function is used in the main.py file to create alerts-related elements such as the alert button (banner) or the alert markers on the map. It takes as arguments: - 'img_url': the URL address of the alert frame to be displayed on the left of the map; - 'alert_status': a binary variable indicating whether or not there is an ongoing alert to display; - 'alert_metadata': a dictionary containing; - 'map_style': the type of map in place, either 'alerts' or 'risks'. All these inputs are instantiated in the main.py file via a call to the API. In the base case, the function returns: - the URL address of the image to be displayed on the left of the map; - the alert button (banner above the map); - the alert markers displayed on the map. But if the style of map in place is 'risks', we don't want to display neither the alert markers. So in this case, the third output of the function is a void string. """ # Fetching alert status and reusable metadata alert_lat = alert_metadata["lat"] alert_lon = alert_metadata["lon"] alert_id = str(alert_metadata["id"]) if alert_status == 1: # Building the button that allows users to zoom towards the alert marker alert_button = dbc.Button( children="Départ de feu, cliquez-ici !", color="danger", block=True, id=f'alert_button_{map_style}' ) # Format of the alert marker icon icon = { "iconUrl": '../assets/pyro_alert_icon.png', "iconSize": [50, 50], # Size of the icon "iconAnchor": [25, 45], # Point of the icon which will correspond to marker's and popup's location "popupAnchor": [0, -20] # Point from which the popup should open relative to the iconAnchor } # Building the list of alert markers to be displayed alerts_markers = [dl.Marker( id="alert_marker_{}".format(alert_id), # Setting a unique id for each alert marker position=(alert_lat, alert_lon), icon=icon, children=[dl.Popup( [ html.H2("Alerte détectée"), html.P("Coordonées : {}, {} ".format(alert_lat, alert_lon)), # Button allowing the user to check the detection data after clicking on an alert marker html.Button("Afficher les données de détection", id=("display_alert_frame_btn{}".format(alert_id)), # Setting a unique btn id n_clicks=0, className="btn btn-danger"), # Adding a separator between the button and the checkbow dcc.Markdown("---"), # Alert acknowledgement checkbox with default value False and value True once checked html.Div(id='acknowledge_alert_div_{}'.format(alert_id), children=[ dbc.FormGroup([dbc.Checkbox(id='acknowledge_alert_checkbox_{}'.format(alert_id), className="form-check-input"), dbc.Label("Confirmer la prise en compte de l'alerte", html_for='acknowledge_alert_checkbox_{}'.format(alert_id), className="form-check-label")], check=True, inline=True)]) ])])] # Wrapping all markers in the list into a dl.LayerGroup object alerts_markers_layer = dl.LayerGroup(children=alerts_markers, id='alerts_markers') else: alert_button = "" alerts_markers_layer = "" if map_style == 'risks': alerts_markers_layer = '' return img_url, alert_button, alerts_markers_layer