def draw_route_leaflet(G, route, zoom=16): center_osmid = ox.stats.extended_stats(G, ecc=True)['center'][0] G_gdfs = ox.graph_to_gdfs(G) nodes_frame = G_gdfs[0] ways_frame = G_gdfs[1] center_node = nodes_frame.loc[center_osmid] location = (center_node['y'], center_node['x']) m = lf.Map(center=location, zoom=zoom) start_node = nodes_frame.loc[route[0]] end_node = nodes_frame.loc[route[len(route) - 1]] start_xy = (start_node['y'], start_node['x']) end_xy = (end_node['y'], end_node['x']) marker = lf.Marker(location=start_xy, draggable=False) m.add_layer(marker) marker = lf.Marker(location=end_xy, draggable=False) m.add_layer(marker) for u, v in zip(route[0:], route[1:]): x, y = (ways_frame.query(f'u == {u} and v == {v}').to_dict('list') ['geometry'])[0].coords.xy points = map(list, [*zip([*y], [*x])]) ant_path = lf.AntPath(locations=[*points], dash_array=[1, 10], delay=1000, color='red', pulse_color='black') m.add_layer(ant_path) return m
def show_timetables(map: Map, timetables: List[Timetable]) -> None: for i, timetable in enumerate(timetables): for j, variant in enumerate(timetable.variants): group = lf.LayerGroup(name=f"{timetable.caption}, variant {j}") for stop in variant.stops: group.add_layer( lf.Marker( location=(stop.latitude, stop.longitude), draggable=False, title=stop.name, ) ) map.add_layer(group) section_group = lf.LayerGroup( name=f"(Shapes) {timetable.caption}, variant {j}" ) for section in prediction.route_sections(variant.stops): p = section.polygon section_group.add_layer( lf.Polygon( locations=[list(p.exterior.coords), list(p.interiors)], color="blue", ) ) map.add_layer(section_group)
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
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)
def draw_map_leaflet(G, highlight=None, zoom=16): """ draws ipyleaflet map with location as center of the map """ center_osmid = ox.stats.extended_stats(G, ecc=True)['center'][0] G_gdfs = ox.graph_to_gdfs(G) nodes_frame = G_gdfs[0] ways_frame = G_gdfs[1] center_node = nodes_frame.loc[center_osmid] location = (center_node['y'], center_node['x']) m = lf.Map(center=location, zoom=zoom) for _, row in ways_frame.iterrows(): lines = lf.Polyline( locations=[list(elem)[::-1] for elem in [*row['geometry'].coords]], color="black", fill=False, weight=1) m.add_layer(lines) # if we want to mark some specific nodes if highlight: for node_osmid in highlight: node = nodes_frame.loc[node_osmid] node_xy = (node['y'], node['x']) marker = lf.Marker(location=node_xy, draggable=False) m.add_layer(marker) return m
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)
def init_map(self): self.mainmap = ilfl.Map(basemap=ilfl.basemaps.Gaode.Satellite, center=[self.query_pt[-1], self.query_pt[0]], zoom=self.zoom) self.marker = ilfl.Marker(location=[self.query_pt[-1], self.query_pt[0]], draggable=True) self.mainmap.add_layer(self.marker) self.pr_selection = self.idxs[0] self.scene_list = pd.DataFrame(columns=('prefix', 'time', 'tier')) self.map_polygon = ilfl.WKTLayer(wkt_string=self.spatial_index.footprint.loc[self.pr_selection].geometry.wkt) self.mainmap.add_layer(self.map_polygon)
def markers(df: pd.DataFrame) -> List[lf.Marker]: return [ lf.Marker( location=(r.latitude, r.longitude), draggable=False, title=r.Index.time().isoformat(), ) for r in df.itertuples() ]
def trip_markers(tps: db.TripPoints) -> List[lf.Marker]: return [ lf.Marker( location=(tp.latitude / 3600000, tp.longitude / 3600000), draggable=False, title=tp.time.time().isoformat(), ) for tp in tps.points ]
def draw_route(G, route, zoom = 16): if len(G) >= 1000: print(f"The graph has {len(G)} which is a lot, we will use basic faster folium instead") m = ox.plot_route_folium(G = G, route = route) return m center_osmid = ox.stats.extended_stats(G,ecc=True)['center'][0] G_gdfs = ox.graph_to_gdfs(G) nodes_frame = G_gdfs[0] ways_frame = G_gdfs[1] center_node = nodes_frame.loc[center_osmid] location = (center_node['y'], center_node['x']) m = lf.Map(center = location, zoom = zoom) start_node = nodes_frame.loc[route[0]] end_node = nodes_frame.loc[route[len(route)-1]] start_xy = (start_node['y'], start_node['x']) end_xy = (end_node['y'], end_node['x']) marker = lf.Marker(location = start_xy, draggable = False) m.add_layer(marker) marker = lf.Marker(location = end_xy, draggable = False) m.add_layer(marker) for u, v in zip(route[0:], route[1:]): try: x, y = (ways_frame.query(f'u == {u} and v == {v}').to_dict('list')['geometry'])[0].coords.xy except: x, y = (ways_frame.query(f'u == {v} and v == {u}').to_dict('list')['geometry'])[0].coords.xy points = map(list, [*zip([*y],[*x])]) ant_path = lf.AntPath( locations = [*points], dash_array=[1, 10], delay=1000, color='red', pulse_color='black' ) m.add_layer(ant_path) return m
def add_func(button=None): p = ipyleaflet.Marker(name=point_name, location=coords, draggable=False) self._add_EELayer(point_name, { 'type': 'temp', 'object': None, 'visParams': None, 'layer': p })
def create_markers_df(self, df: pd.DataFrame) -> None: t = df.iloc[0].trip if t not in self.markers: self.markers[t] = [ lf.Marker( location=(r.latitude, r.longitude), draggable=False, title=r.Index.isoformat(), ) for r in df.itertuples() ]
def __init__(self, records, laps=[], width=None, height=None, fullscreen_widget=False): """Return a instance of a ActivityMap.""" locations = [[record.position_lat, record.position_long] for record in records if record.position_lat is not None and record.position_long is not None] lap_locations = [ [lap.stop_lat, lap.stop_long] for lap in laps if lap.start_lat is not None and lap.start_long is not None ] super().__init__(self.centroid(locations), width=width, height=height, fullscreen_widget=fullscreen_widget) ant_path = ipyleaflet.AntPath(locations=locations, dash_array=[1, 10], delay=2000, color='#7590ba', pulse_color='#3f6fba') self.map.add_layer(ant_path) for lap_num, lap_location in enumerate(lap_locations, start=1): lap_marker = ipyleaflet.Marker(location=lap_location, title=f'lap {lap_num}', draggable=False, icon=blue_pin) self.map.add_layer(lap_marker) start_marker = ipyleaflet.Marker(location=locations[0], title='start', draggable=False, icon=green_pin) self.map.add_layer(start_marker) stop_marker = ipyleaflet.Marker(location=locations[-1], title='stop', draggable=False, icon=red_pin) self.map.add_layer(stop_marker)
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
def show(self, map=None, top=0, kernel='folium'): """Draw the class object on the map with Folium. Args: map (Folium map object, optional): If set to None, the function will create a new map object. If given the map object, the layer will be drawn on the map. Defaults to None. top (int): The top number of records will be drawn on map. If top is set to 0, then all records will be drawn. Defaults to 0. """ if top != 0: data = self.data[0:top] else: data = self.data if map == None: if kernel == 'folium': m = folium.Map(location=[data[0][1], data[0][0]]) for record in data: folium.Marker([record[1], record[0]]).add_to(m) display(m) if kernel == 'ipyleaflet': m = ipyleaflet.Map(center=[data[0][1], data[0][0]]) markers = [] for record in data: marker = ipyleaflet.Marker( location=([record[1], record[0]])) markers.append(marker) layer_group = ipyleaflet.LayerGroup(layers=(markers)) m.add_layer(layer_group) else: markers = [] for record in data: if kernel == 'folium': folium.Marker([record[1], record[0]]).add_to(map) if kernel == 'ipyleaflet': marker = ipyleaflet.Marker( location=([record[1], record[0]])) markers.append(marker) layer_group = ipyleaflet.LayerGroup(layers=(markers)) map.add_layer(layer_group)
def _generateMarkers(self): popupTemplate = """ <head> <style> table { border: 1px solid black; border-radius: 25px; } </style> </head> <body> <table style="width:100%"> <tr> <th>Key</th> <th>Value</th> </tr> ROWS </table> </body> """ # tableTemplate = """<table style="width:100%"><tr><th>key</th><th>value</th></tr>ROWS</table>""" rowTemplate = """<tr><td>KEY</td><td>VALUE</td></tr>""" markers = [] for _, row in self.df.iterrows(): if isinstance(row[self.lon], numbers.Number) and isinstance( row[self.lat], numbers.Number): markerTemp = ipyleaflet.Marker( location=[row[self.lat], row[self.lon]], draggable=False) # popup information message = HTML() rowList = [] for x, y in row.iteritems(): if x in self.properties: str_x = re.escape(str(x)) str_y = re.escape(str(y)) rowTemp = re.sub('VALUE', str_y, re.sub('KEY', str_x, rowTemplate)) rowTemp = re.sub(r'\\(.)', r'\1', rowTemp) rowList.append(rowTemp) message.value = re.sub( r'\\(.)', r'\1', re.sub('ROWS', ''.join(rowList), popupTemplate)) message.placeholder = '' message.description = '' markerTemp.popup = message # style of marker markerTemp.layout = {'padding': '1px'} markers.append(markerTemp) return markers
def init_map(self): self.mainmap = ilfl.Map(basemap=ilfl.basemaps.Gaode.Satellite, center=[self.lat, self.lon], zoom=self.zoom) self.marker = ilfl.Marker(location=[self.lat, self.lon], draggable=True) self.mainmap.add_layer(self.marker) self.pr_selection = self.idxs.data.index[0] self.record = self.spatial_index.data.loc[self.pr_selection] self.map_polygon = Polygon(locations=[ (self.record.lat_UL, self.record.lon_UL), (self.record.lat_UR, self.record.lon_UR), (self.record.lat_LR, self.record.lon_LR), (self.record.lat_LL, self.record.lon_LL) ], color="blue") self.mainmap.add_layer(self.map_polygon)
def draw_map(G, highlight = None , zoom = 16): """ draws ipyleaflet map with location as center of the map """ if len(G) >= 1000: print(f"The graph has {len(G)} which is a lot, we will use basic faster folium instead") if highlight: center_osmid = ox.stats.extended_stats(G,ecc=True)['center'][0] G_gdfs = ox.graph_to_gdfs(G) nodes_frame = G_gdfs[0] ways_frame = G_gdfs[1] m = ox.plot_graph_folium(G = G) for node_osmid in highlight: node = nodes_frame.loc[node_osmid] node_xy = [node['y'], node['x']] fl.Marker(node_xy).add_to(m) else: m = ox.plot_graph_folium(G = G) return m center_osmid = ox.stats.extended_stats(G,ecc=True)['center'][0] G_gdfs = ox.graph_to_gdfs(G) nodes_frame = G_gdfs[0] ways_frame = G_gdfs[1] center_node = nodes_frame.loc[center_osmid] location = (center_node['y'], center_node['x']) m = lf.Map(center = location, zoom = zoom) for _, row in ways_frame.iterrows(): lines = lf.Polyline( locations = [list(elem)[::-1] for elem in [*row['geometry'].coords]], color = "black", fill = False, weight = 1 ) m.add_layer(lines) # if we want to mark some specific nodes if highlight: for node_osmid in highlight: node = nodes_frame.loc[node_osmid] node_xy = (node['y'], node['x']) marker = lf.Marker(location = node_xy, draggable = False) m.add_layer(marker) return m
def create_spec(widget_list): widget_data = [] for widget_name, widget_cls in widget_list: if issubclass(widget_cls, Link): widget = widget_cls((widgets.IntSlider(), 'value'), (widgets.IntSlider(), 'value')) elif issubclass( widget_cls, (widgets.SelectionRangeSlider, widgets.SelectionSlider)): widget = widget_cls(options=[1]) elif issubclass(widget_cls, lf.LegendControl): widget = widget_cls({}) elif issubclass(widget_cls, lf.SearchControl): widget = widget_cls(marker=lf.Marker()) elif issubclass(widget_cls, lf.WidgetControl): widget = widget_cls(widget=widgets.DOMWidget()) else: widget = widget_cls() widget_data.append(jsonify(widget_name, widget, widget_list)) return widget_data
def _add_marker(self, x: float, y: float, tooltip: str = "") -> lf.Marker: marker = lf.Marker(location=(x, y), draggable=False, title=tooltip) self.add_layer(marker) return marker
def get_marker(coordinate, popup_html): "use coordinate (tuple of two numbers) and popup_html (ipywidgets.HTML), return ipyleaflet.Marker object" m = ipyleaflet.Marker(location=coordinate, draggable = False) m.popup = popup_html return m
def __init__(self, projection='Global', **kwargs): # set default keyword arguments kwargs.setdefault('attribution', True) kwargs.setdefault('zoom', 1) kwargs.setdefault('zoom_control', False) kwargs.setdefault('scale_control', False) kwargs.setdefault('cursor_control', True) kwargs.setdefault('layer_control', True) kwargs.setdefault('center', (39, -108)) # create basemap in projection if (projection == 'Global'): self.map = ipyleaflet.Map( center=kwargs['center'], zoom=kwargs['zoom'], max_zoom=15, attribution_control=kwargs['attribution'], basemap=ipyleaflet.basemaps.Esri.WorldTopoMap) self.crs = 'EPSG:3857' elif (projection == 'North'): self.map = ipyleaflet.Map( center=kwargs['center'], zoom=kwargs['zoom'], max_zoom=24, attribution_control=kwargs['attribution'], basemap=ipyleaflet.basemaps.Esri.ArcticOceanBase, crs=projections.EPSG5936.Basemap) self.map.add_layer(ipyleaflet.basemaps.Esri.ArcticOceanReference) self.crs = 'EPSG:5936' elif (projection == 'South'): self.map = ipyleaflet.Map( center=kwargs['center'], zoom=kwargs['zoom'], max_zoom=9, attribution_control=kwargs['attribution'], basemap=ipyleaflet.basemaps.Esri.AntarcticBasemap, crs=projections.EPSG3031.Basemap) self.crs = 'EPSG:3031' # add control for layers if kwargs['layer_control']: self.layer_control = ipyleaflet.LayersControl(position='topleft') self.map.add_control(self.layer_control) self.layers = self.map.layers # add control for zoom if kwargs['zoom_control']: zoom_slider = ipywidgets.IntSlider(description='Zoom level:', min=self.map.min_zoom, max=self.map.max_zoom, value=self.map.zoom) ipywidgets.jslink((zoom_slider, 'value'), (self.map, 'zoom')) zoom_control = ipyleaflet.WidgetControl(widget=zoom_slider, position='topright') self.map.add_control(zoom_control) # add control for spatial scale bar if kwargs['scale_control']: scale_control = ipyleaflet.ScaleControl(position='topright') self.map.add_control(scale_control) # add control for cursor position if kwargs['cursor_control']: self.cursor = ipywidgets.Label() cursor_control = ipyleaflet.WidgetControl(widget=self.cursor, position='bottomleft') self.map.add_control(cursor_control) # keep track of cursor position self.map.on_interaction(self.handle_interaction) # add control for marker if kwargs['marker_control']: # add marker with default location self.marker = ipyleaflet.Marker(location=kwargs['center'], draggable=True) self.map.add_layer(self.marker) # add text with marker location self.marker_text = ipywidgets.Text( value='{0:0.8f},{1:0.8f}'.format(*kwargs['center']), description='Lat/Lon:', disabled=False) # watch marker widgets for changes self.marker.observe(self.set_marker_text) self.marker_text.observe(self.set_marker_location) self.map.observe(self.set_map_center) # add control for marker location marker_control = ipyleaflet.WidgetControl(widget=self.marker_text, position='bottomright') self.map.add_control(marker_control)
def draw(self): if self._box == None: return data = self._datasource.getData() popup = self.getValues("popup") value = self.getOpt("size") c = self._visuals._colors.getColor(self.getOpt("color")) sizePixels = None sizeField = None if value != None: try: sizePixels = int(value) except: sizeField = value colorField = None value = self.getOpt("color") if value != None: colorField = value minSize = sys.maxsize maxSize = 0 minColor = sys.maxsize maxColor = 0 sizes = self.getOpt("sizes", (1, 20)) sizeRange = [] colorRange = None gradient = None if sizeField != None or colorField != None: if isinstance(data, dict): for key, value in data.items(): if sizeField != None: if sizeField in value: num = float(value[sizeField]) if num < minSize: minSize = num if num > maxSize: maxSize = num if colorField != None: if colorField in value: num = float(value[colorField]) if num < minColor: minColor = num if num > maxColor: maxColor = num if sizeField != None: if maxSize > minSize: sizeRange = np.arange(minSize, maxSize, (maxSize - minSize) / int(sizes[1] - sizes[0])) if colorField != None: colorRange = tools.ColorRange(self._visuals._colors, minColor, maxColor) if self._colorbar != None: self._colorbar.data[0].marker.cmin = minColor self._colorbar.data[0].marker.cmax = maxColor #baseColor = self.getOpt("base_color",self._visuals._colors.lightest) #gradient = tools.Gradient(baseColor,levels=200,min=minColor,max=maxColor) opacity = self.getOpt("marker_opacity", .5) border = self.getOpt("marker_border", True) if isinstance(data, dict): for key, value in data.items(): if key in self._markers: marker = self._markers[key] else: if self._icon != None: icon = maps.Icon(icon_url=self._icon, icon_size=[40, 30]) marker = maps.Marker(icon=icon) else: marker = maps.CircleMarker() marker.stroke = border marker.fill_opacity = opacity self._map.add_layer(marker) self._markers[key] = marker if len(popup) > 0: marker.popup = widgets.HTML() if self._lat in value and self._lon in value: lat = value[self._lat] lon = value[self._lon] marker.location = (lat, lon) if sizePixels != None: marker.radius = sizePixels elif len(sizeRange) > 0: size = 0 if sizeField in value: size = float(value[sizeField]) index = np.where(size >= sizeRange)[0] marker.radius = len(index) - 1 if colorRange != None: if colorField in value: num = float(value[colorField]) marker.fill_color = colorRange.getColor(num) if gradient != None: if colorField in value: num = float(value[colorField]) marker.fill_color = gradient.darken(num - minColor) if marker.popup != None: text = "" for i, s in enumerate(popup): if i > 0: text += "<br/>" text += s + "=" + value[s] marker.popup.value = text
def snapshot_to_marker(entry: BusSnapshot) -> lf.Marker: return lf.Marker( location=(entry.latitude, entry.longitude), draggable=False, title=entry.poll_time.time().isoformat(), )
def add_marker(self, p: sg.Point, tooltip: str = "") -> None: self.add_layer(lf.Marker(location=p.coords[0], draggable=False, title=tooltip))
def map(self, coordinates, zoomlevel): """Return a display()-able map for coordinates""" figure = ipyleaflet.Map(center=coordinates, zoom=zoomlevel) figure += ipyleaflet.Marker(location=coordinates) return figure