Exemplo n.º 1
0
def map_click(click_lat_lng, business_type, transportation_type, time_limit):
    if click_lat_lng is None:
        raise PreventUpdate
    if business_type is None:
        raise PreventUpdate
    if transportation_type is None:
        raise PreventUpdate
    if time_limit is None:
        raise PreventUpdate

    time_limit = time_limit * 60
    print(click_lat_lng, time_limit, transportation_type, business_type)
    df = hfa.get_data_around_point(click_lat_lng, time_limit,
                                   transportation_type, business_type)
    if df is None:
        raise PreventUpdate
    table = make_dash_table(df)
    center_marker = [
        dl.Marker(position=click_lat_lng, children=dl.Tooltip("You are here"))
    ]
    df = df.sort_values(by="travel")
    markers = [
        dl.Marker(
            position=row[1][["latitude", "longitude"]].values,
            children=dl.Tooltip(row[1]["name"]),
        ) for row in df.iterrows()
    ]

    return table, center_marker, markers
Exemplo n.º 2
0
def map_click(clicks, click_lat_lng, search_input):

    changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
    empty = search_input == None

    if not empty and 'search-button' in changed_id:

        location = geolocator.geocode(search_input)
        if location == None:
            marker, location_string = None, 'Failed to find location based on search input'
        else:
            search_lat_long = [location.latitude, location.longitude]
            location_string = "Selected location: ({:.3f}, {:.3f})".format(
                *search_lat_long)
            marker = [
                dl.Marker(position=search_lat_long,
                          children=dl.Tooltip(location_string))
            ]

    elif not click_lat_lng == None:

        location_string = "Selected location: ({:.3f}, {:.3f})".format(
            *click_lat_lng)
        marker = [
            dl.Marker(position=click_lat_lng,
                      children=dl.Tooltip(location_string))
        ]

    return marker, location_string
Exemplo n.º 3
0
def map_click(coordinates, month):
    global last_valid

    if coordinates == None:
        coordinates = last_valid
    else:
        last_valid = coordinates

    if coordinates[0] < 32.534156 or coordinates[0] > 42.009518 or coordinates[1] <-124.409591 or coordinates[1] > -114.131211:
        return [dl.Marker(position=coordinates, children=dl.Tooltip("({:.3f}, {:.3f})".format(*coordinates))), 100, '#666']
    val = utils.pred_func_geo(geo_all_data, geo_county_coordinates, geo_model, geo_encodings, geo_extreames, coordinates[0], coordinates[1], month)
    return [dl.Marker(position=coordinates, children=dl.Tooltip("({:.3f}, {:.3f})".format(*coordinates))), 100*val, '#FF3300']
Exemplo n.º 4
0
 def create_map(self):
     self.ns = Namespace("dlx", "scatter")
     self.markers = [
         dl.Marker(
             dl.Tooltip(f"({pos[0]}, {pos[1]}), time:{self.times[i]}"),
             position=pos,
             id="marker{}".format(i))
         for i, pos in enumerate(self.locations)
     ]
     self.cluster = dl.MarkerClusterGroup(
         id="markers",
         children=self.markers,
         options={"polygonOptions": {
             "color": "red"
         }})
     self.app = dash.Dash(external_scripts=[
         "https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.1.0/chroma.min.js"
     ])
     self.polyline = dl.Polyline(positions=self.locations)
     self.app.layout = html.Div([
         dl.Map([
             dl.TileLayer(), self.cluster, self.polyline,
             dl.LayerGroup(id="layer")
         ],
                id="map",
                center=(40.4259, -86.9081),
                zoom=8,
                style={'height': '100vh'}),
     ])
Exemplo n.º 5
0
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])
                              ])
                          ])
            ])
    ]
