def plot(feature, mp=None, style_function=None, **map_kwargs): """Plots a GeoVector in an ipyleaflet map. Parameters ---------- feature : telluric.vectors.GeoVector, telluric.features.GeoFeature, telluric.collections.BaseCollection Data to plot. mp : ipyleaflet.Map, optional Map in which to plot, default to None (creates a new one). style_function : func Function that returns an style dictionary for map_kwargs : kwargs, optional Extra parameters to send to ipyleaflet.Map. """ map_kwargs.setdefault('basemap', basemaps.Stamen.Terrain) if feature.is_empty: warnings.warn("The geometry is empty.") mp = Map(**map_kwargs) if mp is None else mp else: if mp is None: center = feature.envelope.centroid.reproject(WGS84_CRS) zoom = zoom_level_from_geometry(feature.envelope) mp = Map(center=(center.y, center.x), zoom=zoom, **map_kwargs) mp.add_layer(layer_from_element(feature, style_function)) return mp
def plot(feature, mp=None, style_function=None, **map_kwargs): """Plots a GeoVector in an ipyleaflet map. Parameters ---------- feature : Any object with __geo_interface__ Data to plot. mp : ipyleaflet.Map, optional Map in which to plot, default to None (creates a new one). style_function : func Function that returns an style dictionary for map_kwargs : kwargs, optional Extra parameters to send to folium.Map. """ if feature.is_empty: warnings.warn("The geometry is empty.") mp = Map(basemap=basemaps.Stamen.Terrain, ** map_kwargs) if mp is None else mp else: if mp is None: center = feature.envelope.centroid.reproject(WGS84_CRS) zoom = zoom_level_from_geometry(feature.envelope) mp = Map(center=(center.y, center.x), zoom=zoom, basemap=basemaps.Stamen.Terrain, **map_kwargs) mp.add_layer(layer_from_element(feature, style_function)) return mp
def __init__(self, center=(41.8204600, 1.8676800), zoom=9): self.map = Map(center=center, zoom=zoom, basemap=basemaps.OpenStreetMap.HOT) polygon = Polygon(locations=[[]], color="green", fill_color="green") def handle_click(**kwargs): if kwargs.get('type') == 'click': pol = next(layer for layer in self.map.layers if isinstance(layer, Polygon)) coords = kwargs.get('coordinates') if (len(polygon.locations) == 0): pol.locations[0].extend([coords, coords]) else: pol.locations[0].insert(1, coords) self.map.remove_layer(pol) other = Polygon(locations=pol.locations, color="green", fill_color="green") self.map.add_layer(other) if kwargs.get('type') == 'contextmenu': pol = next(layer for layer in self.map.layers if isinstance(layer, Polygon)) self.map.remove_layer(pol) other = Polygon(locations=[[]], color="green", fill_color="green") self.map.add_layer(other) self.map.on_interaction(handle_click) self.map.add_layer(polygon) display(self.map)
def __init__(self, n_days_old_satimg=1): t = datetime.datetime.now() - datetime.timedelta(days=n_days_old_satimg) t_str = t.strftime("%Y-%m-%d") self.m = Map( layers=[ basemap_to_tiles(basemaps.NASAGIBS.ModisTerraTrueColorCR, t_str), ], center=(52.204793, 360.121558), zoom=2, ) self.domain_coords = [] self.polygon = None self.marker_locs = {} self.m.on_interaction(self._handle_map_click) button_reset = Button(description="reset") button_reset.on_click(self._clear_domain) button_save = Button(description="save domain") button_save.on_click(self._save_domain) self.name_textfield = Text(value="domain_name", width=10) self.m.add_control(WidgetControl(widget=button_save, position="bottomright")) self.m.add_control(WidgetControl(widget=button_reset, position="bottomright")) self.m.add_control( WidgetControl(widget=self.name_textfield, position="bottomright") )
def show_map(selected_stats, year): control = WidgetControl(widget=districtbox, position='topright', min_width = 250, max_width=500) # load selected stats into choro_data_all choro_data_all, unit = choro_data_complete[selected_stats], units[selected_stats] # for geo plot extract chosen year and assign to choro_data choro_data = choro_data_all[choro_data_all['year']==year] choro_data = dict(choro_data.drop(columns=['year', 'name']).to_dict('split')['data']) # initialize bar chart with Frankfurt vs Offenbach update_figure('06412', selected_stats, choro_data_all, year) update_figure('06413', selected_stats, choro_data_all, year) # initialize districtbox loading_name, loading_values = id_to_name['06413'], choro_data['06413'] districtbox.value = f'<center><p><b>{loading_name}</b>:</p> {loading_values:g} {unit} {norm_unit}</center>' # set y-axis label fig.update_layout(yaxis_title=f'{stat_dict[selected_stats]} [{unit} {norm_unit}]', yaxis={'range':[0,max(choro_data_all[selected_stats])]}) # define chropleth layer for basic geo plotting layer = Choropleth(geo_data=geo_data,choro_data=choro_data,colormap=cm, style={'fillOpacity': 0.65, 'dashArray': '0, 0', 'weight':1}) # define GeoJSON layer for click and hover event interactions geo_json = GeoJSON(data=geo_data, style={'opacity': 0, 'dashArray': '9', 'fillOpacity': .0, 'weight': 1}, hover_style={'color': 'blue', 'dashArray': '0', 'fillOpacity': 0.7}) # on hover, the districtbox is updated to show properties of the hovered district def update_districtbox(feature, **kwargs): feature['value'] = choro_data[feature['id']] districtbox.value = f'<center><p><b>{id_to_name[feature["id"]]}</b>:</p> {feature["value"]:g} {unit} {norm_unit}</center>' # this function is called upon a click events and triggers figure update with the arguments passed from the map def update_fig_on_click(feature, **kwags): update_figure(feature['id'], selected_stats, choro_data_all, year) geo_json.on_hover(update_districtbox) geo_json.on_click(update_fig_on_click) # add layers and controls; set layout parameters m = Map(basemap=basemaps.OpenStreetMap.Mapnik, center=(50.5,9), zoom=8) m.add_layer(layer) m.add_layer(geo_json) m.add_control(control) m.layout.width = '40%' m.layout.height = '700px' # custom made legend using min/max normalization min_value, max_value = min(choro_data.values()), max(choro_data.values()) legend = LegendControl( {f"{min_value:g} {unit} {norm_unit}": cm(0), #hier f"{min_value+0.5*(max_value-min_value):g} {unit} {norm_unit}": cm(.5), f"{max_value:g} {unit} {norm_unit}": cm(1)}, name= f"{stat_dict[selected_stats]} ({year})", position="bottomleft") m.add_control(legend) return HBox([m, fig], layout=Layout(width='85%'))
def __init__(self, bbox, zoom=8, resolution=10): center = (bbox.min_y + bbox.max_y) / 2, (bbox.min_x + bbox.max_x) / 2 self.map = Map(center=center, zoom=zoom, scroll_wheel_zoom=True) self.resolution = resolution control = DrawControl() control.rectangle = { "shapeOptions": { "fillColor": "#fabd14", "color": "#fa6814", "fillOpacity": 0.2 } } #Disable the rest of draw options control.polyline = {} control.circle = {} control.circlemarker = {} control.polygon = {} control.edit = False control.remove = False control.on_draw(self._handle_draw) self.map.add_control(control) self.bbox = None self.size = None self.rectangle = None self.add_rectangle(bbox.min_x, bbox.min_y, bbox.max_x, bbox.max_y)
def run(): global m,center # center = list(reversed(poly.centroid().coordinates().getInfo())) center = [51.0,6.4] osm = basemap_to_tiles(basemaps.OpenStreetMap.Mapnik) ews = basemap_to_tiles(basemaps.Esri.WorldStreetMap) ewi = basemap_to_tiles(basemaps.Esri.WorldImagery) dc = DrawControl(polyline={},circlemarker={}) dc.rectangle = {"shapeOptions": {"fillColor": "#0000ff","color": "#0000ff","fillOpacity": 0.05}} dc.polygon = {"shapeOptions": {"fillColor": "#0000ff","color": "#0000ff","fillOpacity": 0.05}} dc.on_draw(handle_draw) lc = LayersControl(position='topright') fs = FullScreenControl(position='topleft') mc = MeasureControl(position='topright',primary_length_unit = 'kilometers') m = Map(center=center, zoom=11, layout={'height':'500px'},layers=(ewi,ews,osm),controls=(mc,dc,lc,fs)) # m = Map(center=center, zoom=11, layout={'height':'500px'},controls=(lc,dc,fs,mc,sm_control)) with w_out: w_out.clear_output() print('Algorithm output') display(m) return box
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
def polygon_map(area, source): from ipyleaflet import Map, DrawControl center, zoom = centroid(area, source) m = Map(center=center, zoom=zoom) draw_control = DrawControl() draw_control.polygon = { "shapeOptions": { "fillColor": "#6be5c3", "color": "#6be5c3", "fillOpacity": 1.0 }, "drawError": { "color": "#dd253b", "message": "Oups!" }, "allowIntersection": False } polygon_map.feature_collection = { 'type': 'FeatureCollection', 'features': [] } def handle_draw(self, action, geo_json): """Do something with the GeoJSON when it's drawn on the map""" polygon_map.feature_collection['features'].append(geo_json) draw_control.on_draw(handle_draw) m.add_control(draw_control) return m
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))
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
def draw_interactive_map(): """ Draws interactive map to be able to draw/define a region of interest """ wms_drillholes = WMSLayer( url='http://geo.loop-gis.org/geoserver/loop/wms?', layers='loop:collar_4326', format='image/png', transparent=True, attribution='Drilhole collar from GSWA', name='drillhole collars' ) wms_geol = WMSLayer( url='http://geo.loop-gis.org/geoserver/loop/wms?', layers='loop:2_5m_interpgeop15_4326', format='image/png', transparent=True, opacity=0.4, attribution='Geology data from GSWA', name='geology' ) m =Map(basemap=basemaps.OpenTopoMap, center=(-29,116.5), zoom=8,scroll_wheel_zoom=True) m.add_layer(wms_geol) m.add_layer(wms_drillholes) m.add_control(LayersControl()) dc = DrawControl(rectangle={'shapeOptions': {'color': '#0000FF'}}) m.add_control(dc) m
def print_geojson(geojson, limit=100): center = None j = json.load(StringIO(geojson)) layer_group = LayerGroup() features = j['features'] if limit is not None: features = features[0:limit] for f in features: location = (f['geometry']['coordinates'][1], f['geometry']['coordinates'][0]) marker = Marker(location=location) marker.popup = HTML(str(f['properties'])) layer_group.add_layer(marker) if not center: center = location if not center: center = (0, 0) m = Map(layers=(basemap_to_tiles(basemaps.OpenStreetMap.Mapnik), ), center=center, zoom=8) m.add_layer(layer_group) return m
def SelectMap(): """Create a Map object using ipyleaflet module. Returns: Map,DrawControl (ipyleaflet objects) """ m = Map(basemap=basemaps.Esri.WorldStreetMap, center=(40.853294, 14.305573), zoom=4, dragging=True, scroll_wheel_zoom=True, world_copy_jump=False) draw_control = DrawControl() draw_control.rectangle = { "shapeOptions": { "fillColor": "#fca45d", "color": "#fca45d", "fillOpacity": 0.3 } } # only rectangle selection is provided draw_control.circle = {} draw_control.polygon = {} draw_control.polyline = {} draw_control.circlemarker = {} return m, draw_control
def run(): global m, dc, center # center = list(reversed(poly.centroid().coordinates().getInfo())) center = [51.0, 6.4] osm = basemap_to_tiles(basemaps.OpenStreetMap.Mapnik) ews = basemap_to_tiles(basemaps.Esri.WorldStreetMap) ewi = basemap_to_tiles(basemaps.Esri.WorldImagery) # mb = TileLayer(url="https://api.mapbox.com/styles/v1/mapbox/satellite-streets-v9/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWNhbnR5IiwiYSI6ImNpcjRsMmJxazAwM3hoeW05aDA1cmNkNzMifQ.d2UbIugbQFk2lnU8uHwCsQ", # attribution = "<a href='https://www.mapbox.com/about/maps/'>Mapbox</a> © <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> <strong><a href='https://www.mapbox.com/map-feedback/' target='_blank'>Improve this map</a></strong>" ) # sm_control = SplitMapControl(left_layer=osm,right_layer=ewi) lc = LayersControl(position='topright') fs = FullScreenControl(position='topleft') mc = MeasureControl(position='topright', primary_length_unit='kilometers') m = Map(center=center, zoom=11, layout={'height': '500px'}, layers=(ewi, ews, osm), controls=(mc, dc, lc, fs)) # m = Map(center=center, zoom=11, layout={'height':'500px'},controls=(lc,dc,fs,mc,sm_control)) with w_out: w_out.clear_output() print('Algorithm output') display(m) return box
def drawPOIS(POIS, zoom=12): centerLat, centerLog = 0, 0 # taking the average of all latitude and longitude of all the POIs # to get the center of the map for poi in POIS: centerLat += poi.coordinates[0] centerLog += poi.coordinates[1] centerLat /= len(POIS) centerLog /= len(POIS) center = (centerLog, centerLat) m = Map(center=center, zoom=zoom, close_popup_on_click=False) # creating the popup messages on the markers # with the name of the POI for poi in POIS: name = poi.address.split(",")[0] marker = Marker(location=poi.coordinates[::-1]) text = HTML() text.value = f"{name}" marker.popup = text m.add_layer(marker) return m
def init_map(): lat = 73. lon = 45.748445 center = [lat, lon] zoom = 4 m = Map(default_tiles=TileLayer(opacity=1.0), center=center, zoom=zoom) return m
def __init__(self, session=None): self.session = session self.use_grid = self.settings["enabled_grid"] # generate map grid polygon layers self.grid_layers = LayerGroup() self.grid_dict = {} for feat in above_grid["features"]: level = feat["properties"]["grid_level"] if level == self.use_grid: Cell_object = Cell(feat) #Cell_object.layer.on_click() grid_id = Cell_object.id self.grid_dict[grid_id] = Cell_object self.grid_layers.add_layer(self.grid_dict[grid_id].layer) # make an attribute that will hold selected layer self.selected_layer = LayerGroup() self.map = Map(layers=( esri, self.grid_layers, self.selected_layer, ), center=(65, -100), zoom=3, width="auto", height="auto", scroll_wheel_zoom=True) # map draw controls self.draw_control = DrawControl() self.draw_control.polyline = {} self.draw_control.circle = {} self.draw_control.circlemarker = {} self.draw_control.remove = False self.draw_control.edit = False self.draw_control.polygon = {**draw_style} self.draw_control.rectangle = {**draw_style} self.draw_control.on_draw(self.update_selected_cells) self.map.add_control(self.draw_control) # output display self.output = Output(layout=Layout(width="auto", height="auto")) # make the widget layout self.ui = VBox( [ #header, #HBox([instruct, geojson_text]), self.map, self.output ], layout=Layout(width="auto")) # display ui display(self.ui)
def ipyleaflet_scatterplot_per_class( x, y, center=(0, 0), zoom=5, proportion=1.0, colors=['blue', 'red', 'yellow', 'orange'], m=None, width='600px', height='400px'): if m is None: m = Map(center=center, zoom=zoom) m.layout.width = width m.layout.height = height if proportion < 1.0: n_samples = int(x.shape[0] * proportion) x, y = shuffle(x, y) x = x[:n_samples] y = y[:n_samples] for sample_x, sample_y in zip(x.tolist(), y.tolist()): circle = Circle() circle.location = sample_x circle.radius = 100 circle.color = colors[sample_y] circle.fill_color = colors[sample_y] m.add_layer(circle) return m
def __init__(self, grassimg): self.grassimg = grassimg self.draw_control = None self.zoom = 15 self.center = self.centermap() self.m = Map(default_tiles=TileLayer(opacity=1.0), center=self.center, zoom=self.zoom)
def __create_map(self): # Create the "map" that will be used to display the image # the crs simple, indicates that we will use pixels to locate objects inside the map self.__map = Map(center=(50, 50), zoom=2, crs=projections.Simple, dragging=False, zoom_control=False, double_click_zoom=False, layers=[LocalTileLayer(path='white.png')], layout=dict(width='600px', height='600px')) self.__create_draw_control()
def display_map(self, map_output, hemisphere=None, extra_layers=True): """ Will render the UI using ipyleaflet and jupyter widgets """ self.map_output = map_output self.dc = DrawControl( circlemarker={}, polyline={}, rectangle={ "shapeOptions": { "fillColor": "#cc00cc", "color": "#cc00cc", "fillOpacity": 0.5 } }) if hemisphere is None: projection = widget_projections[self.projection.value] else: projection = widget_projections[hemisphere] # TODO: maybe there is a way to create the map in the constructor # and just update its properties to see if this is faster. self.map = Map(center=projection['center'], zoom=projection['zoom'], max_zoom=projection['max_zoom'], basemap=projection['base_map'], crs=projection['projection']) self.map.add_control(self.dc) self.map.add_control(self.layers_control) self.map.add_control(self.search_control) for ib_layer in flight_layers[self.projection.value]: self.map.add_layer(ib_layer(self.start_date, self.end_date)) if extra_layers: for layer in custom_layers[self.projection.value]: self.map.add_layer(layer) # if self.dc.last_draw['geometry'] is not None: # self.map.add_layer(GeoJSON(name='selected geometry', data=self.dc.last_draw)) self.map.layout.height = '560px' self.out.clear_output() if map_output == 'vertical': if hasattr(self, 'sc'): self.sc.clear_output() else: self.sc = Sidecar(title='Map Widget') with self.sc: display(self.out) with self.out: display(self.map) for component in self.controls: display(component) else: with self.out: display(self.map) display(self.out)
def __init__(self, bounds: tuple): self.layer = None self._leaflet_map = Map(layers=(basemap_to_tiles( basemaps.OpenStreetMap.BlackAndWhite), ), name="Leaflet Map", center=center(bounds), zoom=12, scroll_wheel_zoom=True) self._leaflet_map.add_control(FullScreenControl())
def ipyleaflet_contourmap( center, datapoints=None, contourmap=None, isolines=[0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1], lineopacity=1.0, colormap=linear.viridis, fillopacity=0.7, legend_title='Legend', m=None, zoom=11, width='600px', height='400px'): if m is None: m = Map(center=center, zoom=zoom) m.layout.width = width m.layout.height = height cs = contourmap colors = [ colormap(i / (len(cs.levels) - 1)) for i in range(len(cs.levels) - 1) ] allsegs = cs.allsegs allkinds = cs.allkinds for clev in range(len(cs.allsegs)): kinds = None if allkinds is None else allkinds[clev] segs = split_contours(allsegs[clev], kinds) polygons = Polygon( locations=[p.tolist() for p in segs], # locations=segs[14].tolist(), color=colors[clev], weight=2, opacity=lineopacity, fill_color=colors[clev], fill_opacity=fillopacity) m.add_layer(polygons) if datapoints is not None: m = ipyleaflet_scatterplot_per_class(datapoints[0], datapoints[1], proportion=1.0, m=m) legend_colors = {} for i in reversed(range(len(isolines) - 1)): legend_colors["{:0.1f}-{:0.1f}".format( isolines[i], isolines[i + 1])] = colormap(i / (len(isolines) - 1)) legend = LegendControl(legend_colors, name=legend_title, position="topright") m.add_control(legend) return m
def test_map(): "Test map." from ipyleaflet import Map center = [52.5, 13.4] zoom = 14 m = Map(center=center, zoom=zoom) assert m.center == center assert m.zoom == zoom
def draw_map(lat_longs): center = [37.79481, -122.41186] zoom = 12 m = Map(center=center, zoom=zoom, basemap=basemaps.Hydda.Full) m.layout.height = '650px' pl = Polyline(locations=lat_longs) pl.color = path_color.value pl.fill_color = path_color.value m.add_layer(pl) return m
def map_thick(df1,df2,cols): lat = 73. lon = 45.748445 center = [lat, lon] zoom = 4 m = Map(default_tiles=TileLayer(opacity=1.0), center=center, zoom=zoom) map_ice_thick(df1,m,cols) map_ice_thick(df2,m,cols) #display(m) return m
def showonmap(self): try: from ipyleaflet import Map, Marker except ModuleNotFoundError: print('Non riesco ad importare i moduli.') poi = (self.data['Location']['Y'],self.data['Location']['X']) m = Map(center=poi, zoom=15) marker = Marker(location=poi, draggable=True) m.add_layer(marker); display(m)
def init_map(): m = Map(basemap=dict( url= 'https://cartocdn-gusc.global.ssl.fastly.net/opmbuilder/api/v1/map/named/opm-mars-basemap-v0-1/all/{z}/{x}/{y}.png', attribution='OpenPlanetary', max_zoom=10, name='OPM'), center=(0, 0), zoom=1) return m
def flight_map_leaflet( flight: "Flight", *, zoom: int = 7, highlight: Optional[Dict[str, Union[str, Flight, Callable[[Flight], Optional[Flight]]], ]] = None, airport: Union[None, str, Airport] = None, **kwargs, ) -> Optional[Map]: from traffic.core import Flight from traffic.data import airports last_position = flight.query("latitude == latitude").at() # type: ignore if last_position is None: return None _airport = airports[airport] if isinstance(airport, str) else airport if "center" not in kwargs: if _airport is not None: kwargs["center"] = _airport.latlon else: kwargs["center"] = ( flight.data.latitude.mean(), flight.data.longitude.mean(), ) m = Map(zoom=zoom, **kwargs) if _airport is not None: m.add_layer(_airport) elt = m.add_layer(flight) elt.popup = HTML() elt.popup.value = flight._info_html() if highlight is None: highlight = dict() for color, value in highlight.items(): if isinstance(value, str): value = getattr(Flight, value, None) if value is None: continue assert not isinstance(value, str) f: Optional[Flight] if isinstance(value, Flight): f = value else: f = value(flight) if f is not None: m.add_layer(f, color=color) return m