Example #1
0
def xyz_to_leaflet():
    """Convert xyz tile services to ipyleaflet tile layers.

    Returns:
        dict: A dictionary of ipyleaflet tile layers.
    """
    leaflet_dict = {}

    for key in xyz_tiles:
        name = xyz_tiles[key]["name"]
        url = xyz_tiles[key]["url"]
        attribution = xyz_tiles[key]["attribution"]
        leaflet_dict[key] = ipyleaflet.TileLayer(url=url,
                                                 name=name,
                                                 attribution=attribution,
                                                 max_zoom=22)

    for key in wms_tiles:
        name = wms_tiles[key]["name"]
        url = wms_tiles[key]["url"]
        layers = wms_tiles[key]["layers"]
        fmt = wms_tiles[key]["format"]
        transparent = wms_tiles[key]["transparent"]
        attribution = wms_tiles[key]["attribution"]
        leaflet_dict[key] = ipyleaflet.WMSLayer(
            url=url,
            layers=layers,
            name=name,
            attribution=attribution,
            format=fmt,
            transparent=transparent,
        )

    xyz_dict = get_xyz_dict()
    for item in xyz_dict:
        name = xyz_dict[item].name
        url = xyz_dict[item].build_url()
        attribution = xyz_dict[item].attribution
        if "max_zoom" in xyz_dict[item].keys():
            max_zoom = xyz_dict[item]["max_zoom"]
        else:
            max_zoom = 22
        leaflet_dict[name] = ipyleaflet.TileLayer(url=url,
                                                  name=name,
                                                  max_zoom=max_zoom,
                                                  attribution=attribution)

    if os.environ.get("PLANET_API_KEY") is not None:

        planet_dict = planet_tiles(tile_format="ipyleaflet")
        leaflet_dict.update(planet_dict)

    return leaflet_dict
Example #2
0
 def add_tile_layer(
         self,
         url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
         name=None,
         attribution='',
         opacity=1.0,
         shown=True):
     """Adds a TileLayer to the map.
     
     Args:
         url (str, optional): The URL of the tile layer. Defaults to 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'.
         name (str, optional): The layer name to use for the layer. Defaults to None.
         attribution (str, optional): The attribution to use. Defaults to ''.
         opacity (float, optional): The opacity of the layer. Defaults to 1.
         shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
     """
     try:
         tile_layer = ipyleaflet.TileLayer(url=url,
                                           name=name,
                                           attribution=attribution,
                                           opacity=opacity,
                                           visible=shown)
         self.add_layer(tile_layer)
     except:
         print("Failed to add the specified TileLayer.")
Example #3
0
 def create(self):
     '''
     create layer and throw on the map
     '''
     url = self.get_url()
     self.map_layer = ipyl.TileLayer(url=url, name=self.name)
     self.map.add_layer(self.map_layer)
    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
Example #5
0
    def addFeatureLayer(self, feature, visParams=None, name=None, show=True,
                        opacity=None, replace=True):
        """ Paint a Feature on the map, but the layer underneath is the
        actual added Feature """

        visParams = visParams if visParams else {}

        if isinstance(feature, ee.Feature):
            ty = 'Feature'
        elif isinstance(feature, ee.FeatureCollection):
            ty = 'FeatureCollection'
        else:
            print('The object is not a Feature or FeatureCollection')
            return

        fill_color = visParams.get('fill_color', None)

        if 'outline_color' in visParams:
            out_color = visParams['outline_color']
        elif 'border_color' in visParams:
            out_color = visParams['border_color']
        else:
            out_color = 'black'

        outline = visParams.get('outline', 2)

        proxy_layer = paint(feature, out_color, fill_color, outline)

        thename = name if name else '{} {}'.format(ty, self.addedGeometries)

        img_params = {'bands':['vis-red', 'vis-green', 'vis-blue'],
                      'min': 0, 'max':255}

        # Check if layer exists
        if thename in self.EELayers.keys():
            if not replace:
                print("{} with name '{}' exists already, please choose another name".format(ty, thename))
                return
            else:
                # Get URL, attribution & vis params
                params = getImageTile(proxy_layer, img_params, show, opacity)

                # Remove Layer
                self.removeLayer(thename)
        else:
            # Get URL, attribution & vis params
            params = getImageTile(proxy_layer, img_params, show, opacity)

        layer = ipyleaflet.TileLayer(url=params['url'],
                                     attribution=params['attribution'],
                                     name=thename)

        self._add_EELayer(thename, {'type': ty,
                                    'object': feature,
                                    'visParams': visParams,
                                    'layer': layer})
        return thename
Example #6
0
def click_event(target, m, current_band, df, sample_col, stretch_min, stretch_max, b1, b2, b3):

    pt_index = target['data']['index']
    image_id = df['id'].values[pt_index]
    selected_image = ee.Image(sample_col.filterMetadata('system:index', 'equals', image_id).first())
    tile_url = utils.GetTileLayerUrl(selected_image.visualize(min=stretch_min,
                                                              max=stretch_max,
                                                              bands= [b1, b2, b3]))
    m.add_layer(ipyleaflet.TileLayer(url=tile_url, name=image_id))
