示例#1
0
    def show_stations_on_map(self,list_inc,list_process,list_filters,
     opt_params):
        """ Returns an interactive map of source and stations, use only in 
        Jupyter Notebooks.  

        Inputs:
            | list_inc: list of incidents
            | list_process: list of processes, one list per incident
            | list filters: list of filters defined for stations
            | opt_params: optional parameters (dictionary)

        Optional parameters:

        """
                
        records = self._extract_records(list_inc, list_process, list_filters)

        if not records:
            LOGGER.warning("There are no records to satisfy the provided"
             " filters.")
            return

        m = Map(
            basemap=basemap_to_tiles(basemaps.Esri.WorldImagery, "2020-04-08"),
            center = (Station.pr_source_loc[0],Station.pr_source_loc[1]),
            zoom = 8,
            close_popup_on_click=True
        )

        for i in records:
            if not i[0]:
                continue
            lat = i[0].station.lat
            lon = i[0].station.lon
            marker = Marker(location=(lat, lon), draggable=False,
             icon=AwesomeIcon(name="map-pin", marker_color='green',
             icon_color='darkgreen'), opacity=0.8)
            m.add_layer(marker)
            message = HTML()
            message.value = i[0].station.inc_st_name[list_inc[0]]
            marker.popup = message

        m.add_layer(Marker(icon=AwesomeIcon(name="star",
         marker_color='red', icon_color='darkred'),
         location=(Station.pr_source_loc[0],Station.pr_source_loc[1]),
         draggable=False))
        
        return m
示例#2
0
 def layer(self):
     icon = AwesomeIcon(name='camera',
                        marker_color='blue',
                        icon_color='white')
     return Marker(icon=icon,
                   location=(self.location.latitude,
                             self.location.longitude),
                   draggable=False)
示例#3
0
 def _addControls(self):
     # Add Controls
     self._m.add_control(
         MeasureControl(position='bottomleft',
                        active_color='orange',
                        primary_length_unit='kilometers'))
     self._m.add_control(FullScreenControl())
     self._m.add_control(ScaleControl(position='bottomleft'))
     searchMarker = Marker(icon=AwesomeIcon(
         name="check", marker_color='green', icon_color='darkred'))
     self._m.add_control(
         SearchControl(
             position="topleft",
             url=
             'https://nominatim.openstreetmap.org/search?format=json&q={s}',
             zoom=self._zoom,
             marker=searchMarker))
示例#4
0
def Give_Colored_Marker(df, color='blue', type='d'):
    if type == 'b':
        name = 'fa-podcast'
    elif type == 'd':
        name = 'fa-user-circle-o'
    else:
        name = 'fa-user-circle-o'

    icon1 = AwesomeIcon(name=name, marker_color=color, spin=False)

    markers = []
    for i in df.index:
        x = df.loc[i][df.columns[0]]
        y = df.loc[i][df.columns[1]]
        name = str(i)
        markers.append(
            Marker(icon=icon1, location=(x, y), draggable=False, title=name))

    return markers
示例#5
0
文件: vgan.py 项目: cyhsu/vgan
def createLeafletMarker(m, mission, MapGliderLocation, popup=None):
    icon1 = AwesomeIcon(name='paper-plane-o',
                        marker_color='red',
                        icono_color='black',
                        icon_size=(2, 2),
                        spin=False)

    marker = Marker(
        icon=icon1,
        name=mission,
        location=(MapGliderLocation[-1][0], MapGliderLocation[-1][1] - 0.001),
        draggable=False,
        opacity=0.3,
        rise_on_hover=True,
    )
    if popup:
        marker.popup = widgets.HTML('<h1><u>{}</u></h1>'.format(mission))
    m.add_layer(marker)
    return m
示例#6
0
def theis_fun():
    center = [-43.51876443245584, 172.66858981519297]
    m = GroundwaterMap(basemap=basemaps.Esri.WorldImagery,
                       center=center,
                       zoom=13)
    icon = AwesomeIcon(name='fa-tint',
                       marker_color='green',
                       icon_color='black',
                       spin=False)
    m.add_well([-43.5187, 172.6685], icon=icon)
    Q = FloatSlider(value=25,
                    description=r'$Q$ [L/s]',
                    min=0,
                    max=100,
                    step=5,
                    continuous_update=False,
                    layout=Layout(max_width='230px'),
                    style={'description_width': '60px'})
    m.configure(widgets={'Q0': Q}, func=partial(m.superposition, 0.025))
    return VBox([m, Q])
