예제 #1
0
 def build_map(self, click_handler):
     mean_lat = self.x_data[self.lat_key].values.mean()
     mean_lng = self.x_data[self.lon_key].values.mean()
     # create the map
     m = Map(center=(mean_lat, mean_lng), zoom=4, basemap=basemaps.Stamen.Terrain)
     m.layout.height = '600px'
     # show trace
     markers = []
     for k in self.marker_info:
         lat, lon = k
         message = HTML()
         message.description = "Station ID"
         message.value = str(self.marker_info[k])
         message.placeholder = ""
         marker = Marker(location=(lat, lon))
         marker.on_click(click_handler)
         marker.popup = message
         markers.append(marker)
     marker_cluster = MarkerCluster(
         markers=markers
     )
     # not sure whether we could register once instead of each marker:
     # marker_cluster.on_click(click_handler)
     m.add_layer(marker_cluster)
     # m.add_control(FullScreenControl())
     return m
예제 #2
0
def plot_gps_clusters(ds, user_id:str, zoom=5):
    """
    Plots GPS coordinates

    Args:
        ds (DataStream): datastream object
        user_id (str): uuid of a user
        zoom: min 0 and max 100, zoom map

    """
    pdf = ds_to_pdf(ds, user_id)

    marker_list = []
    center = None
    for index, row in pdf.iterrows():
        if center is None:
            center = [row["latitude"], row["longitude"]]
        marker_list.append(Marker(location=(row["latitude"], row["longitude"])))

    m = Map(center=(center), zoom=zoom)
    marker_cluster = MarkerCluster(
        markers=(marker_list)
    )
    m.add_layer(marker_cluster)
    return m
예제 #3
0
    def visualize_sequence_on_map(self, sequence: list):
        """
        Visualizes the resulting sequence of cities on a open source map.
        :param sequence: list [int]
        :return:
        """

        self.sequence = sequence

        # Get Marker positions and create map with markers:
        markers = self._create_markers(sequence)
        m = Map(center=markers[0].location, zoom=7, scroll_wheel_zoom=True)
        marker_cluster = MarkerCluster(markers=markers)
        m.add_layer(marker_cluster)

        # Create line between cities:
        line = Polyline(locations=[x.location for x in markers],
                        color="red",
                        fill=False)
        m.add_layer(line)

        m.layout.width = '100vw'
        m.layout.height = '100vh'
        # Save file and show in webbrowser:
        fname = "utils/tmp/map.html"
        realpath = os.path.realpath(fname)
        m.save(fname)
        # webbrowser.open_new_tab(fname)
        webbrowser.open_new_tab("file://" + realpath)

        print(
            "...Opening interactive streetmap in browser. If browser does not show the map correctly, try opening "
            "the saved HTML-file ({n}) manually.".format(n=realpath))
예제 #4
0
 def load_data(self):
     # Put a marker on the map for each station
     for i, station in enumerate(tqdm(self.stations)):
         marker = Marker(location=(float(get_station_attr(station, 'lat')), 
                                   float(get_station_attr(station, 'lon'))), 
                         draggable=False)
         self.markers[i] = marker
         
     marker_cluster = MarkerCluster(markers=self.markers)
     self.map.add_layer(marker_cluster)
예제 #5
0
 def __get_marker_cluster(self, locations, color='green'):
     locations_np = np.array(locations.filter(['latitude', 'longitude']))
     points = []
     for loc in locations_np:
         marker = Circle(location=loc.tolist(),
                         radius=1,
                         color=color,
                         fill_color=color)
         points.append(marker)
     cluster = MarkerCluster(markers=tuple(points))
     return cluster
예제 #6
0
def sv_leaflet(sv: "StateVectors", **kwargs) -> MarkerCluster:
    """Returns a Leaflet layer to be directly added to a Map.

    .. warning::
        This is only available if the Leaflet `plugin <plugins.html>`_ is
        activated. (true by default)

    The elements passed as kwargs as passed as is to the Marker constructor.
    """
    point_list = list(point_leaflet(p, title=p.callsign, **kwargs) for p in sv)
    return MarkerCluster(markers=point_list)
예제 #7
0
파일: IpyTools.py 프로젝트: lahlouaicha/IoT
def Give_Marker_Cluster(df):
    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(location=(x, y),
                   draggable=False,
                   title=str(round(x, 3)) + str(round(y, 3))))

    return MarkerCluster(markers=(markers))
예제 #8
0
def Give_Marker_Cluster(df):
    """
    Cette fonction permet de produire une clustered Marquer afin d'affichier l'ensemble des stations
    du DataFrame.
    Les stations se regroupent en fonction du zoom
    """
    markers = []
    for i in df.index:
        x = df.loc[i].latitude
        y = df.loc[i].longitude
        name = df.loc[i].Station_Name
        markers.append(Marker(location=(x, y), draggable=False, title=name))

    return MarkerCluster(markers=(markers))