Exemplo n.º 6
0
def generate_map_plot(df):
    if df is not None:
        lons = df.lons.values
        lats = df.lats.values
        trajectory = np.vstack([lats, lons]).T.tolist()
        start_point = df.source.values[0]
        end_point = df.destination.values[0]
        zoom, center = zoom_center(lons, lats, width_to_height=8)

        fig = [
            dl.Map(
                [
                    dl.TileLayer(url=mapURL,
                                 attribution=attribution,
                                 tileSize=512,
                                 zoomOffset=-1),
                    dl.LayerGroup(id="layer"),
                    dl.WMSTileLayer(url="https://maps.dwd.de/geoserver/ows?",
                                    layers="dwd:RX-Produkt",
                                    format="image/png",
                                    transparent=True,
                                    opacity=0.7),
                    dl.LocateControl(options={
                        'locateOptions': {
                            'enableHighAccuracy': True
                        }
                    }),
                    dl.Polyline(positions=trajectory),
                    dl.Marker(position=trajectory[0],
                              children=dl.Tooltip(start_point)),
                    dl.Marker(position=trajectory[-1],
                              children=dl.Tooltip(end_point))
                ],
                center=[center['lat'], center['lon']],
                zoom=zoom,
                style={
                    'width': '100%',
                    'height': '45vh',
                    'margin': "auto",
                    "display": "block"
                },
                id='map')
        ]
    else:  # make an empty map
        fig = make_empty_map()

    return fig
Exemplo n.º 7
0
def update_output(value):
    if 'stations' in value:
        return [
            dl.Marker(position=[row['lat'], row['lon']],
                      children=dl.Tooltip(row['location']))
            for i, row in stations_uganda.iterrows()
        ]
    else:
        return None
Exemplo n.º 8
0
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')
Exemplo n.º 9
0
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
Exemplo n.º 10
0
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
Exemplo n.º 11
0
    def update_metrics(a):

        locations.append([locations_base[a][0], locations_base[a][1]])
        if (len(locations) >= 100):
            locations.pop(0)
        new_markers = [
            dl.Marker(dl.Tooltip(f"({pos[0]}, {pos[1]}), time:{times[i]}"),
                      position=pos,
                      id="marker{}".format(i))
            for i, pos in enumerate(locations)
        ]
        return new_markers
Exemplo n.º 12
0
 def geotiff_marker(x):
     if x is not None:
         lat, lon, val = x
         return dl.Marker(position=[lat, lon],
                          icon={
                              "iconUrl": "/assets/thermometer.png",
                              "iconSize": [40, 40],
                              "iconAnchor": [20, 36]
                          },
                          children=[dl.Tooltip('{:.1f}°C'.format(val))])
     else:
         return None
Exemplo n.º 13
0
 def geotiff_marker(x):
     if x is not None:
         lat, lon, val = x
         return dl.Marker(
             position=[lat, lon],
             icon={
                 "iconUrl":
                 "https://github.com/thedirtyfew/dash-leaflet/tree/master/assets/thermometer.png",
                 "iconSize": [40, 40],
                 "iconAnchor": [20, 36]
             },
             children=[dl.Tooltip('{:.1f}°C'.format(val))])
     else:
         return None
Exemplo n.º 14
0
def generate_map_plot(data):
    if data is not None:
        start_point = data['STATION_NAME'].item()
        point = [data['LAT'].item(), data['LON'].item()]

        fig = [
            dl.Map(
                [
                    dl.TileLayer(url=mapURL,
                                 attribution=attribution,
                                 tileSize=512,
                                 zoomOffset=-1),
                    dl.LayerGroup(id="layer"),
                    dl.WMSTileLayer(url="https://maps.dwd.de/geoserver/ows?",
                                    layers="dwd:SAT_WELT_KOMPOSIT",
                                    format="image/png",
                                    transparent=True,
                                    opacity=0.7,
                                    version='1.3.0',
                                    detectRetina=True),
                    dl.WMSTileLayer(url="https://maps.dwd.de/geoserver/ows?",
                                    layers="dwd:SAT_EU_RGB",
                                    format="image/png",
                                    transparent=True,
                                    opacity=0.7,
                                    version='1.3.0',
                                    detectRetina=True),
                    dl.LocateControl(options={
                        'locateOptions': {
                            'enableHighAccuracy': True
                        }
                    }),
                    dl.Marker(position=point,
                              children=dl.Tooltip(start_point)),
                ],
                center=point,
                zoom=4,
                style={
                    'width': '100%',
                    'height': '35vh',
                    'margin': "auto",
                    "display": "block"
                },
                id='map')
        ]
    else:  # make an empty map
        fig = make_empty_map()

    return fig