示例#7
0
def superposition_fun(T=0.025):
    center = [-43.51876443245584, 172.66858981519297]
    m = GroundwaterMap(basemap=basemaps.Esri.WorldImagery,
                       center=center,
                       zoom=13)
    Qs = []
    bs = []
    for c in ['green', 'lightblue', 'red', 'pink']:
        icon = AwesomeIcon(name='fa-tint',
                           marker_color=c,
                           icon_color='black',
                           spin=False)
        m.add_well([
            -43.51876443245584 + (random() - 0.5) * 0.01, 172.66858981519297 +
            (random() - 0.5) * 0.01
        ],
                   icon=icon)
        Q = FloatSlider(value=10,
                        description=r'$Q$ [L/s]',
                        min=0,
                        max=40,
                        step=5,
                        continuous_update=False,
                        layout=Layout(max_width='230px'),
                        style={'description_width': '60px'})
        b = Button(disabled=False,
                   icon='fa-tint',
                   layout=Layout(max_width='230px'))
        b.style.button_color = c
        Qs.append(Q)
        bs.append(b)

    m.configure(widgets=dict([('Q{:d}'.format(i), Q)
                              for i, Q in enumerate(Qs)]),
                func=partial(m.superposition, T))
    return VBox([m, HBox([VBox([b, Q]) for Q, b in zip(Qs, bs)])])
示例#8
0
    def __init__(self):
        self.out = widgets.Output(layout={'border': '1px solid black'})
        self.iceflow = IceflowClient()
        self.last_orders = None
        self.current_projection = 'north'
        self.clear = True
        self.controls = []
        self.credentials = None
        self.start_date = datetime(1993, 1, 1)
        self.end_date = datetime.now()
        slider_dates = [(date.strftime(' %Y-%m-%d '), date) for date in
                        pd.date_range(datetime(1993, 1, 1),
                                      datetime.now(),
                                      freq='D')]
        slider_index = (0, len(slider_dates) - 1)

        self.username = widgets.Text(
            value='',
            description='User:'******'Your NASA EarthData username ',
            disabled=False
        )
        self.password = widgets.Password(
            value='',
            placeholder='Enter password',
            description='Password:'******'',
            description='Email:',
            placeholder='Your EarthData e-mail',
            disabled=False
        )
        self.credentials_button = widgets.Button(description='Set Credentials', )
        self.projection = widgets.Dropdown(
            options=['global', 'south', 'north'],
            description='Hemisphere:',
            disabled=False,
            value='north'
        )
        self.dataset = widgets.SelectMultiple(
            options=['ATM1B', 'GLAH06', 'ILVIS2'],
            value=['ATM1B'],
            rows=4,
            description='Datasets',
            disabled=False
        )
        self.itrf = widgets.Dropdown(
            options=[None, 'ITRF2000', 'ITRF2008', 'ITRF2014'],
            disabled=False,
            description='ITRF:',
            layout={'width': 'max-content',
                    'display': 'flex',
                    'description_width': 'initial'}
        )
        self.epoch = widgets.Text(
            value='',
            description='Epoch:',
            placeholder='i.e. 2008.1',
            disabled=False
        )
        self.is2 = widgets.Dropdown(
            options=['None', 'ATL03', 'ATL06', 'ATL07', 'ATL08'],
            description='ICESat 2:',
            disabled=False,
        )
        self.dates_range = widgets.SelectionRangeSlider(
            options=slider_dates,
            index=slider_index,
            continuous_update=False,
            description='Date Range',
            orientation='horizontal',
            layout={'width': '90%'})

        self.granule_count = widgets.Button(description="Get Raw Granule Count",
                                            display='flex',
                                            flex_flow='column',
                                            align_items='stretch', )
        self.granule_count.style.button_color = 'lightgreen'
        self.granule_count.layout.width = 'auto'
        self.print_parameters = widgets.Button(description="Print Current Parameters",
                                               display='flex',
                                               flex_flow='column',
                                               align_items='stretch', )
        self.print_parameters.style.button_color = 'lightgreen'
        self.print_parameters.layout.width = 'auto'

        self.post_order = widgets.Button(description="Place Data Order",
                                         display='flex',
                                         flex_flow='column',
                                         align_items='stretch', )
        self.post_order.style.button_color = 'lightblue'
        self.post_order.layout.width = 'auto'

        self.check_order_status = widgets.Button(description="Order status",
                                                 display='flex',
                                                 flex_flow='column',
                                                 align_items='stretch', )
        self.check_order_status.style.button_color = 'lightblue'
        self.check_order_status.layout.width = 'auto'

        self.download_button = widgets.Button(description="Download completed orders",
                                              display='flex',
                                              flex_flow='column',
                                              align_items='stretch', )
        self.download_button.style.button_color = 'lightblue'
        self.download_button.layout.width = 'auto'

        self.selection_buttons = widgets.HBox([self.granule_count,
                                               self.print_parameters,
                                               self.post_order,
                                               self.check_order_status,
                                               self.download_button])
        self.selection_controls = widgets.VBox([self.projection,
                                                self.dataset,
                                                self.itrf,
                                                self.epoch,
                                                self.is2,
                                                self.dates_range,
                                                self.selection_buttons])
        self.controls.append(self.selection_controls)
        self.layers_control = LayersControl(position='topright')
        # Map Components
        place_marker = Marker(icon=AwesomeIcon(name="check", marker_color='green', icon_color='darkgreen'))
        self.search_control = SearchControl(
            position="topleft",
            url='https://nominatim.openstreetmap.org/search?format=json&q={s}',
            zoom=5,
            marker=place_marker
        )
        self.dc = DrawControl(
            circlemarker={},
            polyline={},
            rectangle={
                "shapeOptions": {
                    "fillColor": "#cc00cc",
                    "color": "#cc00cc",
                    "fillOpacity": 0.5
                }
            })
        self.file_upload = widgets.FileUpload(
            accept='.json,.geojson,.shp',
            multiple=False  # True to accept multiple files upload else False
        )

        # Now we are going to link the controls to the relevant events
        self.dates_range.observe(self.dates_changed, 'value')
        self.projection.observe(self.hemisphere_change)
        self.credentials_button.on_click(self.set_credentials)
        self.granule_count.on_click(self.query_cmr)
        self.print_parameters.on_click(self.get_parameters)
        self.post_order.on_click(self.place_data_orders)
        self.check_order_status.on_click(self.order_statuses)
        self.download_button.on_click(self.download_orders)
