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 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 __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 rasters_on_map(rasters_list, out_dir, overlay_names_list, geojson_data=None): """ displays a raster on a ipyleaflet map :param rasters_list: rasters to display (rasterio image) :param out_dir: path to the output directory (preview writing) :param overlay_names_list: name of the overlays for the map """ # - get bounding box raster = rasters_list[0] epsg4326 = {'init': 'EPSG:4326'} bounds = transform_bounds(raster.crs, epsg4326, *raster.bounds) center = [(bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2] # - get centered map m = Map(center=(center[-1], center[0]), zoom=10) # - plot quicklook for raster, overlay_name in zip(rasters_list, overlay_names_list): bounds = transform_bounds(raster.crs, epsg4326, *raster.bounds) quicklook_url = os.path.join( out_dir, "PREVIEW_{}.JPG".format(datetime.datetime.now())) write_quicklook(raster, quicklook_url) quicklook = ImageOverlay(url=quicklook_url, bounds=((bounds[1], bounds[0]), (bounds[3], bounds[2])), name=overlay_name) m.add_layer(quicklook) m.add_control(LayersControl()) m.add_control(FullScreenControl()) # - add geojson data if geojson_data is not None: geo_json = GeoJSON(data=geojson_data, style={ 'color': 'green', 'opacity': 1, 'weight': 1.9, 'dashArray': '9', 'fillOpacity': 0.1 }) m.add_layer(geo_json) # - add draw control dc = DrawControl() m.add_control(dc) return m, dc
def flight_map(self, center=None, basemap=None, zoom=8): """Display interactive map of the flight path. (Jupyter notebook only.) Parameters ---------- center: tuple, optional (latitude, longitude) center of the map. The default is the average of the flight's lat/lon bounding box. basemap: str, or list or tuple of str, optional Name of the base map available in ipyleaflet. Default: ``('Esri.WorldImagery', 'OpenTopoMap')``. zoom: int, optional Map zoom level. Default is 8. """ if not display_map: raise RuntimeError('Cannot display map') if basemap is None: basemap = ('Esri.WorldImagery', 'OpenTopoMap') elif isinstance(basemap, str): basemap = (basemap, ) elif not isinstance(basemap, (list, tuple)): raise TypeError('basemap is not a str, list, or tuple') base_layers = list() for layer in basemap: name_parts = layer.split('.') base_layer = basemaps for p in name_parts: base_layer = base_layer[p] if not isinstance(base_layer, dict): raise TypeError('base layer not a dict') base_layers.append(basemap_to_tiles(base_layer)) data = self._flight flight_lat = data['latitude'] flight_lon = data['longitude'] if center is None: center = (flight_lat.mean(), flight_lon.mean()) flight_path = Polyline( locations=[np.column_stack((flight_lat, flight_lon)).tolist()], color='blue', fill=False, name='Flight path') flight_map = Map(center=center, zoom=int(zoom)) for _ in base_layers: flight_map.add_layer(_) flight_map.add_layer(flight_path) flight_map.add_control(FullScreenControl()) flight_map.add_control(LayersControl()) display(flight_map)
def __init__(self, **kwargs): if "center" not in kwargs: kwargs["center"] = [40, -100] if "zoom" not in kwargs: kwargs["zoom"] = 4 if "scroll_wheel_zoom" not in kwargs: kwargs["scroll_wheel_zoom"] = True super().__init__(**kwargs) if "height" not in kwargs: self.layout.height = "600px" else: self.layout.height = kwargs["height"] self.add_control(FullScreenControl()) self.add_control(LayersControl(position="topright")) self.add_control(DrawControl(position="topleft")) self.add_control(MeasureControl()) self.add_control(ScaleControl(position="bottomleft")) main_toolbar(self) if "google_map" not in kwargs: layer = TileLayer( url="https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}", attribution="Google", name="Google Maps", ) self.add_layer(layer) else: if kwargs["google_map"] == "ROADMAP": layer = TileLayer( url="https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}", attribution="Google", name="Google Maps", ) self.add_layer(layer) elif kwargs["google_map"] == "HYBRID": layer = TileLayer( url="https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}", attribution="Google", name="Google Satellite", ) self.add_layer(layer)
def _addControls(self): # Add Controls self._m.add_control( MeasureControl(position='bottomleft', active_color='orange', primary_length_unit='kilometers')) self._m.add_control(FullScreenControl()) self._m.add_control(ScaleControl(position='bottomleft')) searchMarker = Marker(icon=AwesomeIcon( name="check", marker_color='green', icon_color='darkred')) self._m.add_control( SearchControl( position="topleft", url= 'https://nominatim.openstreetmap.org/search?format=json&q={s}', zoom=self._zoom, marker=searchMarker))
def __init__(self, center, zoom): self.map = Map(center=center, zoom=zoom, scroll_wheel_zoom=True, interpolation='nearest') self.bbox = [] self.point_coords = [] self.figure = None self.figure_widget = None feature_collection = {'type': 'FeatureCollection', 'features': []} draw = DrawControl( circlemarker={}, polyline={}, polygon={}, marker={"shapeOptions": { "original": {}, "editing": {}, }}, rectangle={"shapeOptions": { "original": {}, "editing": {}, }}) self.map.add_control(draw) def handle_draw(target, action, geo_json): feature_collection['features'] = [] feature_collection['features'].append(geo_json) if feature_collection['features'][0]['geometry'][ 'type'] == 'Point': self.point_coords = feature_collection['features'][0][ 'geometry']['coordinates'] else: coords = feature_collection['features'][0]['geometry'][ 'coordinates'][0] polygon = shapely.geometry.Polygon(coords) self.bbox = polygon.bounds layers_control = LayersControl(position='topright') self.map.add_control(layers_control) self.map.add_control(FullScreenControl()) self.map.add_layer(basemap_to_tiles(basemaps.Esri.WorldImagery)) draw.on_draw(handle_draw)
def __init__(self, **kwargs): """Map class """ if "center" not in kwargs: kwargs["center"] = [40, -100] if "zoom" not in kwargs: kwargs['zoom'] = 4 if "scroll_wheel_zoom" not in kwargs: kwargs["scroll_wheel_zoom"] = True super().__init__(**kwargs) if "height" not in kwargs: self.layout.height = "600px" else: self.layout.height = kwargs['height'] self.add_control(FullScreenControl()) self.add_control(LayersControl(position="bottomright")) self.add_control(DrawControl(position="topleft")) self.add_control(MeasureControl()) self.add_control(ScaleControl(position="bottomleft")) main_toolbar(self) if "google_map" not in kwargs or kwargs["google_map"] == "ROADMAP": layer = TileLayer( url="https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}", attribution="Google", name="Google Maps") self.add_layer(layer) elif kwargs["google_map"] == "HYBRID": layer = TileLayer( url="https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}", attribution="Google", name="Google Satellite") self.add_layer(layer) if 'in_csv' in kwargs: in_csv = kwargs['in_csv'] x = kwargs['x'] y = kwargs['y'] header = kwargs['header'] self.add_points_from_csv(in_csv, x, y, header)
def add_map(self, layers=None): _layers = [Graticule()] if layers is not None: _layers += layers return Map(layers=_layers, controls=(FullScreenControl(), StatusBarControl(), LayersControl(collapsed=False, position="topright")), crs="CAR", center=(0, 0), min_zoom=-5, max_zoom=+5, interpolation="nearest", zoom=0, scroll_wheel_zoom=True, fade_animation=False, world_copy_jump=True, style=MapStyle(cursor="default"), default_style=MapStyle(cursor="default"), dragging_style=MapStyle(cursor="default"))
reqPassing = urllib2.Request( "http://api.open-notify.org/iss-pass.json?lat=48.634566&lon=8.09760") responsePassing = urllib2.urlopen(reqPassing) fetchPassing = json.loads(responsePassing.read()) passTime = int(fetchPassing['request']['datetime']) passTimeCounts = fetchPassing['request']['passes'] for i in range(passTimeCounts): riseTime = int(fetchPassing['response'][i]['risetime']) print( "ISS Overflight " + str(i + 1) + ": " + datetime.utcfromtimestamp(passTime).strftime('%Y-%m-%d %H:%M:%S')) i = +1 m = Map(basemap=basemaps.Esri.WorldImagery, center=(lat, long), zoom=2, scroll_wheel_zoom=True) m.add_layer( Marker( location=(lat, long), title="ISS", icon=Icon(icon_url= "https://img.icons8.com/fluent/48/000000/gps-device.png", icon_size=[20, 20]))) m.add_control(FullScreenControl()) m.add_control(ScaleControl(position='bottomleft')) m.save('current state.html', title="Space Radar") driver.refresh() time.sleep(30.0)
# add heatmap layer to map jakarta_heatmap.add_layer(heatmap_layer) # display map jakarta_heatmap # In[19] from ipyleaflet import Map, FullScreenControl # create map full_screen_map = Map(zoom=1) # create control control = FullScreenControl() # add control to map full_screen_map.add_control(control) # display map full_screen_map # In[20] import ipyleaflet from ipyleaflet import DrawControl # create map draw_control_map = ipyleaflet.Map(zoom=1)
def show_datasets( dss, mode='leaflet', dst=None, layer_name='Datasets', style={}, simplify=True, tolerance=0.001, # ~100m at equator **kw): """ Display dataset footprints on a Leaflet map. :param mode: leaflet|geojson, geojson only works in JupyterLab, leave it as default :param dst: leaflet map to "show" datasets on, default -- create new one :param layer_name: name to give to the layer :param style: GeoJSON style dictionary - weight - color/fillColor - opacity/fillOpacity - full list of options here: https://leafletjs.com/reference-1.5.0.html#path-option :param simplify: simplify geometries before adding them to map :param tolerance: tolerance in degrees for geometry simplification, default 0.001 ~ 111 meters at equator **kw: Arguments to pass to leaflet.Map(..) constructor """ if mode not in ('leaflet', 'geojson'): raise ValueError('Invalid value for mode, expected: leaflet|geojson') polygons, bbox = dss_to_geojson(dss, bbox=True, simplify=simplify, tolerance=tolerance) if mode == 'geojson': from IPython.display import GeoJSON return GeoJSON(polygons) if mode == 'leaflet': from ipyleaflet import Map, GeoJSON, FullScreenControl, LayersControl if dst is None: center = kw.pop('center', None) zoom = kw.pop('zoom', None) if center is None: center = (bbox.bottom + bbox.top) * 0.5, (bbox.right + bbox.left) * 0.5 if zoom is None: zoom = zoom_from_bbox(bbox) height = kw.pop('height', '600px') width = kw.pop('width', None) m = Map(center=center, zoom=zoom, **kw) m.layout.height = height m.layout.width = width m.add_control(FullScreenControl()) m.add_control(LayersControl()) else: m = dst gg = GeoJSON(data={ 'type': 'FeatureCollection', 'features': polygons }, style=style, hover_style={'color': 'tomato'}, name=layer_name) m.add_layer(gg) if dst is None: return m else: return gg
def mk_map_region_selector(height='600px', **kwargs): from ipyleaflet import Map, WidgetControl, FullScreenControl, DrawControl from ipywidgets.widgets import Layout, Button, HTML from types import SimpleNamespace state = SimpleNamespace(selection=None, bounds=None, done=False) btn_done = Button(description='done', layout=Layout(width='5em')) btn_done.style.button_color = 'green' btn_done.disabled = True html_info = HTML( layout=Layout(flex='1 0 20em', width='20em', height='3em')) def update_info(txt): html_info.value = '<pre style="color:grey">' + txt + '</pre>' m = Map(**kwargs) if len(kwargs) else Map(zoom=2) m.scroll_wheel_zoom = True m.layout.height = height widgets = [ WidgetControl(widget=btn_done, position='topright'), WidgetControl(widget=html_info, position='bottomleft'), ] for w in widgets: m.add_control(w) draw = DrawControl() draw.circle = {} draw.polyline = {} draw.circlemarker = {} shape_opts = { "fillColor": "#fca45d", "color": "#000000", "fillOpacity": 0.1 } draw.rectangle = {"shapeOptions": shape_opts} poly_opts = {"shapeOptions": dict(**shape_opts)} poly_opts["shapeOptions"]["original"] = dict(**shape_opts) poly_opts["shapeOptions"]["editing"] = dict(**shape_opts) draw.polygon = poly_opts draw.edit = True draw.remove = True m.add_control(draw) m.add_control(FullScreenControl()) def on_done(btn): state.done = True btn_done.disabled = True m.remove_control(draw) for w in widgets: m.remove_control(w) def bounds_handler(event): (lat1, lon1), (lat2, lon2) = event['new'] txt = 'lat: [{:.{n}f}, {:.{n}f}]\nlon: [{:.{n}f}, {:.{n}f}]'.format( lat1, lat2, lon1, lon2, n=4) update_info(txt) state.bounds = dict(lat=(lat1, lat2), lon=(lon1, lon2)) def on_draw(event): v = event['new'] action = event['name'] if action == 'last_draw': state.selection = v['geometry'] elif action == 'last_action' and v == 'deleted': state.selection = None btn_done.disabled = state.selection is None draw.observe(on_draw) m.observe(bounds_handler, ('bounds', )) btn_done.on_click(on_done) return m, state
def mk_map_region_selector(map=None, height="600px", **kwargs): from ipyleaflet import Map, WidgetControl, FullScreenControl, DrawControl from ipywidgets.widgets import Layout, Button, HTML from types import SimpleNamespace state = SimpleNamespace(selection=None, bounds=None, done=False) btn_done = Button(description="done", layout=Layout(width="5em")) btn_done.style.button_color = "green" btn_done.disabled = True html_info = HTML(layout=Layout(flex="1 0 20em", width="20em", height="3em")) def update_info(txt): html_info.value = '<pre style="color:grey">' + txt + "</pre>" def render_bounds(bounds): (lat1, lon1), (lat2, lon2) = bounds txt = "lat: [{:.{n}f}, {:.{n}f}]\nlon: [{:.{n}f}, {:.{n}f}]".format( lat1, lat2, lon1, lon2, n=4 ) update_info(txt) if map is None: m = Map(**kwargs) if len(kwargs) else Map(zoom=2) m.scroll_wheel_zoom = True m.layout.height = height else: m = map render_bounds(m.bounds) widgets = [ WidgetControl(widget=btn_done, position="topright"), WidgetControl(widget=html_info, position="bottomleft"), ] for w in widgets: m.add_control(w) draw = DrawControl() draw.circle = {} draw.polyline = {} draw.circlemarker = {} shape_opts = {"fillColor": "#fca45d", "color": "#000000", "fillOpacity": 0.1} draw.rectangle = {"shapeOptions": shape_opts, "metric": ["km", "m"]} poly_opts = {"shapeOptions": dict(**shape_opts)} poly_opts["shapeOptions"]["original"] = dict(**shape_opts) poly_opts["shapeOptions"]["editing"] = dict(**shape_opts) draw.polygon = poly_opts draw.edit = True draw.remove = True m.add_control(draw) m.add_control(FullScreenControl()) def on_done(btn): state.done = True btn_done.disabled = True m.remove_control(draw) for w in widgets: m.remove_control(w) def bounds_handler(event): bounds = event["new"] render_bounds(bounds) (lat1, lon1), (lat2, lon2) = bounds state.bounds = dict(lat=(lat1, lat2), lon=(lon1, lon2)) def on_draw(event): v = event["new"] action = event["name"] if action == "last_draw": state.selection = v["geometry"] elif action == "last_action" and v == "deleted": state.selection = None btn_done.disabled = state.selection is None draw.observe(on_draw) m.observe(bounds_handler, ("bounds",)) btn_done.on_click(on_done) return m, state
def __init__(self, **kwargs): if "center" not in kwargs: kwargs["center"] = [40, -100] if "zoom" not in kwargs: kwargs["zoom"] = 4 if "scroll_wheel_zoom" not in kwargs: kwargs["scroll_wheel_zoom"] = True super().__init__(**kwargs) if "height" not in kwargs: self.layout.height = "600px" else: self.layout.height = kwargs["height"] self.add_control(FullScreenControl()) self.add_control(LayersControl(position="topright")) self.add_control(DrawControl(position="topleft")) self.add_control(MeasureControl()) self.add_control(ScaleControl(position="bottomleft")) self.toolbar = None # tools = { # "folder-open": { # "name": "open_data", # "tooltip": "Open local vector/raster data" # }, # "map": { # "name": "basemap", # "tooltip": "Change basemap" # }, # "gears": { # "name": "whitebox", # "tooltip": "WhiteboxTools for local geoprocessing" # }, # "filter": { # "name": "query", # "tooltip": "Attribute selection" # }, # } # icons = list(tools.keys()) # tooltips = [item["tooltip"] for item in list(tools.values())] # icon_width = "32px" # icon_height = "32px" # n_cols = 3 # n_rows = math.ceil(len(icons) / n_cols) # toolbar_grid = ipywidgets.GridBox( # children=[ # ipywidgets.ToggleButton( # layout=ipywidgets.Layout( # width="auto", height="auto", padding="0px 0px 0px 4px" # ), # button_style="primary", # icon=icons[i], # tooltip=tooltips[i], # ) # for i in range(len(icons)) # ], # layout=ipywidgets.Layout( # width="107px", # grid_template_columns=(icon_width + " ") * n_cols, # grid_template_rows=(icon_height + " ") * n_rows, # grid_gap="1px 1px", # padding="5px", # ), # ) # self.toolbar = toolbar_grid if "google_map" not in kwargs: layer = TileLayer( url="https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}", attribution="Google", name="Google Maps", ) self.add_layer(layer) else: if kwargs["google_map"] == "ROADMAP": layer = TileLayer( url="https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}", attribution="Google", name="Google Maps", ) self.add_layer(layer) elif kwargs["google_map"] == "HYBRID": layer = TileLayer( url="https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}", attribution="Google", name="Google Satellite") self.add_layer(layer) if "basemap" not in kwargs: layer = basemap_to_tiles(basemaps.OpenStreetMap.Mapnik) self.add_layer(layer) else: layer = basemap_to_tiles(kwargs["basemap"]) self.add_layer(layer) main_toolbar(self)
def plotmap(self, metric, climatedf, coorddf, filepath, filename='Map'): sel_cols = ['Location', 'Year', metric] climatedf = climatedf[sel_cols] climatedf = climatedf.reindex(columns=climatedf.columns.tolist() + ['color']) color = [] for (i, j) in climatedf.iterrows(): value = (j[metric] - climatedf[metric].min()) / ( climatedf[metric].max() - climatedf[metric].min()) if (value > 0 and value <= (1 / 6)): color.append('darkblue') elif (value > (1 / 6) and value <= (2 / 6)): color.append('blue') elif (value > (2 / 6) and value <= (3 / 6)): color.append('green') elif (value > (3 / 6) and value <= (4 / 6)): color.append('orange') elif (value > (4 / 6) and value <= (5 / 6)): color.append('red') else: color.append('darkred') climatedf['color'] = color gps_color = pd.merge(climatedf, coorddf, on=['Location']) gps_color.head() newdata = pd.DataFrame([]) for (index, row) in gps_color.iterrows(): row['Latitude'] += random.uniform(0.1, 0.9) row['Longitude'] += random.uniform(0.1, 0.9) newdata = newdata.append(row) center = [39.0119, -98.4842] zoom = 3 i = 0 m = Map(basemap=basemaps.Esri.WorldImagery, center=center, zoom=zoom) for (index, row) in newdata.iterrows(): icon = AwesomeIcon( name='tint', marker_color=row.loc['color'], #'#583470' icon_color='black', spin=False) loc = [row.loc['Latitude'], row.loc['Longitude']] marker = Marker(location=loc, draggable=False, icon=icon) m.add_layer(marker) i += 1 m.add_control(FullScreenControl()) m.save(filepath + "/" + filename + '.html', title=filename) mpl.rcParams.update({'font.size': 10}) fig = plt.figure(figsize=(8, 3)) ax = fig.add_subplot(111) vals = [] for i in range(7): vals.append((( (climatedf[metric].max() - climatedf[metric].min()) / 6) * i) + climatedf[metric].min()) cmap = mpl.colors.ListedColormap([ 'darkblue', 'deepskyblue', 'limegreen', 'orange', 'red', 'darkred' ]) norm = mpl.colors.BoundaryNorm(vals, cmap.N) cb = mpl.colorbar.ColorbarBase(ax, cmap=cmap, norm=norm, spacing='uniform', orientation='horizontal', extend='neither', ticks=vals) cb.set_label(metric) ax.set_position((0.1, 0.45, 0.8, 0.1)) plt.savefig(filepath + "/" + 'legend.jpg', dpi=2000, bbox_inches="tight") file = codecs.open(filepath + "/" + filename + '.html', "r", "utf-8") file_list = file.read().split("\n") file.close() print(file_list) file_list.insert( -3, "<img src='legend.jpg' alt='Plot Legend' style='width:35%;'>") file = codecs.open(filepath + "/" + filename + '.html', "w", "utf-8") file.write("\n".join(file_list)) file.close() return m, fig