Exemplo n.º 1
0
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
Exemplo n.º 2
0
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
Exemplo n.º 3
0
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
Exemplo n.º 4
0
    def __init__(self, **kwargs):
        super(Map, self).__init__(**kwargs)
        self.bapwidget = kwargs.get('bapwidget')
        self.map = ui.Map()
        lc = LayersControl()
        self.map.add_control(lc)
        self.name = Text(description='Name', value='BAP_composite')
        self.make_name_button = Button(description='Make name')
        self.visualization = Select(description='VisParams',
                                    options=['NSR', 'RGB'],
                                    value='NSR')
        self.add_map_button = Button(
            description='Add using map bounds',
            tooltip='Add composite to Map using Map bounds')
        self.add_site_button = Button(
            description='Add using Site',
            tooltip='Add composite to Map using the Site')

        self.add_map_button.on_click(self.addMapComposite)
        self.add_site_button.on_click(self.addSiteComposite)
        self.make_name_button.on_click(self.makeName)

        # Tabs
        self.tabs = Tab([
            VBox([
                HBox([self.name, self.make_name_button]), self.visualization,
                self.add_map_button, self.add_site_button
            ]), self.map.inspector_wid, self.map.layers_widget
        ])

        self.tabs.set_title(0, 'Composite')
        self.tabs.set_title(1, 'Inspector')
        self.tabs.set_title(2, 'Layers')

        self.children = [self.map, self.tabs]
Exemplo n.º 5
0
def display_da(da, cm):
    """
    Description:
      Display a colored xarray.DataArray on a map and allow the user to select a point
    -----
    Input:
      da: xarray.DataArray
      cm: matplotlib colormap
    Output:
      m: map to interact with
      dc: draw control
    Usage:
      View, interact and point a location to be used later on
    """

    # Check inputs
    assert 'dataarray.DataArray' in str(
        type(da)), "da must be an xarray.DataArray"

    # convert DataArray to png64
    imgurl = da_to_png64(da, cm)

    # Display
    latitude = (da.latitude.values.min(), da.latitude.values.max())
    longitude = (da.longitude.values.min(), da.longitude.values.max())

    margin = -0.5
    zoom_bias = 0
    lat_zoom_level = _degree_to_zoom_level(margin=margin, *
                                           latitude) + zoom_bias
    lon_zoom_level = _degree_to_zoom_level(margin=margin, *
                                           longitude) + zoom_bias
    zoom = min(lat_zoom_level, lon_zoom_level) - 1
    center = [np.mean(latitude), np.mean(longitude)]
    m = Map(center=center, zoom=zoom)

    # http://leaflet-extras.github.io/leaflet-providers/preview/
    esri = basemap_to_tiles(basemaps.Esri.WorldImagery)
    m.add_layer(esri)

    io = ImageOverlay(name='DataArray',
                      url=imgurl,
                      bounds=[(latitude[0], longitude[0]),
                              (latitude[1], longitude[1])])
    m.add_layer(io)

    dc = DrawControl(circlemarker={'color': 'yellow'}, polygon={}, polyline={})
    m.add_control(dc)

    m.add_control(LayersControl())

    return m, dc, io
Exemplo n.º 6
0
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
Exemplo n.º 7
0
def run():
    global m, dc, center
    center = list(reversed(poly.centroid().coordinates().getInfo()))
    m = Map(center=center, zoom=10, layout={'height': '400px'})
    osm = basemap_to_tiles(basemaps.OpenStreetMap.HOT)
    mb = TileLayer(
        url=
        "https://api.mapbox.com/styles/v1/mapbox/satellite-streets-v9/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWNhbnR5IiwiYSI6ImNpcjRsMmJxazAwM3hoeW05aDA1cmNkNzMifQ.d2UbIugbQFk2lnU8uHwCsQ"
    )
    sm_control = SplitMapControl(left_layer=osm, right_layer=mb)
    m.add_control(dc)
    m.add_control(sm_control)
    m.add_control(LayersControl())
    display(m)
    display(box)
Exemplo n.º 8
0
    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)
Exemplo n.º 9
0
    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)