Exemplo n.º 15
0
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
Exemplo n.º 16
0
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),
Exemplo n.º 17
0
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')
Exemplo n.º 18
0
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)])
                    ])
            ])
    ]
Exemplo n.º 19
0
    def get_map_from_table(data, children):
        """Adds landmark location pin on map from landmark table

        Args:
            data (list): data of landmark table
            children (list): current map children

        Returns:
            (list): updated map children
        """
        children = [children[0]] + [
            dl.Marker(position=[landmark['lat'], landmark['lon']],
                      icon={
                          'iconUrl': '/assets/map-icon.svg',
                          'iconSize': [38, 100],
                          'iconAnchor': [19, 70]
                      },
                      children=[
                          dl.Tooltip(landmark['Landmark']),
                      ]) for landmark in data
        ]
        return children
Exemplo n.º 20
0
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),
    ]),
Exemplo n.º 21
0
def update_plots(click_lat_lng, average_speed, trip_time):
    global census_data, cudf_nodes, cudf_edges
    colorscale_name = 'Blugrn'
    t0 = time.time()

    if click_lat_lng is not None:
        lat, lon = click_lat_lng
        marker = dl.Marker(position=click_lat_lng,
                           children=dl.Tooltip(
                               "({:.3f}, {:.3f})".format(*click_lat_lng)))

        polygons, df, times = get_nearest_polygons_from_selected_point(
            lat, lon, average_speed, trip_time, cudf_nodes, cudf_edges,
            census_data)
        polygon_data = json.loads(polygons.to_json())
    else:
        marker, polygon_data, df = None, None, None
        times = [0, 0, 0, 0]

    if df is None:
        len_df = len(census_data)
        figures = delayed(build_updated_figures)(census_data,
                                                 colorscale_name).compute()

    else:
        len_df = len(df)
        figures = build_updated_figures(df, colorscale_name)

    (education_histogram, income_histogram, cow_histogram,
     age_histogram) = figures

    barchart_config = {
        'displayModeBar':
        True,
        'modeBarButtonsToRemove': [
            'zoom2d', 'pan2d', 'select2d', 'lasso2d', 'zoomIn2d', 'zoomOut2d',
            'resetScale2d', 'hoverClosestCartesian', 'hoverCompareCartesian',
            'toggleSpikelines'
        ]
    }
    n_selected_indicator = {
        'data': [{
            'domain': {
                'x': [0, 1],
                'y': [0, 0.5]
            },
            'type': 'indicator',
            'value': len_df,
            'number': {
                'font': {
                    'color': text_color,
                    'size': '24px'
                },
                "valueformat": ","
            }
        }],
        'layout': {
            'template': template,
            'height': row_heights[0] - 30,
            'margin': {
                'l': 10,
                'r': 10,
                't': 10,
                'b': 10
            }
        }
    }
    compute_time = round(time.time() - t0, 4)
    print(f"Update time: {compute_time}")
    np.append(times, [compute_time - np.sum(times)])
    query_time_stacked_bar = get_stacked_bar(
        np.append(times, [compute_time - np.sum(times)]), colorscale_name)

    return (n_selected_indicator, query_time_stacked_bar, marker, polygon_data,
            education_histogram, income_histogram, cow_histogram,
            age_histogram, barchart_config, barchart_config, barchart_config,
            barchart_config)
Exemplo n.º 22
0
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),
    ]
Exemplo n.º 23
0
import dash
from dash.dependencies import Output
import dash_leaflet as dl
import pandas
import dash_html_components as html
from dash.dependencies import Input, Output
import numpy as np

csv = pandas.read_csv('./ASC2021_draft.csv', names=[0, 1])
csv_list = csv.values.tolist()
markers = [
    dl.Marker(position=pos, id="marker{}".format(i), draggable=True)
    for i, pos in enumerate(csv_list)
]
app = dash.Dash()

