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 make_map(zoom, layout, center, dragging=True, class_popup_on_click=False, basemap=ipyleaflet.basemaps.Esri.WorldStreetMap): m = ipyleaflet.Map(zoom=zoom, layout=layout, center=center, dragging=dragging, close_popup_on_click=False, basemap=basemap) return m
def plotHeatmap(locations: [tuple], heatmapName: str, worldMap: lf.Map = None, center: tuple = (0, 0), **kwargs) -> lf.Map: ''' Plot the given lat lon locations as a heatmap layer on a world map object @center: the center coordinate when creating the world map object @locations: list of latitude & longitude pair @worldMap: ipyleaflet Map object. If this is specified, the new heatmap will be addded to this object. Else a new Map object will be created @heatmapName: name of the heatmap layer Returns: a newly created Map object or the passed in worldMap object. ''' # Create map if it's not passed in to the function if (worldMap is None): baseMap = lf.basemaps.CartoDB.DarkMatter # lf.basemaps.Esri.WorldTopoMap worldMap = lf.Map(basemap=baseMap, center=center, zoom=10) worldMap.add_control(lf.FullScreenControl()) worldMap.add_control(lf.LayersControl(position='topright')) # Remove existing heatmap layer that has the same name removeLayerByType(worldMap, heatmapName, lf.Heatmap) # Add the heatmap layer to the world map object heatmap = lf.Heatmap(locations=locations, radius=20, name=heatmapName, **kwargs) worldMap.add_layer(heatmap) return worldMap
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 build_us_cntymap(dataframe, colname): global geojson_cnty, this_cnty_colname, cnty_overlay, county_data_dict global cnty_layer, cnty_legend, cnty_control global MapsVDict, geojson_cnty, mapcenter, mapzoom, loc_dict # This function builds a US Choropleth Map (but doesn't display it) for the county-level # data provided. # Load data needed to build either kind of map build_us_genericmap() # Build location dictionary if doesn't yet exist try: loc_dict except NameError: loc_dict = BuildLocationDict(dataframe) # ipyleaflet requires a dictionary for the choro_data field/the variable to be visualized, # so convert the Pandas data series into the appropriate dictionary setting keys to postal # codes used in geojson_states county_data_dict = get_cnty_dict(dataframe, colname) # Determine range of values for colormap, then define colormap (need to also pass # max/min values to Choropleth builder or they are ignored). Set up legend dictionary # to show this range. (minval, maxval) = set_cm_limits(county_data_dict) cmap = BuildColormap(minval, maxval) legendDict = BuildLegendDict(minval, maxval, cmap) # Creating the map cnty_map = lf.Map(center=mapcenter, zoom=mapzoom) # Draw a functional counties layer cnty_layer = lf.Choropleth( geo_data=geojson_cnty, choro_data=scrub(county_data_dict), key_on='id', # Below here is some formatting/coloring from the documentation colormap=cmap, value_min=minval, value_max=maxval, border_color=map_border_color, hover_style=map_hover_style, style=map_style) cnty_map.add_layer(cnty_layer) # Display a legend cnty_legend = lf.LegendControl(legendDict, name="Legend", position="bottomleft") cnty_map.add_control(cnty_legend) # Display data in overlay this_cnty_colname = colname cnty_overlay = widgets.HTML("Hover over Location for Details") cnty_control = lf.WidgetControl(widget=cnty_overlay, position='topright') cnty_map.add_control(cnty_control) cnty_layer.on_hover(update_cnty_overlay) return (cnty_map, cnty_legend, cnty_overlay)
def display_composite_ipyleaflet(self, zoom=10): image = self.image.clip(ee.Geometry(self.polygon)) mapid = image.getMapId() tiles_url = self.ee_tiles.format(**mapid) tile_layer = ipyl.TileLayer(url=tiles_url, layers='collection', format='image/png', name=self.collection, opacity=1) polygon = ipyl.Polygon(locations=self.locations, color=self.color, fill_opacity=0., name='AoI') m = ipyl.Map(center=tuple(self.centroid), zoom=zoom) m.add_layer(tile_layer) m.add_layer(polygon) control = ipyl.LayersControl(position='topright') m.add_control(control) m.add_control(ipyl.FullScreenControl()) return m
def get_map(center, zoom): "use center (tuple of two numbers) and zoom (number), return ipyleaflet.Map object" return ipyleaflet.Map( center=center, zoom=zoom, scroll_wheel_zoom=True )
def Map(center=(40, -100), zoom=4, layers=['HYBRID']): """Creates an interactive ipyleaflet map. If you want more options, use ipyleaflet.Map() to create a map. Args: center (tuple, optional): Initial geographic center of the map. Defaults to (40, -100). zoom (int, optional): Initial map zoom level. Defaults to 4. layers (list, optional): Tuple of layers. Defaults to ['HYBRID']. Returns: object: An ipyleaflet map instance. """ m = ipyleaflet.Map(center=center, zoom=zoom, scroll_wheel_zoom=True) m.add_control(LayersControl(position='topright')) m.add_control(ScaleControl(position='bottomleft')) m.add_control(FullScreenControl()) m.add_control(DrawControl()) measure = MeasureControl( position='bottomleft', active_color='orange', primary_length_unit='kilometers' ) m.add_control(measure) for layer in layers: if layer in ee_basemaps.keys(): m.add_layer(ee_basemaps[layer]) else: print("Layer name {} is invalid. It must be one of these values: {}".format( layer, ", ".join(ee_basemaps.keys()))) return m
def render(self, resp: requests.models.Response) -> ipyleaflet.Map: "Return an ipyleaflet map with the GPX object rendered on it, or None." import gpxpy from gpxpy.gpx import GPXXMLSyntaxException obj = resp.content.decode('utf-8') try: trace = gpxpy.parse(obj) except GPXXMLSyntaxException: return None pts = [p.point for p in trace.get_points_data()] bbox = trace.get_bounds() mins = (bbox.min_latitude, bbox.min_longitude) maxs = (bbox.max_latitude, bbox.max_longitude) bbox = mins, maxs center = list(bbox_center(*bbox)) z = zoom_for_bbox(*(mins + maxs)) m = ipyleaflet.Map(center=center, zoom=z + 1) # FIXME: make path styling configurable poly = ipyleaflet.Polyline(locations=[(p.latitude, p.longitude) for p in pts], fill=False) m.add_layer(layer=poly) for p in pts: cm = ipyleaflet.CircleMarker(location=(p.latitude, p.longitude), radius=5) m.add_layer(layer=cm) self.data = m return m
def create_basemap_ipylft(self, geo_dataframe): ext = geo_dataframe.total_bounds cen_x, cen_y = (ext[1] + ext[3]) / 2, (ext[0] + ext[2]) / 2 m = ipylft.Map(center=(cen_x, cen_y), zoom=12, basemap=ipylft.basemaps.Stamen.Toner, scroll_wheel_zoom=True) return m
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 display_animation(self, url): m = ipyl.Map(center=tuple(self.centroid), zoom=12) video = ipyl.VideoOverlay(url=url, bounds=tuple(list(map(tuple, self.bounds)))) m.add_layer(video) m.add_control(ipyl.FullScreenControl()) return m
def __init__(self, center, height, zoom): self.center = center self.map = ill.Map( basemap=ill.basemaps.CartoDB.Positron, center=self.center, scroll_wheel_zoom=True, zoom=zoom, layout=widgets.Layout(height=height) ) self.legend_list = []
def display(self): if self.map is None: self.map = leaflet.Map(center=self.center, zoom=self.zoom, basemap=self.basemap, layout=self.map_layout) self.map.on_interaction(self.handle_interaction) # self.map.add_control(self.layers_control) objs = (self.map, self.label) display(*objs)
def __init__(self, Map=None, center=(52.585538631877306, 245.45105824782084), zoom=6, close_popup_on_click=False): self.map = Map if Map is None: self.map = ipyleaflet.Map(center=center, zoom=zoom, close_popup_on_click=close_popup_on_click) super().__init__(self.map) self.stations = [] self.popups = [] self.markers = [] self.current_station = None self.comm = None
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 render(self, resp: requests.models.Response) -> ipyleaflet.Map: "Return an ipyleaflet map with the GeoJSON object rendered on it, or None." obj = resp.json() if obj.get('type', None) != 'FeatureCollection': return None bbox = geojson_bbox(obj) mins, maxs = bbox center = list(reversed(bbox_center(*bbox))) z = zoom_for_bbox(*(mins + maxs)) m = ipyleaflet.Map(center=center, zoom=z + 1) m.add_layer(layer=ipyleaflet.GeoJSON(data=obj)) self.data = m return m
def __init__(self, distance_choice="agat"): self.m = ipyl.Map(center=(45, 0), zoom=7, layout={"height": "500px"}) # Date date_picker = widg.DatePicker(value=dt.datetime(2020, 1, 26)) self._date = date_picker.value date_picker.observe(self.change_date, "value") self.step = 0 self.distance_choice = distance_choice variable_picker = widg.Dropdown( value="WWMF", options=["WWMF", "WME", "W1", "PRECIP", "T"]) variable_picker.observe(self.variable_change, "value") dept_picker = widg.Dropdown(value="41", options={ "Finistère": "29", "Isère": "38", "Hérault": "34", "Loire-et-cher": "41" }) dept_picker.observe(self.change_dept, "value") self.dept = dept_picker.value self._variable = variable_picker.value # Open dataset and mask self.open_file() # Add other widgets self.legend = widg.Image(layout=widg.Layout(height="430px")) self.html1 = HTML(''' <h4>Type de temps</h4> Hover over a pixel ''') self.html1.layout.margin = '0px 20px 20px 20px' # Add controls control1 = WidgetControl(widget=self.html1, position='bottomright') self.m.add_control(control1) self.m.add_control(ipyl.LayersControl()) slider = widg.IntSlider(min=0, max=len(self.da.step) - 1, step=1, value=0, description="step") slider.observe(self.change_step, 'value') self.m.add_control( ipyl.WidgetControl(widget=widg.VBox( [date_picker, slider, variable_picker, dept_picker]), position="topright")) self.m.add_control(ipyl.FullScreenControl()) self.render() super().__init__([self.m, self.legend])
def __init__(self, visuals, datasource, **kwargs): Chart.__init__(self, visuals, datasource, **kwargs) self._map = maps.Map() self._lat = None self._lon = None self._markers = {} self._colorbar = None self._circles = [] self._polygons = [] self._box = None self._icon = None
def add_minimap(self, zoom=5, position="bottomright"): """Adds a minimap (overview) to the ipyleaflet map. Args: zoom (int, optional): Initial map zoom level. Defaults to 5. position (str, optional): Position of the minimap. Defaults to "bottomright". """ minimap = ipyleaflet.Map( zoom_control=False, attribution_control=False, zoom=5, center=self.center, layers=[ee_basemaps['Google Map']] ) minimap.layout.width = '150px' minimap.layout.height = '150px' link((minimap, 'center'), (self, 'center')) minimap_control = WidgetControl(widget=minimap, position=position) self.add_control(minimap_control)
def display_video(self, zoom=12): # Display movie on map m = ipyl.Map(center=tuple(self.centroid), zoom=zoom) video = ipyl.VideoOverlay(url=self.file_name, bounds=tuple(list(map(tuple, self.bounds)))) polygon = ipyl.Polygon(locations=self.locations, color=self.color, fill_opacity=0., name='AoI') m.add_layer(video) m.add_layer(polygon) return m
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 __init__(self, center, width=None, height=None, zoom=None, fullscreen_widget=False): """Return a instance of a Map.""" if width is None: width = ConfigManager.get_maps('width') if height is None: height = ConfigManager.get_maps('height') if zoom is None: zoom = 15 layout = ipywidgets.Layout(width=f'{width}px', height=f'{height}px') self.map = ipyleaflet.Map(center=center, zoom=zoom, layout=layout) self.map.add_control(ipyleaflet.ScaleControl(position='bottomleft')) if fullscreen_widget: self.map.add_control(ipyleaflet.FullScreenControl())
def __init__(self, geo_json, column_names, **kwargs): # self._control = None super(VizMapGeoJSONLeaflet, self).__init__(**kwargs) self.map = ipyleaflet.Map(center=[40.72866940630964, -73.80228996276857], zoom=10) self.control = VizMapGeoJSONLeaflet.Control(self, column_names) self.regions_layer = ipyleaflet.LayerGroup() # self.index_mapping = {} self.output = widgets.Output() for i, feature in enumerate(geo_json["features"]): if feature["geometry"]["type"] == "Polygon": feature["geometry"]["type"] = "MultiPolygon" feature["geometry"]["coordinates"] = [feature["geometry"]["coordinates"]] polygon = ipyleaflet.GeoJSON(data=feature, hover_style={'fillColor': 'red', 'fillOpacity': 0.6}) self.regions_layer.add_layer(polygon) # self.index_mapping[feature['properties'][index_key]] = i @self.output.capture() # @vaex.jupyter.debounced(DEBOUNCE_SLICE) def on_hover(index=i, **properties): # index_value = properties[index_key] # index = self.index_mapping[index_value] self.state.x_slice = index#event['data']['index'] self.reset_slice() # self.set_transparancy(self.state.x_slice) #print(viz_state.grid.sum()) polygon.on_hover(on_hover) # @self.output.capture() # def on_click(index=i, **properties): # if self.state.x_slice : # self.state.x_slice = None # else: # self.state.x_slice = None # self.reset_slice() # # self.set_transparancy(self.state.x_slice) # #print(viz_state.grid.sum()) # polygon.on_click(on_click) self.map.add_layer(self.regions_layer) # self.state.observe(self.update_bars, ['grid', 'grid_sliced']) # self.observe(self.update_bars, ['normalize']) # self.regions_layer.on_hover(on_hover) # self.reset_opacities() # self.create_viz() self.widget = widgets.HBox([self.control, widgets.VBox([self.map, self.output])])
def __init__(self, output, presenter, map=None, zoom=12, **kwargs): super().__init__(**kwargs) self.output = output self.presenter = presenter self.map = map self._zoom = zoom self.last_image_layer = None center = self.x_min + (self.x_max - self.x_min) / 2, self.y_min + ( self.y_max - self.y_min) / 2 center = center[1], center[0] self.map = ll.Map(center=center, zoom=self._zoom) widgets.dlink((self.map, 'west'), (self, 'x_min')) widgets.dlink((self.map, 'east'), (self, 'x_max')) widgets.dlink((self.map, 'north'), (self, 'y_min')) widgets.dlink((self.map, 'south'), (self, 'y_max')) self.widget = self.map
def create_map(self, basemap, center, zoom): ''' create map and set some parameters ''' # define map kwargs map_kwargs = dict() map_kwargs['center'] = center map_kwargs['zoom'] = zoom map_kwargs['zoom_control'] = False map_kwargs['attribution_control'] = False map_kwargs['scroll_wheel_zoom'] = True # build map m = ipyl.Map(basemap=basemap, **map_kwargs) # set layout height m.layout = ipyw.Layout(height='800px') return m
def get_ipyleaflet_map_with_center_location(cen_lon, cen_lat, zoom_level): """Creates ipyleaflet map object and fit the map using the center point location and zoom level Args: cen_lon (float): longitude of map's center location cen_lat (float): latitude of map's center location zoom_level (int): initial zoom level of the map Returns: map (ipyleaflet.Map): ipyleaflet Map object """ map = ipylft.Map(center=(cen_lon, cen_lat), zoom=zoom_level, basemap=ipylft.basemaps.Stamen.Toner, crs=projections.EPSG3857, scroll_wheel_zoom=True) return map
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 create_widget(self, output, plot, dataset, limits): self.plot = plot self.dataset = dataset self.output = output self.limits = np.array(limits)[:2].tolist() if self.map is None: (xmin, xmax), (ymin, ymax) = limits[:2] center = xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2 center = center[1], center[0] self.map = ll.Map(center=center, zoom=self._zoom) self.map.observe(self._update_limits, "north") self.map.observe(self._update_limits, "east") self.map.observe(self._update_limits, "south") self.map.observe(self._update_limits, "west") # self.map.bounds = self.limits # self.limits = self.map.bounds[1], self.map.bounds[0] # np.array(limits).tolist() # print(self.map.bounds, self.map.west) # print(self.limits) self.widget = self.map