Exemplo n.º 1
0
    def add_points_from_csv(self, in_csv, x, y, header):
        """[summary]

        Args:
            in_csv (str): File path to csv file.
            x (str): Field name for X in csv.
            y (str): Field name for Y in csv.
            header (bool, optional): Whether csv file contains a header. Defaults to True.
        """
        with open(in_csv, encoding='utf8') as csvfile:
            reader = csv.reader(csvfile, delimiter=',')
            i = 0
            markers = []
            for row in reader:
                if i == 0:
                    if header == True:
                        fields = row
                        x_index = fields.index(x)
                        y_index = fields.index(y)
                    i += 1
                else:
                    markers.append(
                        ipyleaflet.Marker(location=(row[y_index],
                                                    row[x_index])))
            marker_cluster = ipyleaflet.MarkerCluster(markers=markers)
            self.add_layer(marker_cluster)
Exemplo n.º 2
0
def get_marker_cluster(data,
                       geom_column,
                       info_box: widgets.HTML,
                       timestamp_column,
                       title_columns=()):
    def get_title(d):
        return '<br>'.join([
            _to_html(d[c]) for c in title_columns if d[c] not in (np.nan, None)
        ])

    def get_hover_event_handler(info):
        def hover_event_handler(**kwargs):
            info_box.value = info

        return hover_event_handler

    locs = data[geom_column].apply(_wkb_hex_to_point)
    dicts = data.to_dict(orient='rows')

    markers = [
        ipyleaflet.Marker(location=loc, title=str(loc), draggable=False)
        for loc in locs
    ]
    clusters = ipyleaflet.MarkerCluster(markers=markers, name='Marker Cluster')
    for marker, d in zip(clusters.markers, dicts):
        marker.on_mouseover(get_hover_event_handler(get_title(d)))
        marker.timestamp = pd.to_datetime(d[timestamp_column])
    return clusters
Exemplo n.º 3
0
    def layer(self):
        self.heatmap_all = ipyleaflet.Heatmap(locations=[
            tuple(r) for r in self.df[['Latitude', 'Longitude']].to_numpy()
        ],
                                              radius=30,
                                              name='All point Heatmap')
        self.m01.add_layer(self.heatmap_all)

        self.heatmap_byLast = ipyleaflet.Heatmap(locations=[
            tuple(r) for r in self.df[['Latitude', 'Longitude']].to_numpy()
        ],
                                                 radius=30,
                                                 name='By Date')
        self.m01.add_layer(self.heatmap_byLast)

        # try:
        #     # path_shapefile = r'G:\Meu Drive\USP-SHS\Outros\Shapefile\Jaguaribe\Jaguaribe.shp'
        #     self.shape = gpd.read_file(self.control_shapefileText.value)
        #     geo_data = ipyleaflet.GeoData(geo_dataframe=self.shape, name='Bacias',style={'color': 'black', 'fillColor': '#3366cc', 'opacity':0.05, 'weight':1.9, 'dashArray':'2', 'fillOpacity':0.6},
        #                    hover_style={'fillColor': 'red' , 'fillOpacity': 0.2})
        #     self.m01.add_layer(geo_data)
        # except:
        #     pass

        # Layer too slow to used
        marks = tuple([
            ipyleaflet.Marker(location=(lat, lon))
            for lat, lon in self.df[['Latitude', 'Longitude']].to_numpy()
        ])
        marker_cluster = ipyleaflet.MarkerCluster(markers=marks)
        self.m01.add_layer(marker_cluster)
Exemplo n.º 4
0
def mk_station_selector(on_select,
                        stations=None,
                        dst_map=None,
                        **kw):
    """
    Add stations to the map and register on_click event.

    :param on_select: Will be called when user selects station on the map `on_select(station)`
    :param stations: List of stations as returned from get_stations
    :param dst_map: Map to add stations markers to

    Any other arguments are passed on  to Map(..) constructor.

    Returns
    =======

    (map, marker_cluster)

    Passes through map=dst_map if not None, or returns newly constructed Map object.
    """
    import ipyleaflet as L

    if stations is None:
        stations = get_stations()

    stations = [st for st in stations if st.pos is not None]
    pos2st = {st.pos: st for st in stations}

    def on_click(event='', type='', coordinates=None):
        pos = tuple(coordinates)
        st = pos2st.get(pos)
        if st is None:
            # should probably log warning here
            print("Can't map click to station")
            return

        on_select(st)

    markers = [L.Marker(location=st.pos,
                        draggable=False,
                        title=st.name)
               for st in stations]

    cluster = L.MarkerCluster(markers=markers)

    if dst_map is None:
        dst_map = L.Map(**kw)

    dst_map.add_layer(cluster)
    cluster.on_click(on_click)

    return dst_map, cluster
Exemplo n.º 5
0
 def display(self,
             basemap=False,
             mapLayout=False,
             style=False,
             groupBy=False,
             colorDict=False,
             pageTitle='GeoJSON map',
             outputPath='html/static'):
     """
     Display the dataframe on a map. Markers can be plotted at once, grouped (style='grouped'), or as pie charts (style='pie') grouped by a chosen category (groupBy='COLUMN').
     """
     if basemap:
         self.basemap = basemap
     else:
         self.basemap = {
             'url':
             'https://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png',
             'max_zoom': 16,
             'attribution':
             '<a href="https://carto.com">Carto Light NoLabels</a>',
             'name': 'Carto Light'
         }
     latList = [
         x for x in self.df[self.lat].values
         if type(x) not in [str, list, dict]
     ]
     latMean = sum(latList) / len(latList)
     lonList = [
         x for x in self.df[self.lon].values
         if type(x) not in [str, list, dict]
     ]
     lonMean = sum(lonList) / len(lonList)
     self.center = [latMean, lonMean]
     self.zoom = 5
     self.displayMap = ipyleaflet.Map(center=self.center,
                                      zoom=self.zoom,
                                      layers=(ipyleaflet.basemap_to_tiles(
                                          self.basemap), ))
     if mapLayout:
         self.displayMap.layout = mapLayout
     if not style:
         markers = self._generateMarkers()
         for marker in markers:
             self.displayMap.add_layer(marker)
         return self.displayMap
     elif style == 'grouped':
         markers = self._generateMarkers()
         self.markerCluster = ipyleaflet.MarkerCluster(markers=markers)
         self.displayMap.add_control(ipyleaflet.LayersControl())
         self.displayMap.add_layer(self.markerCluster)
         return self.displayMap
     elif style == 'pie':
         if not groupBy:
             raise KeyError(
                 'Please add groupBy=COLNAME. You need to specify the column containing the categories for the pie chart.'
             )
         html = self._writeHTML(groupCategory=groupBy,
                                pageTitle=pageTitle,
                                outputPath=outputPath)
         css = self._writeCSS(groupCategory=groupBy,
                              colorDict=colorDict,
                              outputPath=outputPath)
         print(
             'Your map has been generated at\n\t"/html/static/index.html".\nDue to CORS issues, most browsers will not load the GeoJSON in an Iframe correctly.\nPlease open the map in a seperate browser window.'
         )
         return displayHTML(
             "<iframe allowfullscreen=”true” mozallowfullscreen=”true” webkitallowfullscreen=”true” height=550px; width=100% src='./html/static/index.html'> <iframe>"
         )