Exemplo n.º 10
0
def addImageLayer(inMap, filename, spatial_extent, name):
    im = PIL.Image.open(filename)
    f = BytesIO()
    im.save(f, 'png')
    data = b64encode(f.getvalue())
    data = data.decode('ascii')
    imgurl = 'data:image/png;base64,' + data

    image = ImageOverlay(url=imgurl,
                         bounds=((spatial_extent['south'],
                                  spatial_extent['east']),
                                 (spatial_extent['north'],
                                  spatial_extent['west'])),
                         name=name)
    layers_control = LayersControl(position='topright')
    inMap.map.add_layer(image)
    return
Exemplo n.º 11
0
    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)
Exemplo n.º 12
0
    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)
Exemplo n.º 13
0
def draw_map():
    """
    Description:
      Create an empty map to be used to draw a polygon or rectangle
    -----
    Input:
      None
    Output:
      m: empty map ti interact with
      dc: draw control
    Usage:
      Draw a polygon or a rectangle
    """

    # Location
    center = [47, 8]
    zoom = 7
    m = Map(center=center, zoom=zoom)

    # Layers
    # http://leaflet-extras.github.io/leaflet-providers/preview/
    esri = basemap_to_tiles(basemaps.Esri.WorldImagery)
    m.add_layer(esri)
    terrain = basemap_to_tiles(basemaps.Stamen.Terrain)
    m.add_layer(terrain)
    mapnik = basemap_to_tiles(basemaps.OpenStreetMap.Mapnik)
    m.add_layer(mapnik)

    m.add_control(LayersControl())

    # Controls
    dc = DrawControl(rectangle={'shapeOptions': {'color': '#0000FF'}},
                     polygon={'shapeOptions': {'color': '#0000FF'}},
                     marker={},
                     polyline={},
                     circle={},
                     circlemarker={}
                    )

    m.add_control(dc)

    return m, dc
Exemplo n.º 14
0
 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"))
Exemplo n.º 15
0
def get_ipy(wards, wardcentres, const, constcentres, x="ratio"):
    from ipyleaflet import Map, Marker, GeoJSON, basemaps, GeoData, LayersControl
    from pymapbox.utils import geojson

    m = Map()
    m.center = [52.1917, -1.7083]
    m.zoom = 10
    m.scroll_wheel_zoom = True

    x, cats, colorset, wards = get_cats(x, wards)

    # create style columns
    wards["fillcolor"] = wards[x].map(dict(zip(cats, colorset)))
    wards = wards[["geometry", "wardname", "fillcolor"]]
    wardcentres = wardcentres[["wardname", "geometry"]]

    def wardstyle(row):
        return dict(fillColor=row["properties"]["fillcolor"], fillOpacity=1)

    layer = GeoJSON(
        name="constituencies",
        data=geojson(const),
        style=dict(fillColor="#00000000", weight=3),
    )
    m.add_layer(layer)

    layer = GeoJSON(
        name="wards",
        data=geojson(wards),
        style_callback=wardstyle,
        style=dict(weight=1),
    )
    m.add_layer(layer)

    m.add_control(LayersControl())

    return m
Exemplo n.º 16
0
    def __init__(self,
                 basemaps=[],
                 dc=False,
                 vinspector=False,
                 gee=True,
                 **kwargs):

        self.world_copy_jump = True

        # Init the map
        super().__init__(
            ee_initialize=
            False,  # we take care of the initialization on our side
            add_google_map=False,
            center=[0, 0],
            zoom=2,
            **kwargs)

        # init ee
        self.ee = gee
        if gee: su.init_ee()

        # init the rasters
        self.loaded_rasters = {}

        # add the basemaps
        self.clear_layers()
        if len(basemaps):
            [self.add_basemap(basemap) for basemap in set(basemaps)]
        else:
            self.add_basemap('CartoDB.DarkMatter')

        # add the base controls
        self.clear_controls()
        self.add_control(ZoomControl(position='topright'))
        self.add_control(LayersControl(position='topright'))
        self.add_control(AttributionControl(position='bottomleft'))
        self.add_control(ScaleControl(position='bottomleft', imperial=False))

        # change the prefix
        for control in self.controls:
            if type(control) == AttributionControl:
                control.prefix = "SEPAL"

        # specific drawing control
        self.set_drawing_controls(dc)

        # Add value inspector
        self.w_vinspector = widgets.Checkbox(
            value=False,
            description='Inspect values',
            indent=False,
            layout=widgets.Layout(width='18ex'))

        if vinspector:
            self.add_control(
                WidgetControl(widget=self.w_vinspector, position='topright'))

            link((self.w_vinspector, 'value'), (self, 'vinspector'))

        # Create output space for raster interaction
        self.output_r = widgets.Output(layout={'border': '1px solid black'})
        self.output_control_r = WidgetControl(widget=self.output_r,
                                              position='bottomright')
        self.add_control(self.output_control_r)

        # define interaction with rasters
        self.on_interaction(self._raster_interaction)