예제 #9
0
 def add_points_from_csv(self,
                         in_csv,
                         x="longitude",
                         y="latitude",
                         label=None,
                         layer_name="Marker cluster"):
     # COME BACK TO THIS: https://carpentries-incubator.github.io/jupyter_maps/03-vector/index.html
     # TO-DO: ADD POP UPS
     points = csv_to_geojson(in_csv=in_csv, x=x, y=y)
     markers = [
         Marker(location=record['geometry']['coordinates'])
         for record in points['features']
     ]
     marker_cluster = MarkerCluster(markers=markers, name=layer_name)
     self.add_layer(marker_cluster)
예제 #10
0
 def build_map(self, click_handler: Callable[[Dict[str, Any]],
                                             None]) -> Map:
     mean_lat = self.x_data[self.lat_key].values.mean()
     mean_lng = self.x_data[self.lon_key].values.mean()
     # create the map
     m = Map(center=(mean_lat, mean_lng),
             zoom=4,
             basemap=basemaps.Stamen.Terrain)
     m.layout.height = '1200px'
     # show trace
     markers = []
     for k in self.marker_info:
         message = self.create_popup(k)
         marker = Marker(location=k, draggable=False)
         marker.on_click(click_handler)
         marker.popup = message
         markers.append(marker)
     marker_cluster = MarkerCluster(markers=markers)
     # not sure whether we could register once instead of each marker:
     # marker_cluster.on_click(click_handler)
     m.add_layer(marker_cluster)
     # m.add_control(FullScreenControl())
     return m
예제 #11
0
    def add_points_from_csv(
        self,
        in_csv,
        x="longitude",
        y="latitude",
        label=None,
        layer_name="Marker cluster",
    ):
        """Adds points from a CSV file containing lat/lon information and display data on the map.

        Args:
            in_csv (str): The file path to the input CSV file.
            x (str, optional): The name of the column containing longitude coordinates. Defaults to "longitude".
            y (str, optional): The name of the column containing latitude coordinates. Defaults to "latitude".
            label (str, optional): The name of the column containing label information to used for marker popup. Defaults to None.
            layer_name (str, optional): The layer name to use. Defaults to "Marker cluster".

        Raises:
            FileNotFoundError: The specified input csv does not exist.
            ValueError: The specified x column does not exist.
            ValueError: The specified y column does not exist.
            ValueError: The specified label column does not exist.
        """
        import pandas as pd
        import ipywidgets as widgets
        from ipyleaflet import Marker, MarkerCluster

        if not os.path.exists(in_csv):
            raise FileNotFoundError("The specified input csv does not exist.")

        df = pd.read_csv(in_csv)
        col_names = df.columns.values.tolist()

        if x not in col_names:
            raise ValueError(f"x must be one of the following: {', '.join(col_names)}")

        if y not in col_names:
            raise ValueError(f"y must be one of the following: {', '.join(col_names)}")

        if label is not None and (label not in col_names):
            raise ValueError(
                f"label must be one of the following: {', '.join(col_names)}"
            )

        points = list(zip(df[y], df[x]))

        self.default_style = {"cursor": "wait"}
        if label is not None:
            labels = df[label]
            markers = [
                Marker(
                    location=point, draggable=False, popup=widgets.HTML(labels[index])
                )
                for index, point in enumerate(points)
            ]
        else:
            markers = [Marker(location=point, draggable=False) for point in points]

        marker_cluster = MarkerCluster(markers=markers, name=layer_name)
        self.add_layer(marker_cluster)
        self.default_style = {"cursor": "default"}
예제 #12
0
location5.json
# In[11]

# Marker Cluster

from ipyleaflet import Map, Marker, MarkerCluster
import geocoder

m = Map(center=(-6.1753942, 106.827183), zoom=5)

marker6 = Marker(location=(-6.18233995, 106.84287153600738))
marker7 = Marker(location=(-6.26289085, 106.88222894692834))
marker8 = Marker(location=(-6.16156235, 106.74389124027667))
marker9 = Marker(location=(-6.28381815, 106.80486349194814))

marker_cluster = MarkerCluster(markers=(marker6, marker7, marker8, marker9))

m.add_layer(marker_cluster);
# display_map
m

# In[12]
# Multiple Marker

from ipyleaflet import Map, Marker
# install vega_datasets first from python.org python package index
from vega_datasets import data