Example #7
0
def qms_to_geemap(service_id):

    service_details = get_qms(service_id)
    name = service_details["name"]
    url = service_details["url"]
    attribution = service_details["copyright_text"]

    layer = ipyleaflet.TileLayer(url=url, name=name, attribution=attribution)
    return layer
Example #8
0
    def add_ee_layer(self, ee_object, vis_params={}, name=None, shown=True, opacity=1.0):
        """Adds a given EE object to the map as a layer.
        
        Args:
            ee_object (Collection|Feature|Image|MapId): The object to add to the map.
            vis_params (dict, optional): The visualization parameters. Defaults to {}.
            name (str, optional): The name of the layer. Defaults to 'Layer N'.
            shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
            opacity (float, optional): The layer's opacity represented as a number between 0 and 1. Defaults to 1.
        """
        image = None
        if name is None:
            layer_count = len(self.layers)
            name = 'Layer ' + str(layer_count + 1)

        if not isinstance(ee_object, ee.Image) and not isinstance(ee_object, ee.ImageCollection) and not isinstance(ee_object, ee.FeatureCollection) and not isinstance(ee_object, ee.Feature) and not isinstance(ee_object, ee.Geometry):
            err_str = "\n\nThe image argument in 'addLayer' function must be an instace of one of ee.Image, ee.Geometry, ee.Feature or ee.FeatureCollection."
            raise AttributeError(err_str)

        if isinstance(ee_object, ee.geometry.Geometry) or isinstance(ee_object, ee.feature.Feature) or isinstance(ee_object, ee.featurecollection.FeatureCollection):
            features = ee.FeatureCollection(ee_object)

            width = 2

            if 'width' in vis_params:
                width = vis_params['width']

            color = '000000'

            if 'color' in vis_params:
                color = vis_params['color']

            image_fill = features.style(
                **{'fillColor': color}).updateMask(ee.Image.constant(0.5))
            image_outline = features.style(
                **{'color': color, 'fillColor': '00000000', 'width': width})

            image = image_fill.blend(image_outline)
        elif isinstance(ee_object, ee.image.Image):
            image = ee_object
        elif isinstance(ee_object, ee.imagecollection.ImageCollection):
            image = ee_object.mosaic()

        map_id_dict = ee.Image(image).getMapId(vis_params)
        tile_layer = ipyleaflet.TileLayer(
            url=map_id_dict['tile_fetcher'].url_format,
            attribution='Google Earth Engine',
            name=name,
            opacity=opacity,
            visible=shown
        )
        self.ee_layers.append(ee_object)
        self.ee_layer_names.append(name)
        self.add_layer(tile_layer)
Example #9
0
File: map.py Project: whigg/ipygee
    def addImage(self,
                 image,
                 visParams=None,
                 name=None,
                 show=True,
                 opacity=None,
                 replace=True):
        """ Add an ee.Image to the Map

        :param image: Image to add to Map
        :type image: ee.Image
        :param visParams: visualization parameters. Can have the
            following arguments: bands, min, max.
        :type visParams: dict
        :param name: name for the layer
        :type name: str
        :return: the name of the added layer
        :rtype: str
        """
        # Check if layer exists
        if name in self.EELayers.keys():
            if not replace:
                return self.getLayer(name)
            else:
                # Get URL, attribution & vis params
                params = getImageTile(image, visParams, show, opacity)

                # Remove Layer
                self.removeLayer(name)
        else:
            # Get URL, attribution & vis params
            params = getImageTile(image, visParams, show, opacity)

        layer = ipyleaflet.TileLayer(url=params['url'],
                                     attribution=params['attribution'],
                                     name=name)

        EELayer = {
            'type': 'Image',
            'object': image,
            'visParams': params['visParams'],
            'layer': layer
        }

        # self._add_EELayer(name, EELayer)
        # return name
        return EELayer
Example #10
0
    def click_event(self, target):
        pt_index = target['data']['index']
        current_band = Plot_interface.band_list[Plot_interface.band_index1]
        image_id = Plot_interface.sample_df['id'].values[pt_index]
        selected_image = ee.Image(
            Plot_interface.sample_col.filterMetadata('system:index', 'equals',
                                                     image_id).first())
        tile_url = GetTileLayerUrl(
            selected_image.visualize(min=Plot_interface.stretch_min.value,
                                     max=Plot_interface.stretch_max.value,
                                     bands=[
                                         Plot_interface.b1, Plot_interface.b2,
                                         Plot_interface.b3
                                     ]))

        Plot_interface.m.add_layer(
            ipyleaflet.TileLayer(url=tile_url, name=image_id))
