geemap/geemap.py
def add_legend(
        self,
        legend_title="Legend",
        legend_dict=None,
        legend_keys=None,
        legend_colors=None,
        position="bottomright",
        builtin_legend=None,
        layer_name=None,
        **kwargs,
    ):
        """Adds a customized basemap to the map.

        Args:
            legend_title (str, optional): Title of the legend. Defaults to 'Legend'.
            legend_dict (dict, optional): A dictionary containing legend items as keys and color as values. If provided, legend_keys and legend_colors will be ignored. Defaults to None.
            legend_keys (list, optional): A list of legend keys. Defaults to None.
            legend_colors (list, optional): A list of legend colors. Defaults to None.
            position (str, optional): Position of the legend. Defaults to 'bottomright'.
            builtin_legend (str, optional): Name of the builtin legend to add to the map. Defaults to None.
            layer_name (str, optional): Layer name of the legend to be associated with. Defaults to None.

        """
        import pkg_resources
        from IPython.display import display

        pkg_dir = os.path.dirname(
            pkg_resources.resource_filename("geemap", "geemap.py")
        )
        legend_template = os.path.join(pkg_dir, "data/template/legend.html")

        if "min_width" not in kwargs.keys():
            min_width = None
        if "max_width" not in kwargs.keys():
            max_width = None
        else:
            max_width = kwargs["max_width"]
        if "min_height" not in kwargs.keys():
            min_height = None
        else:
            min_height = kwargs["min_height"]
        if "max_height" not in kwargs.keys():
            max_height = None
        else:
            max_height = kwargs["max_height"]
        if "height" not in kwargs.keys():
            height = None
        else:
            height = kwargs["height"]
        if "width" not in kwargs.keys():
            width = None
        else:
            width = kwargs["width"]

        if width is None:
            max_width = "300px"
        if height is None:
            max_height = "400px"

        if not os.path.exists(legend_template):
            print("The legend template does not exist.")
            return

        if legend_keys is not None:
            if not isinstance(legend_keys, list):
                print("The legend keys must be a list.")
                return
        else:
            legend_keys = ["One", "Two", "Three", "Four", "etc"]

        if legend_colors is not None:
            if not isinstance(legend_colors, list):
                print("The legend colors must be a list.")
                return
            elif all(isinstance(item, tuple) for item in legend_colors):
                try:
                    legend_colors = [rgb_to_hex(x) for x in legend_colors]
                except Exception as e:
                    print(e)
            elif all(
                (item.startswith("#") and len(item) == 7) for item in legend_colors
            ):
                pass
            elif all((len(item) == 6) for item in legend_colors):
                pass
            else:
                print("The legend colors must be a list of tuples.")
                return
        else:
            legend_colors = [
                "#8DD3C7",
                "#FFFFB3",
                "#BEBADA",
                "#FB8072",
                "#80B1D3",
            ]

        if len(legend_keys) != len(legend_colors):
            print("The legend keys and values must be the same length.")
            return

        allowed_builtin_legends = builtin_legends.keys()
        if builtin_legend is not None:
            if builtin_legend not in allowed_builtin_legends:
                print(
                    "The builtin legend must be one of the following: {}".format(
                        ", ".join(allowed_builtin_legends)
                    )
                )
                return
            else:
                legend_dict = builtin_legends[builtin_legend]
                legend_keys = list(legend_dict.keys())
                legend_colors = list(legend_dict.values())

        if legend_dict is not None:
            if not isinstance(legend_dict, dict):
                print("The legend dict must be a dictionary.")
                return
            else:
                legend_keys = list(legend_dict.keys())
                legend_colors = list(legend_dict.values())
                if all(isinstance(item, tuple) for item in legend_colors):
                    try:
                        legend_colors = [rgb_to_hex(x) for x in legend_colors]
                    except Exception as e:
                        print(e)

        allowed_positions = [
            "topleft",
            "topright",
            "bottomleft",
            "bottomright",
        ]
        if position not in allowed_positions:
            print(
                "The position must be one of the following: {}".format(
                    ", ".join(allowed_positions)
                )
            )
            return

        header = []
        content = []
        footer = []

        with open(legend_template) as f:
            lines = f.readlines()
            lines[3] = lines[3].replace("Legend", legend_title)
            header = lines[:6]
            footer = lines[11:]

        for index, key in enumerate(legend_keys):
            color = legend_colors[index]
            if not color.startswith("#"):
                color = "#" + color
            item = "      <li><span style='background:{};'></span>{}</li>\n".format(
                color, key
            )
            content.append(item)

        legend_html = header + content + footer
        legend_text = "".join(legend_html)

        try:

            legend_output_widget = widgets.Output(
                layout={
                    # "border": "1px solid black",
                    "max_width": max_width,
                    "min_width": min_width,
                    "max_height": max_height,
                    "min_height": min_height,
                    "height": height,
                    "width": width,
                    "overflow": "scroll",
                }
            )
            legend_control = ipyleaflet.WidgetControl(
                widget=legend_output_widget, position=position
            )
            legend_widget = widgets.HTML(value=legend_text)
            with legend_output_widget:
                display(legend_widget)

            self.legend_widget = legend_output_widget
            self.legend = legend_control
            self.add_control(legend_control)

            if not hasattr(self, "legends"):
                setattr(self, "legends", [legend_control])
            else:
                self.legends.append(legend_control)

            if layer_name in self.ee_layer_names:
                self.ee_layer_dict[layer_name]["legend"] = legend_control

        except Exception as e:
            raise Exception(e)