Exemplo n.º 17
0
    def __init__(self, basemaps=[], add_google_map=None, **kwargs):
        """  Initialize Sepal Map.

        Args:

            basemap (str): Select one of the Sepal Base Maps available.


        """
        basemap = dict(
            url='http://c.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
            max_zoom=20,
            attribution=
            '&copy; <a href="http://www.openstreetmap.org/copyright">\
            OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">\
            CartoDB</a>',
            name='CartoDB.DarkMatter')

        basemap = basemap_to_tiles(basemap)

        if not add_google_map:
            add_google_map = False

        super().__init__(**kwargs,
                         add_google_map=add_google_map,
                         basemap=basemap)

        if basemaps:
            for basemap in basemaps:
                self.add_basemap(basemap)

        self.center = [0, 0]
        self.zoom = 2

        super().clear_controls()

        self.add_control(ZoomControl(position='topright'))
        self.add_control(LayersControl(position='topright'))
        self.add_control(AttributionControl(position='bottomleft'))
        self.add_control(ScaleControl(position='bottomleft', imperial=False))

        # Create output space for raster interaction
        output_r = widgets.Output(layout={'border': '1px solid black'})
        output_control_r = WidgetControl(widget=output_r,
                                         position='bottomright')
        self.add_control(output_control_r)

        self.loaded_rasters = {}

        # Define a behavior when ispector checked and map clicked
        def raster_interaction(**kwargs):

            if kwargs.get('type') == 'click' and self.inspector_checked:
                latlon = kwargs.get('coordinates')
                self.default_style = {'cursor': 'wait'}

                local_rasters = [
                    lr.name for lr in self.layers
                    if isinstance(lr, LocalTileLayer)
                ]

                if local_rasters:

                    with output_r:
                        output_r.clear_output(wait=True)

                        for lr_name in local_rasters:

                            lr = self.loaded_rasters[lr_name]
                            lat, lon = latlon

                            # Verify if the selected latlon is the image bounds
                            if any([
                                    lat < lr.bottom, lat > lr.top,
                                    lon < lr.left, lon > lr.right
                            ]):
                                print('Location out of raster bounds')
                            else:
                                #row in pixel coordinates
                                y = int(((lr.top - lat) / abs(lr.y_res)))

                                #column in pixel coordinates
                                x = int(((lon - lr.left) / abs(lr.x_res)))

                                #get height and width
                                h, w = lr.data.shape
                                value = lr.data[y][x]
                                print(f'{lr_name}')
                                print(
                                    f'Lat: {round(lat,4)}, Lon: {round(lon,4)}'
                                )
                                print(f'x:{x}, y:{y}')
                                print(f'Pixel value: {value}')
                else:
                    with output_r:
                        output_r.clear_output()

                self.default_style = {'cursor': 'crosshair'}

        self.on_interaction(raster_interaction)