Example #11
0
    def click_event2(self, target):
        pt_index = target['data']['index']
        current_band = Plot_interface.band_list[Plot_interface.band_index2]
        #Find clicked image. .values needed to access the nth element of that list instead of indexing by ID
        image_id = Plot_interface.click_df['id'].values[pt_index]
        selected_image = ee.Image(
            Plot_interface.click_col.filterMetadata('system:index', 'equals',
                                                    image_id).first())
        tile_url = GetTileLayerUrl(
            selected_image.visualize(min=Plot_interface.minv,
                                     max=Plot_interface.maxv,
                                     bands=[
                                         Plot_interface.b1, Plot_interface.b2,
                                         Plot_interface.b3
                                     ]))

        Plot_interface.m.add_layer(
            ipyleaflet.TileLayer(url=tile_url, name=image_id))
Example #12
0
        def addImage(image, name):
            # Check if layer exists
            if name in self.EELayers.keys():
                print("Layer with name {} exists already, please choose" +
                      "another name".format(name))
                return

            params = get_image_tile(image, visParams, show, opacity)

            layer = ipyleaflet.TileLayer(url=params['url'],
                                         attribution=params['attribution'],
                                         name=name)
            self.add_layer(layer)
            self.EELayers[name] = {
                'type': 'Image',
                'object': image,
                'visParams': visParams,
                'layer': layer
            }
            return layer
Example #13
0
    def add_ee_layer(self, raw_img, vis=None, **kwargs):
        """Add a EE layer to the map.

        Parameters
        ----------
        raw_img : ee.image.Image
            Image without visualisation parameters.
        vis : dict
            Visualisation parameters. Default is None.
        **kwargs :
            Extra parameters for ipyleaflet.TileLayer.

        """
        if vis is not None:
            img = raw_img.visualize(**vis)
        else:
            img = raw_img
        self.add_layer(
            ipyleaflet.TileLayer(url=self._get_tileLayer_url(img), **kwargs))
        self.ee_layers.append(raw_img)
Example #14
0
File: map.py Project: whigg/ipygee
 def addBasemap(self, name, url, **kwargs):
     """ Add a basemap with the given URL """
     layer = ipyleaflet.TileLayer(url=url, name=name, base=True, **kwargs)
     self.add_layer(layer)
Example #15
0
def add_to_map(
    arr: xr.DataArray,
    map: ipyleaflet.Map,
    name: Optional[str] = None,
    range: Optional[Range] = None,
    cmap: Optional[Union[str, matplotlib.colors.Colormap]] = None,
    checkerboard: bool = True,
    interpolation: Literal["linear", "nearest"] = "linear",
) -> ipyleaflet.Layer:
    """
    Add the `~xarray.DataArray` to an ipyleaflet :doc:`api_reference/map` as a new layer or replacing an existing one.

    By giving a name, you can change and re-run notebook cells without piling up extraneous layers on
    your map.

    As you pan around the map, the part of the array that's in view is computed on the fly by dask.
    This requires using a :doc:`dask distributed <distributed:index>` cluster.

    Parameters
    ----------
    arr:
        `~xarray.DataArray` to visualize. Must have ``x`` and ``y``, and optionally ``band`` dims,
        and the ``epsg`` coordinate set.

        ``arr`` must have 1-3 bands. Single-band data can be colormapped; multi-band data will be
        displayed as RGB. For 2-band arrays, the first band will be duplicated into the third band's spot,
        then shown as RGB.
    map:
        ipyleaflet :doc:`api_reference/map` to show the array on.
    name: str
        Name of the layer. If there's already a layer with this name on the map, its URL will be updated.
        Otherwise, a new layer is added.

        If None (default), ``arr.name`` is used as the name. If a layer with this name already exists,
        it will be replaced.
    range:
        Min and max values in ``arr`` which will become black (0) and white (255) in the visualization.

        If None (default), it will automatically use the 2nd/98th percentile values of the *entire array*
        (unless it's a boolean array; then we just use 0-1).
        For large arrays, this can be very slow and expensive, and slow down tile rendering a lot, so
        passing an explicit range is usually a good idea.
    cmap:
        Colormap to use for single-band data. Can be a
        :doc:`matplotlib colormap name <gallery/color/colormap_reference>` as a string,
        or a `~matplotlib.colors.Colormap` object for custom colormapping.

        If None (default), the default matplotlib colormap (usually ``viridis``) will automatically
        be used for 1-band data. Setting a colormap for multi-band data is an error.
    checkerboard:
        Whether to show a checkerboard pattern for missing data (default), or leave it fully transparent.

        Note that only NaN is considered a missing value; any custom fill value should be converted
        to NaN before visualizing.
    interpolation:
        Interpolation method to use while reprojecting: ``"linear"`` or ``"nearest"`` (default ``"linear"``).
        Use ``"linear"`` for continuous data, such as imagery, SAR, DEMs, weather data, etc. Use ``"nearest"``
        for discrete/categorical data, such as classification maps.


    Returns
    -------
    ipyleaflet.Layer:
        The new or existing layer for visualizing this array.
    """
    if name is None:
        name = str(arr.name)
    for lyr in map.layers:
        if lyr.name == name:
            break
    else:
        lyr = ipyleaflet.TileLayer(name=name, url="")
        map.add_layer(lyr)

    register(
        arr,
        map=map,
        layer=lyr,
        range=range,
        cmap=cmap,
        checkerboard=checkerboard,
        interpolation=interpolation,
    )
    return lyr