Adds a customized basemap to the map.

        Args:
            legend_title (str, optional): Title of the legend. Defaults to 'Legend'.
            legend_dict (dict, optional): A dictionary containing legend items as keys and color as values. If provided, legend_keys and legend_colors will be ignored. Defaults to None.
            legend_keys (list, optional): A list of legend keys. Defaults to None.
            legend_colors (list, optional): A list of legend colors. Defaults to None.
            position (str, optional): Position of the legend. Defaults to 'bottomright'.
            builtin_legend (str, optional): Name of the builtin legend to add to the map. Defaults to None.
            layer_name (str, optional): Layer name of the legend to be associated with. Defaults to None.

        
Adds a customized basemap to the map.
Adds a customized basemap to the map .
def add_legend(
        self,
        legend_title="Legend",
        legend_dict=None,
        legend_keys=None,
        legend_colors=None,
        position="bottomright",
        builtin_legend=None,
        layer_name=None,
        **kwargs,
    ):
        import pkg_resources
        from IPython.display import display
        pkg_dir = os.path.dirname(
            pkg_resources.resource_filename("geemap", "geemap.py")
        )
        legend_template = os.path.join(pkg_dir, "data/template/legend.html")
        if "min_width" not in kwargs.keys():
            min_width = None
        if "max_width" not in kwargs.keys():
            max_width = None
        else:
            max_width = kwargs["max_width"]
        if "min_height" not in kwargs.keys():
            min_height = None
        else:
            min_height = kwargs["min_height"]
        if "max_height" not in kwargs.keys():
            max_height = None
        else:
            max_height = kwargs["max_height"]
        if "height" not in kwargs.keys():
            height = None
        else:
            height = kwargs["height"]
        if "width" not in kwargs.keys():
            width = None
        else:
            width = kwargs["width"]
        if width is None:
            max_width = "300px"
        if height is None:
            max_height = "400px"
        if not os.path.exists(legend_template):
            print("The legend template does not exist.")
            return
        if legend_keys is not None:
            if not isinstance(legend_keys, list):
                print("The legend keys must be a list.")
                return
        else:
            legend_keys = ["One", "Two", "Three", "Four", "etc"]
        if legend_colors is not None:
            if not isinstance(legend_colors, list):
                print("The legend colors must be a list.")
                return
            elif all(isinstance(item, tuple) for item in legend_colors):
                try:
                    legend_colors = [rgb_to_hex(x) for x in legend_colors]
                except Exception as e:
                    print(e)
            elif all(
                (item.startswith("#") and len(item) == 7) for item in legend_colors
            ):
                pass
            elif all((len(item) == 6) for item in legend_colors):
                pass
            else:
                print("The legend colors must be a list of tuples.")
                return
        else:
            legend_colors = [
                "#8DD3C7",
                "#FFFFB3",
                "#BEBADA",
                "#FB8072",
                "#80B1D3",
            ]
        if len(legend_keys) != len(legend_colors):
            print("The legend keys and values must be the same length.")
            return
        allowed_builtin_legends = builtin_legends.keys()
        if builtin_legend is not None:
            if builtin_legend not in allowed_builtin_legends:
                print(
                    "The builtin legend must be one of the following: {}".format(
                        ", ".join(allowed_builtin_legends)
                    )
                )
                return
            else:
                legend_dict = builtin_legends[builtin_legend]
                legend_keys = list(legend_dict.keys())
                legend_colors = list(legend_dict.values())
        if legend_dict is not None:
            if not isinstance(legend_dict, dict):
                print("The legend dict must be a dictionary.")
                return
            else:
                legend_keys = list(legend_dict.keys())
                legend_colors = list(legend_dict.values())
                if all(isinstance(item, tuple) for item in legend_colors):
                    try:
                        legend_colors = [rgb_to_hex(x) for x in legend_colors]
                    except Exception as e:
                        print(e)
        allowed_positions = [
            "topleft",
            "topright",
            "bottomleft",
            "bottomright",
        ]
        if position not in allowed_positions:
            print(
                "The position must be one of the following: {}".format(
                    ", ".join(allowed_positions)
                )
            )
            return
        header = []
        content = []
        footer = []
        with open(legend_template) as f:
            lines = f.readlines()
            lines[3] = lines[3].replace("Legend", legend_title)
            header = lines[:6]
            footer = lines[11:]
        for index, key in enumerate(legend_keys):
            color = legend_colors[index]
            if not color.startswith("#"):
                color = "#" + color
            item = "      <li><span style='background:{};'></span>{}</li>\n".format(
                color, key
            )
            content.append(item)
        legend_html = header + content + footer
        legend_text = "".join(legend_html)
        try:
            legend_output_widget = widgets.Output(
                layout={
                    "max_width": max_width,
                    "min_width": min_width,
                    "max_height": max_height,
                    "min_height": min_height,
                    "height": height,
                    "width": width,
                    "overflow": "scroll",
                }
            )
            legend_control = ipyleaflet.WidgetControl(
                widget=legend_output_widget, position=position
            )
            legend_widget = widgets.HTML(value=legend_text)
            with legend_output_widget:
                display(legend_widget)
            self.legend_widget = legend_output_widget
            self.legend = legend_control
            self.add_control(legend_control)
            if not hasattr(self, "legends"):
                setattr(self, "legends", [legend_control])
            else:
                self.legends.append(legend_control)
            if layer_name in self.ee_layer_names:
                self.ee_layer_dict[layer_name]["legend"] = legend_control
        except Exception as e:
            raise Exception(e)