app.layout = html.Div([
    html.Div(dl.Map(
        [dl.TileLayer(), dl.LayerGroup(id="layer"), *markers],
        zoom=4,
        center=(csv_list[0][0], csv_list[0][1])),
             style={
                 'width': '60%',
                 'height': '50vh',
                 'margin': "auto",
                 "display": "block"
             }),
    html.Div(id='clickdata')
])

Exemplo n.º 24
0
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)
Exemplo n.º 25
0
def build_alerts_elements(images_url_live_alerts, live_alerts, 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:

    - 'images_url_live_alerts': url dict with live_alerts urls having event_id keys
    - 'live_alerts': json containing live_alerts data
    - 'map_style': the type of map in place, either 'alerts' or 'risks'.

    All these inputs are instantiated in the main.py file via a POST from the API.

    In the base case, the function returns:

    - the urls addresses of the image to be displayed on the left of the map;

    - the new_alert_button;

    - the alert markers displayed on the map;

    - new navbar_color as in alert mode;

    - new navbar title;

    - a list of individual storage components, one for each alert/event to be displayed, that give the URL addresses of
    the corresponding frames.

    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.
    """

    # Changing the navabar color and title
    navbar_color = "#f34848"
    navbar_title = "Départs de feux détectés"

    # 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 = []
    live_alerts_check = json.loads(live_alerts)

    if ((isinstance(live_alerts_check, dict)
         and 'status' in live_alerts_check.keys()
         and live_alerts_check['status'] == 'never_loaded_alerts_data')
            or not live_alerts_check):
        # When there is no live alert to display, we return a alert header button that will remain hidden
        hidden_header_alert_button = html.Div(
            html.Button(id=f'alert_button_{map_style}'),
            style={'display': 'none'})

        # This is to ensure that the "click_new_alerts_button" callback gets triggered with n_clicks=0 and hides the
        # blank user selection area, letting the map take the full width of the screen

        # (It can be interesting to test returning [] instead of [hidden_header_alert_button] and erase all alerts one
        # by one if explanations are unclear)

        return [hidden_header_alert_button
                ], [], '#054546', 'Surveillez les départs de feux'

    else:
        all_alerts = pd.read_json(live_alerts)

    all_events = all_alerts.drop_duplicates(
        ['id', 'event_id']).groupby('event_id').head(1)  # Get unique events
    for _, row in all_events.iterrows():
        alert_id = str(row['event_id'])
        alert_lat = row['lat']
        alert_lon = row['lon']

        alerts_markers.append(
            dl.Marker(
                id={
                    'type': 'alert_marker',
                    'index': alert_id
                },  # Setting a unique id for each alert marker
                position=(alert_lat, alert_lon),
                icon=icon))

    # Wrapping all markers in the list into a dl.LayerGroup object
    alerts_markers_layer = dl.LayerGroup(children=alerts_markers,
                                         id='alerts_markers')

    # Building the alerts notification btn
    nb_alerts = len(all_events)  # Number of unique events
    alert_button = html.Div(dbc.Button(
        "Nouvelles alertes | {}".format(nb_alerts),
        className="btn-header-alerts"),
                            id=f'alert_button_{map_style}',
                            style={
                                'position': 'absolute',
                                'top': '10px',
                                'right': '30px',
                                'z-index': '1000'
                            })

    individual_alert_frame_placeholder_children = []
    for event_id, frame_url_list in images_url_live_alerts.items():

        individual_alert_frame_placeholder_children.append(
            html.Div(id={
                'type': 'individual_alert_frame_storage',
                'index': str(event_id)
            },
                     children=frame_url_list,
                     style={'display': 'none'}))

    return [alert_button, alerts_markers_layer, navbar_color, navbar_title]
Exemplo n.º 26
0
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]
Exemplo n.º 27
0
</html>""",
)
server = app.server

starting_position = (
    float(city_lookup.iloc[[starting_city_id]]["lat"]),
    float(city_lookup.iloc[[starting_city_id]]["lng"]),
)

print("starting_position", starting_position)