Exemplo n.º 18
0
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
Exemplo n.º 19
0
def draw_map(lat_ext=None, lon_ext=None):
    """
    Description:
      Create an empty map with a blue rectangle of given <lat_ext>, <lon_ext> to be used to manually
      draw a polygon or rectangle
    -----
    Input:
      lat_ext: latitude extent
      lon_ext: longitude extent
    Output:
      m: empty map ti interact with
      dc: draw control
    Usage:
      Draw a polygon or a rectangle
    """
    # check options combination
    assert not((lat_ext is None) or (lon_ext is None)), \
           'lat_ext and lon_ext are required'
    assert lat_ext[0] < lat_ext[1], 'lat_ext values are in the wrong order'
    assert lon_ext[0] < lon_ext[1], 'lon_ext values are in the wrong order'

    # Location
    center = [np.mean(lat_ext), np.mean(lon_ext)]

    # source: https://sdc.unepgrid.ch:8080/edit/utils/data_cube_utilities/dc_display_map.py
    margin = -0.5
    zoom_bias = 0
    lat_zoom_level = _degree_to_zoom_level(margin=margin, *lat_ext) + zoom_bias
    lon_zoom_level = _degree_to_zoom_level(margin=margin, *lon_ext) + zoom_bias
    zoom = min(lat_zoom_level, lon_zoom_level)

    m = Map(center=center, zoom=zoom, scroll_wheel_zoom=True)

    # Layers
    # http://leaflet-extras.github.io/leaflet-providers/preview/
    esri = basemap_to_tiles(basemaps.Esri.WorldImagery)
    m.add_layer(esri)
    terrain = basemap_to_tiles(basemaps.Stamen.Terrain)
    m.add_layer(terrain)
    mapnik = basemap_to_tiles(basemaps.OpenStreetMap.Mapnik)
    m.add_layer(mapnik)

    rectangle = Rectangle(bounds=((lat_ext[0], lon_ext[0]), (lat_ext[1],
                                                             lon_ext[1])),
                          color='red',
                          weight=2,
                          fill=False)

    m.add_layer(rectangle)

    m.add_control(LayersControl())

    # Controls
    dc = DrawControl(rectangle={'shapeOptions': {
        'color': '#0000FF'
    }},
                     polygon={'shapeOptions': {
                         'color': '#0000FF'
                     }},
                     marker={},
                     polyline={},
                     circle={},
                     circlemarker={})

    m.add_control(dc)

    return m, dc