示例#9
0
 def plotmap(self, metric, climatedf, coorddf, filepath, filename='Map'):
     sel_cols = ['Location', 'Year', metric]
     climatedf = climatedf[sel_cols]
     climatedf = climatedf.reindex(columns=climatedf.columns.tolist() +
                                   ['color'])
     color = []
     for (i, j) in climatedf.iterrows():
         value = (j[metric] - climatedf[metric].min()) / (
             climatedf[metric].max() - climatedf[metric].min())
         if (value > 0 and value <= (1 / 6)):
             color.append('darkblue')
         elif (value > (1 / 6) and value <= (2 / 6)):
             color.append('blue')
         elif (value > (2 / 6) and value <= (3 / 6)):
             color.append('green')
         elif (value > (3 / 6) and value <= (4 / 6)):
             color.append('orange')
         elif (value > (4 / 6) and value <= (5 / 6)):
             color.append('red')
         else:
             color.append('darkred')
     climatedf['color'] = color
     gps_color = pd.merge(climatedf, coorddf, on=['Location'])
     gps_color.head()
     newdata = pd.DataFrame([])
     for (index, row) in gps_color.iterrows():
         row['Latitude'] += random.uniform(0.1, 0.9)
         row['Longitude'] += random.uniform(0.1, 0.9)
         newdata = newdata.append(row)
     center = [39.0119, -98.4842]
     zoom = 3
     i = 0
     m = Map(basemap=basemaps.Esri.WorldImagery, center=center, zoom=zoom)
     for (index, row) in newdata.iterrows():
         icon = AwesomeIcon(
             name='tint',
             marker_color=row.loc['color'],  #'#583470'
             icon_color='black',
             spin=False)
         loc = [row.loc['Latitude'], row.loc['Longitude']]
         marker = Marker(location=loc, draggable=False, icon=icon)
         m.add_layer(marker)
         i += 1
     m.add_control(FullScreenControl())
     m.save(filepath + "/" + filename + '.html', title=filename)
     mpl.rcParams.update({'font.size': 10})
     fig = plt.figure(figsize=(8, 3))
     ax = fig.add_subplot(111)
     vals = []
     for i in range(7):
         vals.append(((
             (climatedf[metric].max() - climatedf[metric].min()) / 6) * i) +
                     climatedf[metric].min())
     cmap = mpl.colors.ListedColormap([
         'darkblue', 'deepskyblue', 'limegreen', 'orange', 'red', 'darkred'
     ])
     norm = mpl.colors.BoundaryNorm(vals, cmap.N)
     cb = mpl.colorbar.ColorbarBase(ax,
                                    cmap=cmap,
                                    norm=norm,
                                    spacing='uniform',
                                    orientation='horizontal',
                                    extend='neither',
                                    ticks=vals)
     cb.set_label(metric)
     ax.set_position((0.1, 0.45, 0.8, 0.1))
     plt.savefig(filepath + "/" + 'legend.jpg',
                 dpi=2000,
                 bbox_inches="tight")
     file = codecs.open(filepath + "/" + filename + '.html', "r", "utf-8")
     file_list = file.read().split("\n")
     file.close()
     print(file_list)
     file_list.insert(
         -3, "<img src='legend.jpg' alt='Plot Legend' style='width:35%;'>")
     file = codecs.open(filepath + "/" + filename + '.html', "w", "utf-8")
     file.write("\n".join(file_list))
     file.close()
     return m, fig