def add_legend ( self , legend_title = "Legend" , legend_dict = None , legend_keys = None , legend_colors = None , position = "bottomright" , builtin_legend = None , layer_name = None , ** kwargs , ) : import pkg_resources from IPython . display import display pkg_dir = os . path . dirname ( pkg_resources . resource_filename ( "geemap" , "geemap.py" ) ) legend_template = os . path . join ( pkg_dir , "data/template/legend.html" ) if "min_width" not in kwargs . keys ( ) : min_width = None if "max_width" not in kwargs . keys ( ) : max_width = None else : max_width = kwargs [ "max_width" ] if "min_height" not in kwargs . keys ( ) : min_height = None else : min_height = kwargs [ "min_height" ] if "max_height" not in kwargs . keys ( ) : max_height = None else : max_height = kwargs [ "max_height" ] if "height" not in kwargs . keys ( ) : height = None else : height = kwargs [ "height" ] if "width" not in kwargs . keys ( ) : width = None else : width = kwargs [ "width" ] if width is None : max_width = "300px" if height is None : max_height = "400px" if not os . path . exists ( legend_template ) : print ( "The legend template does not exist." ) return if legend_keys is not None : if not isinstance ( legend_keys , list ) : print ( "The legend keys must be a list." ) return else : legend_keys = [ "One" , "Two" , "Three" , "Four" , "etc" ] if legend_colors is not None : if not isinstance ( legend_colors , list ) : print ( "The legend colors must be a list." ) return elif all ( isinstance ( item , tuple ) for item in legend_colors ) : try : legend_colors = [ rgb_to_hex ( x ) for x in legend_colors ] except Exception as e : print ( e ) elif all ( ( item . startswith ( "#" ) and len ( item ) == 7 ) for item in legend_colors ) : pass elif all ( ( len ( item ) == 6 ) for item in legend_colors ) : pass else : print ( "The legend colors must be a list of tuples." ) return else : legend_colors = [ "#8DD3C7" , "#FFFFB3" , "#BEBADA" , "#FB8072" , "#80B1D3" , ] if len ( legend_keys ) != len ( legend_colors ) : print ( "The legend keys and values must be the same length." ) return allowed_builtin_legends = builtin_legends . keys ( ) if builtin_legend is not None : if builtin_legend not in allowed_builtin_legends : print ( "The builtin legend must be one of the following: {}" . format ( ", " . join ( allowed_builtin_legends ) ) ) return else : legend_dict = builtin_legends [ builtin_legend ] legend_keys = list ( legend_dict . keys ( ) ) legend_colors = list ( legend_dict . values ( ) ) if legend_dict is not None : if not isinstance ( legend_dict , dict ) : print ( "The legend dict must be a dictionary." ) return else : legend_keys = list ( legend_dict . keys ( ) ) legend_colors = list ( legend_dict . values ( ) ) if all ( isinstance ( item , tuple ) for item in legend_colors ) : try : legend_colors = [ rgb_to_hex ( x ) for x in legend_colors ] except Exception as e : print ( e ) allowed_positions = [ "topleft" , "topright" , "bottomleft" , "bottomright" , ] if position not in allowed_positions : print ( "The position must be one of the following: {}" . format ( ", " . join ( allowed_positions ) ) ) return header = [ ] content = [ ] footer = [ ] with open ( legend_template ) as f : lines = f . readlines ( ) lines [ 3 ] = lines [ 3 ] . replace ( "Legend" , legend_title ) header = lines [ : 6 ] footer = lines [ 11 : ] for index , key in enumerate ( legend_keys ) : color = legend_colors [ index ] if not color . startswith ( "#" ) : color = "#" + color item = "      <li><span style='background:{};'></span>{}</li>\n" . format ( color , key ) content . append ( item ) legend_html = header + content + footer legend_text = "" . join ( legend_html ) try : legend_output_widget = widgets . Output ( layout = { "max_width" : max_width , "min_width" : min_width , "max_height" : max_height , "min_height" : min_height , "height" : height , "width" : width , "overflow" : "scroll" , } ) legend_control = ipyleaflet . WidgetControl ( widget = legend_output_widget , position = position ) legend_widget = widgets . HTML ( value = legend_text ) with legend_output_widget : display ( legend_widget ) self . legend_widget = legend_output_widget self . legend = legend_control self . add_control ( legend_control ) if not hasattr ( self , "legends" ) : setattr ( self , "legends" , [ legend_control ] ) else : self . legends . append ( legend_control ) if layer_name in self . ee_layer_names : self . ee_layer_dict [ layer_name ] [ "legend" ] = legend_control except Exception as e : raise Exception ( e )
Adds a customized basemap to the map.
Adds a customized basemap to the map .
"""Adds a customized basemap to the map.

        Args:
            legend_title (str, optional): Title of the legend. Defaults to 'Legend'.
            legend_dict (dict, optional): A dictionary containing legend items as keys and color as values. If provided, legend_keys and legend_colors will be ignored. Defaults to None.
            legend_keys (list, optional): A list of legend keys. Defaults to None.
            legend_colors (list, optional): A list of legend colors. Defaults to None.
            position (str, optional): Position of the legend. Defaults to 'bottomright'.
            builtin_legend (str, optional): Name of the builtin legend to add to the map. Defaults to None.
            layer_name (str, optional): Layer name of the legend to be associated with. Defaults to None.

        """ # "border": "1px solid black",

self
legend_title
Title of the legend. Defaults to 'Legend'.
Title of the legend . Defaults to ' Legend ' .
'Legend'
legend_dict
A dictionary containing legend items as keys and color as values. If provided, legend_keys and legend_colors will be ignored. Defaults to None.
A dictionary containing legend items as keys and color as values . If provided legend_keys and legend_colors will be ignored . Defaults to None .
None
legend_keys
A list of legend keys. Defaults to None.
A list of legend keys . Defaults to None .
None
legend_colors
A list of legend colors. Defaults to None.
A list of legend colors . Defaults to None .
None
position
Position of the legend. Defaults to 'bottomright'.
Position of the legend . Defaults to ' bottomright ' .
'bottomright'
builtin_legend
Name of the builtin legend to add to the map. Defaults to None.
Name of the builtin legend to add to the map . Defaults to None .
None
layer_name
Layer name of the legend to be associated with. Defaults to None.
Layer name of the legend to be associated with . Defaults to None .
None