Exemplo n.º 20
0
    def __init__(self):
        self.out = widgets.Output(layout={'border': '1px solid black'})
        self.iceflow = IceflowClient()
        self.last_orders = None
        self.current_projection = 'north'
        self.clear = True
        self.controls = []
        self.credentials = None
        self.start_date = datetime(1993, 1, 1)
        self.end_date = datetime.now()
        slider_dates = [(date.strftime(' %Y-%m-%d '), date) for date in
                        pd.date_range(datetime(1993, 1, 1),
                                      datetime.now(),
                                      freq='D')]
        slider_index = (0, len(slider_dates) - 1)

        self.username = widgets.Text(
            value='',
            description='User:'******'Your NASA EarthData username ',
            disabled=False
        )
        self.password = widgets.Password(
            value='',
            placeholder='Enter password',
            description='Password:'******'',
            description='Email:',
            placeholder='Your EarthData e-mail',
            disabled=False
        )
        self.credentials_button = widgets.Button(description='Set Credentials', )
        self.projection = widgets.Dropdown(
            options=['global', 'south', 'north'],
            description='Hemisphere:',
            disabled=False,
            value='north'
        )
        self.dataset = widgets.SelectMultiple(
            options=['ATM1B', 'GLAH06', 'ILVIS2'],
            value=['ATM1B'],
            rows=4,
            description='Datasets',
            disabled=False
        )
        self.itrf = widgets.Dropdown(
            options=[None, 'ITRF2000', 'ITRF2008', 'ITRF2014'],
            disabled=False,
            description='ITRF:',
            layout={'width': 'max-content',
                    'display': 'flex',
                    'description_width': 'initial'}
        )
        self.epoch = widgets.Text(
            value='',
            description='Epoch:',
            placeholder='i.e. 2008.1',
            disabled=False
        )
        self.is2 = widgets.Dropdown(
            options=['None', 'ATL03', 'ATL06', 'ATL07', 'ATL08'],
            description='ICESat 2:',
            disabled=False,
        )
        self.dates_range = widgets.SelectionRangeSlider(
            options=slider_dates,
            index=slider_index,
            continuous_update=False,
            description='Date Range',
            orientation='horizontal',
            layout={'width': '90%'})

        self.granule_count = widgets.Button(description="Get Raw Granule Count",
                                            display='flex',
                                            flex_flow='column',
                                            align_items='stretch', )
        self.granule_count.style.button_color = 'lightgreen'
        self.granule_count.layout.width = 'auto'
        self.print_parameters = widgets.Button(description="Print Current Parameters",
                                               display='flex',
                                               flex_flow='column',
                                               align_items='stretch', )
        self.print_parameters.style.button_color = 'lightgreen'
        self.print_parameters.layout.width = 'auto'

        self.post_order = widgets.Button(description="Place Data Order",
                                         display='flex',
                                         flex_flow='column',
                                         align_items='stretch', )
        self.post_order.style.button_color = 'lightblue'
        self.post_order.layout.width = 'auto'

        self.check_order_status = widgets.Button(description="Order status",
                                                 display='flex',
                                                 flex_flow='column',
                                                 align_items='stretch', )
        self.check_order_status.style.button_color = 'lightblue'
        self.check_order_status.layout.width = 'auto'

        self.download_button = widgets.Button(description="Download completed orders",
                                              display='flex',
                                              flex_flow='column',
                                              align_items='stretch', )
        self.download_button.style.button_color = 'lightblue'
        self.download_button.layout.width = 'auto'

        self.selection_buttons = widgets.HBox([self.granule_count,
                                               self.print_parameters,
                                               self.post_order,
                                               self.check_order_status,
                                               self.download_button])
        self.selection_controls = widgets.VBox([self.projection,
                                                self.dataset,
                                                self.itrf,
                                                self.epoch,
                                                self.is2,
                                                self.dates_range,
                                                self.selection_buttons])
        self.controls.append(self.selection_controls)
        self.layers_control = LayersControl(position='topright')
        # Map Components
        place_marker = Marker(icon=AwesomeIcon(name="check", marker_color='green', icon_color='darkgreen'))
        self.search_control = SearchControl(
            position="topleft",
            url='https://nominatim.openstreetmap.org/search?format=json&q={s}',
            zoom=5,
            marker=place_marker
        )
        self.dc = DrawControl(
            circlemarker={},
            polyline={},
            rectangle={
                "shapeOptions": {
                    "fillColor": "#cc00cc",
                    "color": "#cc00cc",
                    "fillOpacity": 0.5
                }
            })
        self.file_upload = widgets.FileUpload(
            accept='.json,.geojson,.shp',
            multiple=False  # True to accept multiple files upload else False
        )

        # Now we are going to link the controls to the relevant events
        self.dates_range.observe(self.dates_changed, 'value')
        self.projection.observe(self.hemisphere_change)
        self.credentials_button.on_click(self.set_credentials)
        self.granule_count.on_click(self.query_cmr)
        self.print_parameters.on_click(self.get_parameters)
        self.post_order.on_click(self.place_data_orders)
        self.check_order_status.on_click(self.order_statuses)
        self.download_button.on_click(self.download_orders)
                              layer_type='marker', filter_on='document', color='red')
    well_layer_no_docs = create_layer(wells, 'wells with docs',
                                      label_col='wlbWell', secondary_label_col='document',
                                      layer_type='marker', filter_on='document', inverse=True, color='lightGray')

    marker_cluster = MarkerCluster(markers=well_layer.layers, name='Wells with Docs')
    marker_cluster2 = MarkerCluster(markers=well_layer_no_docs.layers, name='Wells without Docs')
    # marker_cluster.add_layer(well_layer)
    m.add_layer(structure_layer_docs)
    m.add_layer(structure_layer)
    m.add_layer(fields_layer_docs)
    m.add_layer(fields_layer)
    m.add_layer(subareas_layer)
    m.add_layer(subareas_layer_docs)
    m.add_layer(facilities_layer_docs)
    m.add_layer(facilities_layer)
    m.add_layer(discoveries_layer_docs)
    m.add_layer(discoveries_layer)
    m.add_layer(marker_cluster)
    m.add_layer(marker_cluster2)
    m.add_control(LayersControl())
    m.add_control(FullScreenControl())
    comments = []

    for i in check_cols:
        comments.append(create_layer(final_dataframe[final_dataframe[i] != "Empty"],
                                     i, label_col='wlbWellbor', secondary_label_col=i, layer_type='marker',
                                     color='green'))

        m.add_layer(comments[-1])
    m