示例#10
0
    name="GTS",
    position="bottomright",
)
m.add_control(legend)


def make_popup(row):
    classes = "table table-striped table-hover table-condensed table-responsive"
    return pd.DataFrame(row[["met", "wave", "type", "name", "pgm"]]).to_html(
        classes=classes
    )

for k, row in map_df.iterrows():
    if (row["met"] + row["wave"]) > 0:
        location = row["lat"], row["lon"]
        if row["met"] == 0:
            color = "red"
        elif row["wave"] == 0:
            color = "orange"
        else:
            color = "green"
        marker = Marker(
            draggable=False,
            icon=AwesomeIcon(name="life-ring", marker_color=color),
            location=location,
        )
        msg = HTML()
        msg.value = make_popup(row)
        marker.popup = msg
        m.add_layer(marker)
m
示例#11
0
def plot_bounds(bounds,
                receiver_locations=[],
                receiver_info=pd.DataFrame(),
                node_locations=[]):
    """
    Construct a map view widget for the given region with further info. The map widget displays
    inside IPython notebooks.

    :param bounds: Dictionary containing the keys 'north', 'east', 'south', 'west'. Each value
                   should be a latitude or longitude in degrees.
    :type bounds: dict

    :param receiver_locations: List of tuples containing the locations (lat, lon) of receivers.
    :type receiver_locations: list

    :param receiver_info: A dataframe containing receiver information to be displayed on the map.
    :type receiver_info: pandas.DataFrame

    :param node_locations: Set of tuples containing the locations (lat, lon) of data nodes.
    :type node_locations: set
    """
    # Create the Map
    # **************
    center = ((bounds['north'] + bounds['south']) / 2,
              (bounds['east'] + bounds['west']) / 2)
    m = Map(center=center, zoom=8)

    # Add a rectagle for the Bounds
    # *****************************
    rectangle = Rectangle(bounds=((bounds['north'], bounds['east']),
                                  (bounds['south'], bounds['west'])),
                          color='#2e4053',
                          opacity=0.5,
                          weight=3,
                          fill_color='#2e4053',
                          fill_opacity=0.1)
    m.add_layer(rectangle)

    # Add markers for Receiver Locations
    # **********************************
    receiver_markers = []
    for lat, lon in receiver_locations:
        # Create Icon for the Marker
        icon = AwesomeIcon(name='microphone', marker_color='darkblue')

        # Create Popup message
        if receiver_info is not None:
            r_info = receiver_info[(receiver_info['Receiver.lat'] == lat)
                                   & (receiver_info['Receiver.lon'] == lon)]
            r_info = r_info.drop(['Receiver.lat', 'Receiver.lon'], axis=1)
        message = HTML()
        message.value = r_info.to_html(index=False)

        # Add Marker
        receiver_markers.append(
            Marker(location=(lat, lon),
                   draggable=False,
                   icon=icon,
                   popup=message))
    # Group the markers into a cluster
    receiver_cluster = MarkerCluster(markers=receiver_markers)
    # Add marker cluster to the map
    m.add_layer(receiver_cluster)

    # Add markers for Node Locations
    # ******************************
    node_markers = []
    for lat, lon in node_locations:
        # Create Icon for the Marker
        icon = AwesomeIcon(name='info', marker_color='lightred')

        # Add Marker
        node_markers.append(
            Marker(location=(lat, lon),
                   draggable=False,
                   icon=icon,
                   size=10,
                   opacity=0.8))

    node_cluster = MarkerCluster(markers=node_markers)
    # Add marker cluster to the map
    m.add_layer(node_cluster)

    # Display the map
    # ***************

    display(m)
    return m