# airports dataframe using vega_datasets
airports = data.airports()
airports = airports[:25]
    facilities_layer = create_layer(facilities_map, 'facilities',
                                    label_col='FACNAME', secondary_label_col='document',
                                    layer_type='marker', filter_on='document', inverse=True, color='lightGray')
    facilities_layer_docs = create_layer(facilities_map, 'facilities_docs',
                                         label_col='FACNAME', secondary_label_col='document',
                                         layer_type='marker', filter_on='document', color='black')

    wells = map_dict['wells']
    well_layer = create_layer(wells, 'wells with docs',
                              label_col='wlbWell', secondary_label_col='document',
                              layer_type='marker', filter_on='document', color='red')
    well_layer_no_docs = create_layer(wells, 'wells with docs',
                                      label_col='wlbWell', secondary_label_col='document',
                                      layer_type='marker', filter_on='document', inverse=True, color='lightGray')

    marker_cluster = MarkerCluster(markers=well_layer.layers, name='Wells with Docs')
    marker_cluster2 = MarkerCluster(markers=well_layer_no_docs.layers, name='Wells without Docs')
    # marker_cluster.add_layer(well_layer)
    m.add_layer(structure_layer_docs)
    m.add_layer(structure_layer)
    m.add_layer(fields_layer_docs)
    m.add_layer(fields_layer)
    m.add_layer(subareas_layer)
    m.add_layer(subareas_layer_docs)
    m.add_layer(facilities_layer_docs)
    m.add_layer(facilities_layer)
    m.add_layer(discoveries_layer_docs)
    m.add_layer(discoveries_layer)
    m.add_layer(marker_cluster)
    m.add_layer(marker_cluster2)
    m.add_control(LayersControl())
예제 #14
0
# Des marqueurs pour le début et la fin du parcours :

circle_marker1 = CircleMarker(
    location = (points[-1].latitude,points[-1].longitude),
    radius = 7,color = "red",fill_color = "white")
circle_marker2 = CircleMarker(
    location = (points[0].latitude,points[0].longitude),
    radius = 7,color = "green",fill_color = "green")
marks+=[circle_marker1,circle_marker2]


# Placer les marqueurs sur la carte:

marker_cluster = MarkerCluster(
    markers=marks
)
m.add_layer(marker_cluster);

print("Distance totale parcourue :",distance_parcourue,"mêtres.")


# ### La carte : ###
# 


# ### L'altitude au cours du parcours : ###


p = figure(title="Altitude /distance", x_axis_label='Distance parcourue', y_axis_label='altitude',
           width=800,height=300)
예제 #15
0
 def filter_markers(marker_cluster: ipyleaflet.MarkerCluster, min_date,
                    max_date):
     marker_cluster.markers = [
         m for m in app_state['markers']
         if min_date <= m.timestamp.date() <= max_date
     ]
for i in dalit_id_list:
    dalit_latitudes.append(location_table.loc[i]['latitude'])
    dalit_longitudes.append(location_table.loc[i]['longitude'])

# In[19]:

# Create map markers for Dalit hate crimes
dalit_markers_list = []

for i in range(len(dalit_id_list)):
    marker = Marker(location=(dalit_latitudes[i], dalit_longitudes[i]),
                    draggable=False)
    dalit_markers_list.append(marker)

marker_cluster = MarkerCluster(markers=(dalit_markers_list))

# In[20]:

# Make a map that shows hate crimes against Dalit People per state
# Figure out how to stylize it
# Can you divide regions by state instead of random?
# all markers should look the same, the circle + numbers are a nice -- should we make them all one color?
center = (20.5937, 78.9629)

dalit_map = Map(basemap=basemaps.OpenStreetMap.Mapnik, center=center, zoom=5)

dalit_map.add_layer(marker_cluster)

display(dalit_map)
예제 #17
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
예제 #18
0
파일: map.py 프로젝트: Hewlbern/Tdashboard
from ipyleaflet import Marker, Map, MarkerCluster

det_info = "Data.csv"
detector_information = pd.read_csv(det_info)

center = (-37.814, 144.96332)  #This is the lat long of Melbourne


def GPS(n):
    Coordinates = detector_information.set_index("Short Name")[["Y", "X"]]
    return {
        "Name": Coordinates.index[n],
        "GPS": (Coordinates.Y[n], Coordinates.X[n])
    }


Detectors = {}

Detectors[0] = {"Name": "14352OB_L1P0", "GPS": (-37.735018, 144.894947)}
Detectors[1] = {"Name": "14352OB_L1P1", "GPS": (-37.735012, 144.894879)}

m = Map(center=center, zoom=11)

marker1 = Marker(location=Detectors[0].get("GPS"), draggable=False)
marker2 = Marker(location=Detectors[1].get("GPS"), draggable=False)

marker_cluster = MarkerCluster(markers=(marker1, marker2))

m.add_layer(marker_cluster)

m