Exemplo n.º 22
0
def plot_routing_product_with_ipyleaflet(path_to_product_folder,
                                         version_number=''):
    product_folder = path_to_product_folder
    if version_number != '':
        version_number = '_' + version_number
    path_subbasin = os.path.join(product_folder,
                                 'finalcat_info' + version_number + '.shp')
    path_river = os.path.join(product_folder,
                              'finalcat_info_riv' + version_number + '.shp')
    path_cllake = os.path.join(product_folder,
                               'sl_connected_lake' + version_number + '.shp')
    path_ncllake = os.path.join(
        product_folder, 'sl_non_connected_lake' + version_number + '.shp')

    subbasin = geopandas.read_file(path_subbasin)
    river = geopandas.read_file(path_river)
    subbasin = subbasin.to_crs("EPSG:4326")
    river = river.to_crs("EPSG:4326")

    if os.path.exists(path_cllake):
        cllake = geopandas.read_file(path_cllake)
        cllake = cllake.to_crs("EPSG:4326")
    if os.path.exists(path_ncllake):
        ncllake = geopandas.read_file(path_ncllake)
        ncllake = ncllake.to_crs("EPSG:4326")

    cx = subbasin['centroid_x'].mean()
    cy = subbasin['centroid_y'].mean()
    m = Map(center=(cy, cx), zoom=9, basemap=basemaps.Esri.WorldTopoMap)

    subnolake = subbasin[subbasin['Lake_Cat'] == 0].copy(deep=True)
    sub_nolake_map = GeoData(geo_dataframe=subnolake,
                             style={
                                 'color': '#6E6E6E',
                                 'fillColor': '#89CD66',
                                 'opacity': 1,
                                 'weight': 1,
                                 'dashArray': '2',
                                 'fillOpacity': 1
                             },
                             name='Subbasin without lakes')
    subcllake = subbasin[subbasin['Lake_Cat'] == 1].copy(deep=True)
    if len(subcllake) > 0:
        sub_cllake_map = GeoData(geo_dataframe=subcllake,
                                 style={
                                     'color': '#6E6E6E',
                                     'fillColor': '#CDE389',
                                     'opacity': 1,
                                     'weight': 1,
                                     'dashArray': '2',
                                     'fillOpacity': 1
                                 },
                                 name='Subbasin with connected lakes')
    subncllake = subbasin[subbasin['Lake_Cat'] == 2].copy(deep=True)
    if len(subncllake) > 0:
        sub_ncllake_map = GeoData(geo_dataframe=subncllake,
                                  style={
                                      'color': '#6E6E6E',
                                      'fillColor': '#F5F57A',
                                      'opacity': 1,
                                      'weight': 1,
                                      'dashArray': '2',
                                      'fillOpacity': 1
                                  },
                                  name='Subbasin with connected lakes')

    river_map = GeoData(geo_dataframe=river,
                        style={
                            'color': '#0070FF',
                            'fillColor': '#0070FF',
                            'opacity': 1,
                            'weight': 2,
                            'dashArray': '2',
                            'fillOpacity': 1
                        },
                        name='River')
    if os.path.exists(path_cllake):
        cllake_map = GeoData(geo_dataframe=cllake,
                             style={
                                 'color': '#6E6E6E',
                                 'fillColor': '#0070FF',
                                 'opacity': 1,
                                 'weight': 1,
                                 'dashArray': '2',
                                 'fillOpacity': 1
                             },
                             name='Non connected lakes')
    if os.path.exists(path_ncllake):
        ncllake_map = GeoData(geo_dataframe=ncllake,
                              style={
                                  'color': '#6E6E6E',
                                  'fillColor': '#0070FF',
                                  'opacity': 0,
                                  'weight': 1,
                                  'dashArray': '2',
                                  'fillOpacity': 1
                              },
                              name='Connected lakes')

    m.add_layer(sub_nolake_map)
    if len(subcllake) > 0:
        m.add_layer(sub_cllake_map)
    if len(subncllake) > 0:
        m.add_layer(sub_ncllake_map)
    m.add_layer(river_map)
    if os.path.exists(path_cllake):
        m.add_layer(cllake_map)
    if os.path.exists(path_ncllake):
        m.add_layer(ncllake_map)

    m.add_control(LayersControl())
    m.layout.height = "700px"

    return m
Exemplo n.º 23
0
    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)