markers = [
    dl.Marker(
        dl.Tooltip(city_row.city + ", " + city_row.country),
        position=(
            float(city_row["lat"]),
            float(city_row["lng"]),
        ),
        id="city_id_" + str(i),
    ) for i, city_row in city_lookup.iterrows()
]
cluster = dl.MarkerClusterGroup(id="markers",
                                children=markers,
                                options={"polygonOptions": {
                                    "color": "red"
                                }})

app.layout = html.Div([
    # represents the URL bar, doesn't render anything
    dcc.Location(id="url", refresh=False),
    # dcc.Link(html.H2(children=title), href="/"),
    # html.P("Select a city on the map to load temperature history"),
Exemplo n.º 28
0
def map_click(click_lat_lng, steps, min_perc):
    lat_min = np.floor(click_lat_lng[0] * 10) / 10
    lat_max = np.ceil(click_lat_lng[0] * 10) / 10
    lon_min = np.floor(click_lat_lng[1] * 10) / 10
    lon_max = np.ceil(click_lat_lng[1] * 10) / 10

    poi_start = str(round(
        (lat_min + 0.05), 2)) + '_' + str(round((lon_min + 0.05), 2))
    df_output = select_neighbours_percentages(poi_start=poi_start,
                                              steps=steps,
                                              limit=int(min_perc))

    # All points of interest (cells with % larger than minimal percentage)
    new_pois = df_output.poi.unique().tolist()
    # Add column with lat and lon to df_selection
    lat = [x.split('_')[0] for x in new_pois]
    lon = [x.split('_')[1] for x in new_pois]
    df_pois = pd.DataFrame(columns=["lat", "lon"],
                           data=np.column_stack((lat, lon)))

    # Get disctricts connected to POIS
    districts_df = get_districts(df=df_pois, districts=admin_boundaries)
    if len(districts_df) > 0:
        districts_return = 'The connected disctricts are: ' + str(
            districts_df).strip('[]')
    else:
        districts_return = 'No connected districts found.'

    # All neighbours
    new_nbrs = df_output.neighbour.unique().tolist()
    # Add column with lat and lon to df_selection
    lat = [x.split('_')[0] for x in new_nbrs]
    lon = [x.split('_')[1] for x in new_nbrs]
    perc = [str(round(x)) for x in df_output.percentage.tolist()]
    df_nbr = pd.DataFrame(columns=["lat_lon", "lat", "lon", "perc"],
                          data=np.column_stack((new_nbrs, lat, lon, perc)))

    # Add number of pois
    df_nr_pois = df_output[['poi', 'nbr_poi']].drop_duplicates()
    df_nr_pois['nbr_poi'] = 'order nr: ' + df_nr_pois['nbr_poi'].astype(
        int).astype(str)
    df_nbr = df_nbr.merge(df_nr_pois,
                          how='left',
                          left_on='lat_lon',
                          right_on='poi').drop(['poi'], axis=1)
    df_nbr = df_nbr.fillna('')

    # Create: the selected colored path of POIs and their neighbours
    return [
        dl.Marker(
            position=click_lat_lng,
            children=dl.Tooltip('start ' +
                                "({:.2f}, {:.2f})".format(*click_lat_lng)))
    ], [
        dl.Rectangle(bounds=[[
            round(float(row['lat']) - 0.05, 2),
            round(float(row['lon']) - 0.05, 2)
        ],
                             [
                                 round(float(row['lat']) + 0.05, 2),
                                 round(float(row['lon']) + 0.05, 2)
                             ]],
                     stroke=False,
                     fillColor=get_color(float(row['perc'])),
                     weight=1,
                     opacity=1,
                     fillOpacity=.7,
                     children=dl.Tooltip(row['perc'] + '%   ' +
                                         row['nbr_poi']))
        for i, row in df_nbr.iterrows()
    ], [
        dl.Rectangle(bounds=[[
            round(float(row['lat']) - 0.05, 2),
            round(float(row['lon']) - 0.05, 2)
        ],
                             [
                                 round(float(row['lat']) + 0.05, 2),
                                 round(float(row['lon']) + 0.05, 2)
                             ]],
                     fill=False,
                     opacity=.65,
                     color='blue') for i, row in df_pois.iterrows()
    ], districts_return
Exemplo n.º 29
0
def render_map(show_labels):
    show_labels = 'show-all-labels' in show_labels
    simplify = False
    nodes = []
    links = []
    lats = []
    lons = []
    tt_paths = {}
    for i, (abbr, full_name) in enumerate(BASINS.items()):
        oa_network_path = '../openagua_schematics/{} River.json'.format(
            full_name)
        if not os.path.exists(oa_network_path):
            continue
        with open(oa_network_path) as f:
            oa_network = json.load(f)
        pywr_model_path = '../{}/temp/pywr_model_Livneh_simplified.json'.format(
            full_name.replace(' ', '_').lower())
        if not os.path.exists(pywr_model_path):
            continue
        with open(pywr_model_path) as f:
            pywr_network = json.load(f)

        net = oa_network['network']
        tmpl = oa_network['template']
        node_lookup = {n['name']: n for n in net['nodes']}

        if i == 0:
            for tt in tmpl['templatetypes']:
                tt_name = tt['name']
                tt_svg = tt['layout'].get('svg')
                if not tt_svg:
                    continue
                tt_path = './icons/{}.svg'.format(tt_name.replace(' ', '_'))
                with open(os.path.join('./assets', tt_path), 'w') as f:
                    f.write(tt_svg)
                tt_paths[tt['name']] = tt_path

        if simplify:
            for n in pywr_network['nodes']:
                if n['name'] not in node_lookup:
                    continue
                node = node_lookup[n['name']]
                lat, lon = float(node['y']), float(node['x'])
                lats.append(lat)
                lons.append(lon)
                nodes.append(leaflet.Marker(position=[lat, lon]))

            for n1, n2 in pywr_network['edges']:
                if n1 not in node_lookup or n2 not in node_lookup:
                    continue
                node1 = node_lookup[n1]
                node2 = node_lookup[n2]
                lat1, lon1 = float(node1['y']), float(node1['x'])
                lat2, lon2 = float(node2['y']), float(node2['x'])
                positions = [[lat1, lon1], [lat2, lon2]]
                links.append(leaflet.Polyline(positions=positions))
        else:
            for node in net['nodes']:
                lat, lon = float(node['y']), float(node['x'])
                tt = [
                    t for t in node['types'] if t['template_id'] == tmpl['id']
                ][-1]

                tt_path = tt_paths.get(tt['name'])
                kwargs = {}
                if tt_path:
                    if tt['name'].lower(
                    ) == 'junction' or 'gauge' in tt['name'].lower():
                        size = 12
                    else:
                        size = 24
                    kwargs.update(icon=dict(iconUrl=app.get_asset_url(tt_path),
                                            iconSize=[size, size],
                                            iconAnchor=[size / 2, size / 2]))
                nodes.append(leaflet.Marker(position=[lat, lon], **kwargs))
                lats.append(lat)
                lons.append(lon)
            for link in net['links']:
                coords = link['layout']['geojson']['geometry']['coordinates']
                lons_, lats_ = zip(*coords)
                positions = list(zip(*[lats_, lons_]))
                tt = [
                    t for t in link['types'] if t['template_id'] == tmpl['id']
                ][-1]
                linestyle = tt['layout'].get('linestyle')
                if type(linestyle) == str:
                    try:
                        linestyle = json.loads(linestyle)
                    except:
                        linestyle = {}
                links.append(leaflet.Polyline(positions=positions,
                                              **linestyle))

    clat = (min(lats) + max(lats)) / 2
    clon = (min(lons) + max(lons)) / 2

    return [
        leaflet.Map(
            style={
                'width': '100%',
                'height': '100%'
            },
            center=[clat, clon],
            zoom=9,
            children=[
                leaflet.TileLayer(
                    url="https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"),
                leaflet.LayerGroup(children=nodes + links)
            ])
    ]
Exemplo n.º 30
0
def map_click(dbl_click_lat_lng):
    click_positions.append(dbl_click_lat_lng)
    print(click_positions[-2:])
    popup = "Start ({:.3f}, {:.3f})".format(*dbl_click_lat_lng)
    return [dl.Marker(position=dbl_click_lat_lng, children=dl.Tooltip(popup))]