index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
12,694
ipyleaflet.leaflet
clear_rectangles
Clear all rectangles.
def clear_rectangles(self): """Clear all rectangles.""" self.send({"msg": "clear_rectangles"})
(self)
12,705
ipyleaflet.leaflet
on_draw
Add a draw event listener. Parameters ---------- callback : callable Callback function that will be called on draw event. remove: boolean Whether to remove this callback or not. Defaults to False.
def on_draw(self, callback, remove=False): """Add a draw event listener. Parameters ---------- callback : callable Callback function that will be called on draw event. remove: boolean Whether to remove this callback or not. Defaults to False. """ self._draw_callbacks.register_callback(callback, remove=remove)
(self, callback, remove=False)
12,723
ipyleaflet.leaflet
DrawControlBase
null
class DrawControlBase(Control): # Leave empty to disable these circle = Dict().tag(sync=True) rectangle = Dict().tag(sync=True) marker = Dict().tag(sync=True) # Edit tools edit = Bool(True).tag(sync=True) remove = Bool(True).tag(sync=True) # Layer data data = List().tag(sync=True) _draw_callbacks = Instance(CallbackDispatcher, ()) def __init__(self, **kwargs): super(DrawControlBase, self).__init__(**kwargs) def on_draw(self, callback, remove=False): """Add a draw event listener. Parameters ---------- callback : callable Callback function that will be called on draw event. remove: boolean Whether to remove this callback or not. Defaults to False. """ self._draw_callbacks.register_callback(callback, remove=remove) def clear(self): """Clear all drawings.""" self.send({"msg": "clear"}) def clear_polylines(self): """Clear all polylines.""" self.send({"msg": "clear_polylines"}) def clear_polygons(self): """Clear all polygons.""" self.send({"msg": "clear_polygons"}) def clear_circles(self): """Clear all circles.""" self.send({"msg": "clear_circles"}) def clear_circle_markers(self): """Clear all circle markers.""" self.send({"msg": "clear_circle_markers"}) def clear_rectangles(self): """Clear all rectangles.""" self.send({"msg": "clear_rectangles"}) def clear_markers(self): """Clear all markers.""" self.send({"msg": "clear_markers"})
(**kwargs)
12,728
ipyleaflet.leaflet
__init__
null
def __init__(self, **kwargs): super(DrawControlBase, self).__init__(**kwargs)
(self, **kwargs)
12,788
ipyleaflet.leaflet
DrawControlCompatibility
DrawControl class. Python side compatibility layer for old DrawControls, using the new Geoman front-end but old Python API.
class DrawControlCompatibility(DrawControlBase): """DrawControl class. Python side compatibility layer for old DrawControls, using the new Geoman front-end but old Python API. """ _view_name = Unicode("LeafletGeomanDrawControlView").tag(sync=True) _model_name = Unicode("LeafletGeomanDrawControlModel").tag(sync=True) # Different drawing modes # See https://www.geoman.io/docs/modes/draw-mode polyline = Dict({ 'shapeOptions': {} }).tag(sync=True) polygon = Dict({ 'shapeOptions': {} }).tag(sync=True) circlemarker = Dict({ 'shapeOptions': {} }).tag(sync=True) last_draw = Dict({ 'type': 'Feature', 'geometry': None }) last_action = Unicode() def __init__(self, **kwargs): super(DrawControlCompatibility, self).__init__(**kwargs) self.on_msg(self._handle_leaflet_event) def _handle_leaflet_event(self, _, content, buffers): if content.get('event', '').startswith('pm:'): action = content.get('event').split(':')[1] geo_json = content.get('geo_json') # We remove vertexadded events, since they were not available through leaflet-draw if action == "vertexadded": return # Some actions return only new feature, while others return all features # in the layer if not isinstance(geo_json, dict): geo_json = geo_json[-1] self.last_draw = geo_json self.last_action = action self._draw_callbacks(self, action=action, geo_json=self.last_draw)
(**kwargs)
12,793
ipyleaflet.leaflet
__init__
null
def __init__(self, **kwargs): super(DrawControlCompatibility, self).__init__(**kwargs) self.on_msg(self._handle_leaflet_event)
(self, **kwargs)
12,804
ipyleaflet.leaflet
_handle_leaflet_event
null
def _handle_leaflet_event(self, _, content, buffers): if content.get('event', '').startswith('pm:'): action = content.get('event').split(':')[1] geo_json = content.get('geo_json') # We remove vertexadded events, since they were not available through leaflet-draw if action == "vertexadded": return # Some actions return only new feature, while others return all features # in the layer if not isinstance(geo_json, dict): geo_json = geo_json[-1] self.last_draw = geo_json self.last_action = action self._draw_callbacks(self, action=action, geo_json=self.last_draw)
(self, _, content, buffers)
12,854
traitlets.traitlets
Enum
An enum whose value must be in a given sequence.
class Enum(TraitType[G, G]): """An enum whose value must be in a given sequence.""" if t.TYPE_CHECKING: @t.overload def __init__( self: Enum[G], values: t.Sequence[G], default_value: G | Sentinel = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., config: t.Any = ..., **kwargs: t.Any, ) -> None: ... @t.overload def __init__( self: Enum[G | None], values: t.Sequence[G] | None, default_value: G | Sentinel | None = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., config: t.Any = ..., **kwargs: t.Any, ) -> None: ... def __init__( self: Enum[G], values: t.Sequence[G] | None, default_value: G | Sentinel | None = Undefined, allow_none: bool = False, read_only: bool | None = None, help: str | None = None, config: t.Any = None, **kwargs: t.Any, ) -> None: self.values = values if allow_none is True and default_value is Undefined: default_value = None kwargs["allow_none"] = allow_none kwargs["read_only"] = read_only kwargs["help"] = help kwargs["config"] = config super().__init__(default_value, **kwargs) def validate(self, obj: t.Any, value: t.Any) -> G: if self.values and value in self.values: return t.cast(G, value) self.error(obj, value) def _choices_str(self, as_rst: bool = False) -> str: """Returns a description of the trait choices (not none).""" choices = self.values or [] if as_rst: choice_str = "|".join("``%r``" % x for x in choices) else: choice_str = repr(list(choices)) return choice_str def _info(self, as_rst: bool = False) -> str: """Returns a description of the trait.""" none = " or %s" % ("`None`" if as_rst else "None") if self.allow_none else "" return f"any of {self._choices_str(as_rst)}{none}" def info(self) -> str: return self._info(as_rst=False) def info_rst(self) -> str: return self._info(as_rst=True) def from_string(self, s: str) -> G: try: return self.validate(None, s) except TraitError: return t.cast(G, _safe_literal_eval(s)) def subclass_init(self, cls: type[t.Any]) -> None: pass # fully opt out of instance_init def argcompleter(self, **kwargs: t.Any) -> list[str]: """Completion hints for argcomplete""" return [str(v) for v in self.values or []]
(values: 't.Sequence[G] | None', default_value: Any = traitlets.Undefined, allow_none: bool = False, read_only: bool = None, help: 'str | None' = None, config: 't.Any' = None, **kwargs: 't.Any') -> 'None'
12,856
traitlets.traitlets
__init__
null
def __init__( self: Enum[G], values: t.Sequence[G] | None, default_value: G | Sentinel | None = Undefined, allow_none: bool = False, read_only: bool | None = None, help: str | None = None, config: t.Any = None, **kwargs: t.Any, ) -> None: self.values = values if allow_none is True and default_value is Undefined: default_value = None kwargs["allow_none"] = allow_none kwargs["read_only"] = read_only kwargs["help"] = help kwargs["config"] = config super().__init__(default_value, **kwargs)
(self: traitlets.traitlets.Enum[~G], values: Optional[Sequence[~G]], default_value: Union[~G, traitlets.utils.sentinel.Sentinel, NoneType] = traitlets.Undefined, allow_none: bool = False, read_only: Optional[bool] = None, help: Optional[str] = None, config: Optional[Any] = None, **kwargs: Any) -> NoneType
12,859
traitlets.traitlets
_choices_str
Returns a description of the trait choices (not none).
def _choices_str(self, as_rst: bool = False) -> str: """Returns a description of the trait choices (not none).""" choices = self.values or [] if as_rst: choice_str = "|".join("``%r``" % x for x in choices) else: choice_str = repr(list(choices)) return choice_str
(self, as_rst: bool = False) -> str
12,861
traitlets.traitlets
_info
Returns a description of the trait.
def _info(self, as_rst: bool = False) -> str: """Returns a description of the trait.""" none = " or %s" % ("`None`" if as_rst else "None") if self.allow_none else "" return f"any of {self._choices_str(as_rst)}{none}"
(self, as_rst: bool = False) -> str
12,863
traitlets.traitlets
argcompleter
Completion hints for argcomplete
def argcompleter(self, **kwargs: t.Any) -> list[str]: """Completion hints for argcomplete""" return [str(v) for v in self.values or []]
(self, **kwargs: Any) -> list[str]
12,868
traitlets.traitlets
from_string
null
def from_string(self, s: str) -> G: try: return self.validate(None, s) except TraitError: return t.cast(G, _safe_literal_eval(s))
(self, s: str) -> ~G
12,872
traitlets.traitlets
info
null
def info(self) -> str: return self._info(as_rst=False)
(self) -> str
12,873
traitlets.traitlets
info_rst
null
def info_rst(self) -> str: return self._info(as_rst=True)
(self) -> str
12,880
traitlets.traitlets
validate
null
def validate(self, obj: t.Any, value: t.Any) -> G: if self.values and value in self.values: return t.cast(G, value) self.error(obj, value)
(self, obj: Any, value: Any) -> ~G
12,881
ipyleaflet.leaflet
FeatureGroup
FeatureGroup abstract class.
class FeatureGroup(LayerGroup): """FeatureGroup abstract class.""" _view_name = Unicode("LeafletFeatureGroupView").tag(sync=True) _model_name = Unicode("LeafletFeatureGroupModel").tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
12,954
traitlets.traitlets
Float
A float trait.
class Float(TraitType[G, S]): """A float trait.""" default_value = 0.0 info_text = "a float" @t.overload def __init__( self: Float[float, int | float], default_value: float | Sentinel = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., config: t.Any | None = ..., **kwargs: t.Any, ) -> None: ... @t.overload def __init__( self: Float[int | None, int | float | None], default_value: float | Sentinel | None = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., config: t.Any | None = ..., **kwargs: t.Any, ) -> None: ... def __init__( self: Float[int | None, int | float | None], default_value: float | Sentinel | None = Undefined, allow_none: bool = False, read_only: bool | None = False, help: str | None = None, config: t.Any | None = None, **kwargs: t.Any, ) -> None: self.min = kwargs.pop("min", -float("inf")) self.max = kwargs.pop("max", float("inf")) super().__init__( default_value=default_value, allow_none=allow_none, read_only=read_only, help=help, config=config, **kwargs, ) def validate(self, obj: t.Any, value: t.Any) -> G: if isinstance(value, int): value = float(value) if not isinstance(value, float): self.error(obj, value) return t.cast(G, _validate_bounds(self, obj, value)) def from_string(self, s: str) -> G: if self.allow_none and s == "None": return t.cast(G, None) return t.cast(G, float(s)) def subclass_init(self, cls: type[t.Any]) -> None: pass # fully opt out of instance_init
(default_value: Any = traitlets.Undefined, allow_none: bool = False, read_only: bool = False, help: 'str | None' = None, config: 't.Any | None' = None, **kwargs: 't.Any') -> 'None'
12,976
traitlets.traitlets
validate
null
def validate(self, obj: t.Any, value: t.Any) -> G: if isinstance(value, int): value = float(value) if not isinstance(value, float): self.error(obj, value) return t.cast(G, _validate_bounds(self, obj, value))
(self, obj: Any, value: Any) -> ~G
12,977
ipyleaflet.leaflet
FullScreenControl
FullScreenControl class, with Control as parent class. A control which contains a button that will put the Map in full-screen when clicked.
class FullScreenControl(Control): """FullScreenControl class, with Control as parent class. A control which contains a button that will put the Map in full-screen when clicked. """ _view_name = Unicode("LeafletFullScreenControlView").tag(sync=True) _model_name = Unicode("LeafletFullScreenControlModel").tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
13,034
ipyleaflet.leaflet
GeoData
GeoData class with GeoJSON as parent class. Layer created from a GeoPandas dataframe. Attributes ---------- geo_dataframe: geopandas.GeoDataFrame instance, default None The GeoPandas dataframe to use.
class GeoData(GeoJSON): """GeoData class with GeoJSON as parent class. Layer created from a GeoPandas dataframe. Attributes ---------- geo_dataframe: geopandas.GeoDataFrame instance, default None The GeoPandas dataframe to use. """ geo_dataframe = Instance("geopandas.GeoDataFrame") def __init__(self, **kwargs): super(GeoData, self).__init__(**kwargs) self.data = self._get_data() @observe("geo_dataframe", "style", "style_callback") def _update_data(self, change): self.data = self._get_data() def _get_data(self): return json.loads(self.geo_dataframe.to_json()) @property def __geo_interface__(self): """ Return a dict whose structure aligns to the GeoJSON format For more information about the ``__geo_interface__``, see https://gist.github.com/sgillies/2217756 """ return self.geo_dataframe.__geo_interface__
(**kwargs)
13,039
ipyleaflet.leaflet
__init__
null
def __init__(self, **kwargs): super(GeoData, self).__init__(**kwargs) self.data = self._get_data()
(self, **kwargs)
13,048
ipyleaflet.leaflet
_get_data
null
def _get_data(self): return json.loads(self.geo_dataframe.to_json())
(self)
13,110
ipyleaflet.leaflet
GeoJSON
GeoJSON class, with FeatureGroup as parent class. Layer created from a GeoJSON data structure. Attributes ---------- data: dict, default {} The JSON data structure. style: dict, default {} Extra style to apply to the features. hover_style: dict, default {} Style that will be applied to a feature when the mouse is over this feature. point_style: dict, default {} Extra style to apply to the point features. style_callback: callable, default None Function that will be called for each feature, should take the feature as input and return the feature style.
class GeoJSON(FeatureGroup): """GeoJSON class, with FeatureGroup as parent class. Layer created from a GeoJSON data structure. Attributes ---------- data: dict, default {} The JSON data structure. style: dict, default {} Extra style to apply to the features. hover_style: dict, default {} Style that will be applied to a feature when the mouse is over this feature. point_style: dict, default {} Extra style to apply to the point features. style_callback: callable, default None Function that will be called for each feature, should take the feature as input and return the feature style. """ _view_name = Unicode("LeafletGeoJSONView").tag(sync=True) _model_name = Unicode("LeafletGeoJSONModel").tag(sync=True) data = Dict().tag(sync=True) style = Dict().tag(sync=True) visible = Bool(True).tag(sync=True) hover_style = Dict().tag(sync=True) point_style = Dict().tag(sync=True) style_callback = Any() _click_callbacks = Instance(CallbackDispatcher, ()) _hover_callbacks = Instance(CallbackDispatcher, ()) def __init__(self, **kwargs): self.updating = True super(GeoJSON, self).__init__(**kwargs) self.data = self._get_data() self.updating = False @validate("style_callback") def _validate_style_callback(self, proposal): if not callable(proposal.value): raise TraitError( "style_callback should be callable (functor/function/lambda)" ) return proposal.value @observe("data", "style", "style_callback") def _update_data(self, change): if self.updating: return self.updating = True self.data = self._get_data() self.updating = False def _get_data(self): if "type" not in self.data: # We can't apply a style we don't know what the data look like return self.data datatype = self.data["type"] style_callback = None if self.style_callback: style_callback = self.style_callback elif self.style: style_callback = lambda feature: self.style else: # No style to apply return self.data # We need to make a deep copy for ipywidgets to see the change data = copy.deepcopy(self.data) if datatype == "Feature": self._apply_style(data, style_callback) elif datatype == "FeatureCollection": for feature in data["features"]: self._apply_style(feature, style_callback) return data @property def __geo_interface__(self): """ Return a dict whose structure aligns to the GeoJSON format For more information about the ``__geo_interface__``, see https://gist.github.com/sgillies/2217756 """ return self.data def _apply_style(self, feature, style_callback): if "properties" not in feature: feature["properties"] = {} properties = feature["properties"] if "style" in properties: style = properties["style"].copy() style.update(style_callback(feature)) properties["style"] = style else: properties["style"] = style_callback(feature) def _handle_mouse_events(self, _, content, buffers): if content.get("event", "") == "click": self._click_callbacks(**content) if content.get("event", "") == "mouseover": self._hover_callbacks(**content) def on_click(self, callback, remove=False): """Add a feature click event listener. Parameters ---------- callback : callable Callback function that will be called on click event on a feature, this function should take the event and the feature as inputs. remove: boolean Whether to remove this callback or not. Defaults to False. """ self._click_callbacks.register_callback(callback, remove=remove) def on_hover(self, callback, remove=False): """Add a feature hover event listener. Parameters ---------- callback : callable Callback function that will be called when the mouse is over a feature, this function should take the event and the feature as inputs. remove: boolean Whether to remove this callback or not. Defaults to False. """ self._hover_callbacks.register_callback(callback, remove=remove)
(**kwargs)
13,115
ipyleaflet.leaflet
__init__
null
def __init__(self, **kwargs): self.updating = True super(GeoJSON, self).__init__(**kwargs) self.data = self._get_data() self.updating = False
(self, **kwargs)
13,124
ipyleaflet.leaflet
_get_data
null
def _get_data(self): if "type" not in self.data: # We can't apply a style we don't know what the data look like return self.data datatype = self.data["type"] style_callback = None if self.style_callback: style_callback = self.style_callback elif self.style: style_callback = lambda feature: self.style else: # No style to apply return self.data # We need to make a deep copy for ipywidgets to see the change data = copy.deepcopy(self.data) if datatype == "Feature": self._apply_style(data, style_callback) elif datatype == "FeatureCollection": for feature in data["features"]: self._apply_style(feature, style_callback) return data
(self)
13,186
ipyleaflet.leaflet
GeomanDrawControl
GeomanDrawControl class. Alternative drawing tools for drawing on the map provided by Leaflet-Geoman.
class GeomanDrawControl(DrawControlBase): """GeomanDrawControl class. Alternative drawing tools for drawing on the map provided by Leaflet-Geoman. """ _view_name = Unicode("LeafletGeomanDrawControlView").tag(sync=True) _model_name = Unicode("LeafletGeomanDrawControlModel").tag(sync=True) # Current mode & shape # valid values are: 'draw', 'edit', 'drag', 'remove', 'cut', 'rotate' # for drawing, the tool can be added after ':' e.g. 'draw:marker' current_mode = Any(allow_none=True, default_value=None).tag(sync=True) # Hides toolbar hide_controls = Bool(False).tag(sync=True) # Different drawing modes # See https://www.geoman.io/docs/modes/draw-mode polyline = Dict({ 'pathOptions': {} }).tag(sync=True) polygon = Dict({ 'pathOptions': {} }).tag(sync=True) circlemarker = Dict({ 'pathOptions': {} }).tag(sync=True) # Disabled by default text = Dict().tag(sync=True) # Tools # See https://www.geoman.io/docs/modes drag = Bool(True).tag(sync=True) cut = Bool(True).tag(sync=True) rotate = Bool(True).tag(sync=True) def __init__(self, **kwargs): super(GeomanDrawControl, self).__init__(**kwargs) self.on_msg(self._handle_leaflet_event) def _handle_leaflet_event(self, _, content, buffers): if content.get('event', '').startswith('pm:'): action = content.get('event').split(':')[1] geo_json = content.get('geo_json') if action == "vertexadded": self._draw_callbacks(self, action=action, geo_json=geo_json) return # Some actions return only new feature, while others return all features # in the layer if not isinstance(geo_json, list): geo_json = [geo_json] self._draw_callbacks(self, action=action, geo_json=geo_json) def on_draw(self, callback, remove=False): """Add a draw event listener. Parameters ---------- callback : callable Callback function that will be called on draw event. remove: boolean Whether to remove this callback or not. Defaults to False. """ self._draw_callbacks.register_callback(callback, remove=remove) def clear_text(self): """Clear all text.""" self.send({'msg': 'clear_text'})
(**kwargs)
13,191
ipyleaflet.leaflet
__init__
null
def __init__(self, **kwargs): super(GeomanDrawControl, self).__init__(**kwargs) self.on_msg(self._handle_leaflet_event)
(self, **kwargs)
13,202
ipyleaflet.leaflet
_handle_leaflet_event
null
def _handle_leaflet_event(self, _, content, buffers): if content.get('event', '').startswith('pm:'): action = content.get('event').split(':')[1] geo_json = content.get('geo_json') if action == "vertexadded": self._draw_callbacks(self, action=action, geo_json=geo_json) return # Some actions return only new feature, while others return all features # in the layer if not isinstance(geo_json, list): geo_json = [geo_json] self._draw_callbacks(self, action=action, geo_json=geo_json)
(self, _, content, buffers)
13,224
ipyleaflet.leaflet
clear_text
Clear all text.
def clear_text(self): """Clear all text.""" self.send({'msg': 'clear_text'})
(self)
13,253
ipyleaflet.leaflet
Heatmap
Heatmap class, with RasterLayer as parent class. Heatmap layer. Attributes ---------- locations: list, default [] List of data points locations for generating the heatmap. radius: float, default 25. Radius of the data points. blur: float, default 15. Blurring intensity. gradient: dict, default {0.4: 'blue', 0.6: 'cyan', 0.7: 'lime', 0.8: 'yellow', 1.0: 'red'} Colors used for the color-mapping from low to high heatmap intensity.
class Heatmap(RasterLayer): """Heatmap class, with RasterLayer as parent class. Heatmap layer. Attributes ---------- locations: list, default [] List of data points locations for generating the heatmap. radius: float, default 25. Radius of the data points. blur: float, default 15. Blurring intensity. gradient: dict, default {0.4: 'blue', 0.6: 'cyan', 0.7: 'lime', 0.8: 'yellow', 1.0: 'red'} Colors used for the color-mapping from low to high heatmap intensity. """ _view_name = Unicode("LeafletHeatmapView").tag(sync=True) _model_name = Unicode("LeafletHeatmapModel").tag(sync=True) locations = List().tag(sync=True) # Options min_opacity = Float(0.05).tag(sync=True, o=True) max_zoom = Int(18).tag(sync=True, o=True) max = Float(1.0).tag(sync=True, o=True) radius = Float(25.0).tag(sync=True, o=True) blur = Float(15.0).tag(sync=True, o=True) gradient = Dict( {0.4: "blue", 0.6: "cyan", 0.7: "lime", 0.8: "yellow", 1.0: "red"} ).tag(sync=True, o=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
13,318
ipyleaflet.leaflet
Icon
Icon class. Custom icon used for markers. Attributes ---------- icon_url : string, default "" The url to the image used for the icon. shadow_url: string, default None The url to the image used for the icon shadow. icon_size: tuple, default None The size of the icon, in pixels. shadow_size: tuple, default None The size of the icon shadow, in pixels. icon_anchor: tuple, default None The coordinates of the "tip" of the icon (relative to its top left corner). The icon will be aligned so that this point is at the marker's geographical location. Centered by default if icon_size is specified. shadow_anchor: tuple, default None The coordinates of the "tip" of the shadow (relative to its top left corner). The same as icon_anchor if None. popup_anchor: tuple, default None The coordinates of the point from which popups will "open", relative to the icon anchor.
class Icon(UILayer): """Icon class. Custom icon used for markers. Attributes ---------- icon_url : string, default "" The url to the image used for the icon. shadow_url: string, default None The url to the image used for the icon shadow. icon_size: tuple, default None The size of the icon, in pixels. shadow_size: tuple, default None The size of the icon shadow, in pixels. icon_anchor: tuple, default None The coordinates of the "tip" of the icon (relative to its top left corner). The icon will be aligned so that this point is at the marker's geographical location. Centered by default if icon_size is specified. shadow_anchor: tuple, default None The coordinates of the "tip" of the shadow (relative to its top left corner). The same as icon_anchor if None. popup_anchor: tuple, default None The coordinates of the point from which popups will "open", relative to the icon anchor. """ _view_name = Unicode("LeafletIconView").tag(sync=True) _model_name = Unicode("LeafletIconModel").tag(sync=True) icon_url = Unicode("").tag(sync=True, o=True) shadow_url = Unicode(None, allow_none=True).tag(sync=True, o=True) icon_size = List(default_value=None, allow_none=True).tag(sync=True, o=True) shadow_size = List(default_value=None, allow_none=True).tag(sync=True, o=True) icon_anchor = List(default_value=None, allow_none=True).tag(sync=True, o=True) shadow_anchor = List(default_value=None, allow_none=True).tag(sync=True, o=True) popup_anchor = List([0, 0], allow_none=True).tag(sync=True, o=True) @validate( "icon_size", "shadow_size", "icon_anchor", "shadow_anchor", "popup_anchor" ) def _validate_attr(self, proposal): value = proposal["value"] # Workaround Traitlets which does not respect the None default value if value is None or len(value) == 0: return None if len(value) != 2: raise TraitError( "The value should be of size 2, but {} was given".format(value) ) return value
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
13,383
ipyleaflet.leaflet
ImageOverlay
ImageOverlay class. Image layer from a local or remote image file. Attributes ---------- url: string, default "" Url to the local or remote image file. bounds: list, default [0., 0] SW and NE corners of the image. attribution: string, default "" Image attribution.
class ImageOverlay(RasterLayer): """ImageOverlay class. Image layer from a local or remote image file. Attributes ---------- url: string, default "" Url to the local or remote image file. bounds: list, default [0., 0] SW and NE corners of the image. attribution: string, default "" Image attribution. """ _view_name = Unicode("LeafletImageOverlayView").tag(sync=True) _model_name = Unicode("LeafletImageOverlayModel").tag(sync=True) url = Unicode().tag(sync=True) bounds = List([def_loc, def_loc], help="SW and NE corners of the image").tag( sync=True ) # Options attribution = Unicode().tag(sync=True, o=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
13,448
ipyleaflet.leaflet
ImageService
ImageService class Image Service layer for raster data served through a web service Attributes ---------- url: string, default "" URL to the image service f: string, default "image" response format (use ``"image"`` to stream as bytes) format: string, default "jpgpng" format of exported image - ``"jpgpng"`` - ``"png"`` - ``"png8"`` - ``"png24"`` - ``"jpg"`` - ``"bmp"`` - ``"gif"`` - ``"tiff"`` - ``"png32"`` - ``"bip"`` - ``"bsq"`` - ``"lerc"`` pixel_type: string, default "UNKNOWN" data type of the raster image - ``"C128"`` - ``"C64"`` - ``"F32"`` - ``"F64"`` - ``"S16"`` - ``"S32"`` - ``"S8"`` - ``"U1"`` - ``"U16"`` - ``"U2"`` - ``"U32"`` - ``"U4"`` - ``"U8"`` - ``"UNKNOWN"`` no_data: List[int], default [] pixel values representing no data no_data_interpretation: string, default "" how to interpret no data values - ``"esriNoDataMatchAny"`` - ``"esriNoDataMatchAll"`` interpolation: string, default "" resampling process for interpolating the pixel values - ``"RSP_BilinearInterpolation"`` - ``"RSP_CubicConvolution"`` - ``"RSP_Majority"`` - ``"RSP_NearestNeighbor"`` compression_quality: int, default 100 lossy quality for image compression band_ids: List[int], default [] order of bands to export for multiple band images time: List[string], default [] time range for image rendering_rule: dict, default {} rules for rendering mosaic_rule: dict, default {} rules for mosaicking endpoint: string, default "Esri" endpoint format for building the export image URL - ``"Esri"`` attribution: string, default "" include image service attribution crs: dict, default ipyleaflet.projections.EPSG3857 projection used for this image service. interactive: bool, default False emit when clicked for registered callback update_interval: int, default 200 minimum time interval to query for updates when panning (ms)
class ImageService(Layer): """ImageService class Image Service layer for raster data served through a web service Attributes ---------- url: string, default "" URL to the image service f: string, default "image" response format (use ``"image"`` to stream as bytes) format: string, default "jpgpng" format of exported image - ``"jpgpng"`` - ``"png"`` - ``"png8"`` - ``"png24"`` - ``"jpg"`` - ``"bmp"`` - ``"gif"`` - ``"tiff"`` - ``"png32"`` - ``"bip"`` - ``"bsq"`` - ``"lerc"`` pixel_type: string, default "UNKNOWN" data type of the raster image - ``"C128"`` - ``"C64"`` - ``"F32"`` - ``"F64"`` - ``"S16"`` - ``"S32"`` - ``"S8"`` - ``"U1"`` - ``"U16"`` - ``"U2"`` - ``"U32"`` - ``"U4"`` - ``"U8"`` - ``"UNKNOWN"`` no_data: List[int], default [] pixel values representing no data no_data_interpretation: string, default "" how to interpret no data values - ``"esriNoDataMatchAny"`` - ``"esriNoDataMatchAll"`` interpolation: string, default "" resampling process for interpolating the pixel values - ``"RSP_BilinearInterpolation"`` - ``"RSP_CubicConvolution"`` - ``"RSP_Majority"`` - ``"RSP_NearestNeighbor"`` compression_quality: int, default 100 lossy quality for image compression band_ids: List[int], default [] order of bands to export for multiple band images time: List[string], default [] time range for image rendering_rule: dict, default {} rules for rendering mosaic_rule: dict, default {} rules for mosaicking endpoint: string, default "Esri" endpoint format for building the export image URL - ``"Esri"`` attribution: string, default "" include image service attribution crs: dict, default ipyleaflet.projections.EPSG3857 projection used for this image service. interactive: bool, default False emit when clicked for registered callback update_interval: int, default 200 minimum time interval to query for updates when panning (ms) """ _view_name = Unicode("LeafletImageServiceView").tag(sync=True) _model_name = Unicode("LeafletImageServiceModel").tag(sync=True) _formats = [ "jpgpng", "png", "png8", "png24", "jpg", "bmp", "gif", "tiff", "png32", "bip", "bsq", "lerc", ] _pixel_types = [ "C128", "C64", "F32", "F64", "S16", "S32", "S8", "U1", "U16", "U2", "U32", "U4", "U8", "UNKNOWN", ] _no_data_interpretations = ["esriNoDataMatchAny", "esriNoDataMatchAll"] _interpolations = [ "RSP_BilinearInterpolation", "RSP_CubicConvolution", "RSP_Majority", "RSP_NearestNeighbor", ] url = Unicode().tag(sync=True) f = Unicode("image").tag(sync=True, o=True) format = Enum(values=_formats, default_value="jpgpng").tag(sync=True, o=True) pixel_type = Enum(values=_pixel_types, default_value="UNKNOWN").tag( sync=True, o=True ) no_data = List(allow_none=True).tag(sync=True, o=True) no_data_interpretation = Enum(values=_no_data_interpretations, allow_none=True).tag( sync=True, o=True ) interpolation = Enum(values=_interpolations, allow_none=True).tag(sync=True, o=True) compression_quality = Unicode().tag(sync=True, o=True) band_ids = List(allow_none=True).tag(sync=True, o=True) time = List(allow_none=True).tag(sync=True, o=True) rendering_rule = Dict({}).tag(sync=True, o=True) mosaic_rule = Dict({}).tag(sync=True, o=True) endpoint = Unicode("Esri").tag(sync=True, o=True) attribution = Unicode("").tag(sync=True, o=True) crs = Dict(default_value=projections.EPSG3857).tag(sync=True) interactive = Bool(False).tag(sync=True, o=True) update_interval = Int(200).tag(sync=True, o=True) _click_callbacks = Instance(CallbackDispatcher, ()) def __init__(self, **kwargs): super(ImageService, self).__init__(**kwargs) self.on_msg(self._handle_mouse_events) def _handle_mouse_events(self, _, content, buffers): event_type = content.get("type", "") if event_type == "click": self._click_callbacks(**content)
(**kwargs)
13,453
ipyleaflet.leaflet
__init__
null
def __init__(self, **kwargs): super(ImageService, self).__init__(**kwargs) self.on_msg(self._handle_mouse_events)
(self, **kwargs)
13,464
ipyleaflet.leaflet
_handle_mouse_events
null
def _handle_mouse_events(self, _, content, buffers): event_type = content.get("type", "") if event_type == "click": self._click_callbacks(**content)
(self, _, content, buffers)
13,513
traitlets.traitlets
Instance
A trait whose value must be an instance of a specified class. The value can also be an instance of a subclass of the specified class. Subclasses can declare default classes by overriding the klass attribute
class Instance(ClassBasedTraitType[T, T]): """A trait whose value must be an instance of a specified class. The value can also be an instance of a subclass of the specified class. Subclasses can declare default classes by overriding the klass attribute """ klass: str | type[T] | None = None if t.TYPE_CHECKING: @t.overload def __init__( self: Instance[T], klass: type[T] = ..., args: tuple[t.Any, ...] | None = ..., kw: dict[str, t.Any] | None = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., **kwargs: t.Any, ) -> None: ... @t.overload def __init__( self: Instance[T | None], klass: type[T] = ..., args: tuple[t.Any, ...] | None = ..., kw: dict[str, t.Any] | None = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., **kwargs: t.Any, ) -> None: ... @t.overload def __init__( self: Instance[t.Any], klass: str | None = ..., args: tuple[t.Any, ...] | None = ..., kw: dict[str, t.Any] | None = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., **kwargs: t.Any, ) -> None: ... @t.overload def __init__( self: Instance[t.Any | None], klass: str | None = ..., args: tuple[t.Any, ...] | None = ..., kw: dict[str, t.Any] | None = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., **kwargs: t.Any, ) -> None: ... def __init__( self, klass: str | type[T] | None = None, args: tuple[t.Any, ...] | None = None, kw: dict[str, t.Any] | None = None, allow_none: bool = False, read_only: bool | None = None, help: str | None = None, **kwargs: t.Any, ) -> None: """Construct an Instance trait. This trait allows values that are instances of a particular class or its subclasses. Our implementation is quite different from that of enthough.traits as we don't allow instances to be used for klass and we handle the ``args`` and ``kw`` arguments differently. Parameters ---------- klass : class, str The class that forms the basis for the trait. Class names can also be specified as strings, like 'foo.bar.Bar'. args : tuple Positional arguments for generating the default value. kw : dict Keyword arguments for generating the default value. allow_none : bool [ default False ] Indicates whether None is allowed as a value. **kwargs Extra kwargs passed to `ClassBasedTraitType` Notes ----- If both ``args`` and ``kw`` are None, then the default value is None. If ``args`` is a tuple and ``kw`` is a dict, then the default is created as ``klass(*args, **kw)``. If exactly one of ``args`` or ``kw`` is None, the None is replaced by ``()`` or ``{}``, respectively. """ if klass is None: klass = self.klass if (klass is not None) and (inspect.isclass(klass) or isinstance(klass, str)): self.klass = klass else: raise TraitError("The klass attribute must be a class not: %r" % klass) if (kw is not None) and not isinstance(kw, dict): raise TraitError("The 'kw' argument must be a dict or None.") if (args is not None) and not isinstance(args, tuple): raise TraitError("The 'args' argument must be a tuple or None.") self.default_args = args self.default_kwargs = kw super().__init__(allow_none=allow_none, read_only=read_only, help=help, **kwargs) def validate(self, obj: t.Any, value: t.Any) -> T | None: assert self.klass is not None if self.allow_none and value is None: return value if isinstance(value, self.klass): # type:ignore[arg-type] return t.cast(T, value) else: self.error(obj, value) def info(self) -> str: if isinstance(self.klass, str): result = add_article(self.klass) else: result = describe("a", self.klass) if self.allow_none: result += " or None" return result def instance_init(self, obj: t.Any) -> None: # we can't do this in subclass_init because that # might be called before all imports are done. self._resolve_classes() def _resolve_classes(self) -> None: if isinstance(self.klass, str): self.klass = self._resolve_string(self.klass) def make_dynamic_default(self) -> T | None: if (self.default_args is None) and (self.default_kwargs is None): return None assert self.klass is not None return self.klass(*(self.default_args or ()), **(self.default_kwargs or {})) # type:ignore[operator] def default_value_repr(self) -> str: return repr(self.make_dynamic_default()) def from_string(self, s: str) -> T | None: return t.cast(T, _safe_literal_eval(s))
(klass: str | type[~T] | None = None, args: 'tuple[t.Any, ...] | None' = None, kw: 'dict[str, t.Any] | None' = None, allow_none: bool = False, read_only: bool = None, help: 'str | None' = None, **kwargs: 't.Any') -> 'None'
13,515
traitlets.traitlets
__init__
Construct an Instance trait. This trait allows values that are instances of a particular class or its subclasses. Our implementation is quite different from that of enthough.traits as we don't allow instances to be used for klass and we handle the ``args`` and ``kw`` arguments differently. Parameters ---------- klass : class, str The class that forms the basis for the trait. Class names can also be specified as strings, like 'foo.bar.Bar'. args : tuple Positional arguments for generating the default value. kw : dict Keyword arguments for generating the default value. allow_none : bool [ default False ] Indicates whether None is allowed as a value. **kwargs Extra kwargs passed to `ClassBasedTraitType` Notes ----- If both ``args`` and ``kw`` are None, then the default value is None. If ``args`` is a tuple and ``kw`` is a dict, then the default is created as ``klass(*args, **kw)``. If exactly one of ``args`` or ``kw`` is None, the None is replaced by ``()`` or ``{}``, respectively.
def __init__( self, klass: str | type[T] | None = None, args: tuple[t.Any, ...] | None = None, kw: dict[str, t.Any] | None = None, allow_none: bool = False, read_only: bool | None = None, help: str | None = None, **kwargs: t.Any, ) -> None: """Construct an Instance trait. This trait allows values that are instances of a particular class or its subclasses. Our implementation is quite different from that of enthough.traits as we don't allow instances to be used for klass and we handle the ``args`` and ``kw`` arguments differently. Parameters ---------- klass : class, str The class that forms the basis for the trait. Class names can also be specified as strings, like 'foo.bar.Bar'. args : tuple Positional arguments for generating the default value. kw : dict Keyword arguments for generating the default value. allow_none : bool [ default False ] Indicates whether None is allowed as a value. **kwargs Extra kwargs passed to `ClassBasedTraitType` Notes ----- If both ``args`` and ``kw`` are None, then the default value is None. If ``args`` is a tuple and ``kw`` is a dict, then the default is created as ``klass(*args, **kw)``. If exactly one of ``args`` or ``kw`` is None, the None is replaced by ``()`` or ``{}``, respectively. """ if klass is None: klass = self.klass if (klass is not None) and (inspect.isclass(klass) or isinstance(klass, str)): self.klass = klass else: raise TraitError("The klass attribute must be a class not: %r" % klass) if (kw is not None) and not isinstance(kw, dict): raise TraitError("The 'kw' argument must be a dict or None.") if (args is not None) and not isinstance(args, tuple): raise TraitError("The 'args' argument must be a tuple or None.") self.default_args = args self.default_kwargs = kw super().__init__(allow_none=allow_none, read_only=read_only, help=help, **kwargs)
(self, klass: Union[str, type[~T], NoneType] = None, args: Optional[tuple[Any, ...]] = None, kw: Optional[dict[str, Any]] = None, allow_none: bool = False, read_only: Optional[bool] = None, help: Optional[str] = None, **kwargs: Any) -> NoneType
13,526
traitlets.traitlets
from_string
null
def from_string(self, s: str) -> T | None: return t.cast(T, _safe_literal_eval(s))
(self, s: str) -> Optional[~T]
13,536
traitlets.traitlets
subclass_init
null
def subclass_init(self, cls: type[HasTraits]) -> None: # Instead of HasDescriptors.setup_instance calling # every instance_init, we opt in by default. # This gives descriptors a change to opt out for # performance reasons. # Because most traits do not need instance_init, # and it will otherwise be called for every HasTrait instance # being created, this otherwise gives a significant performance # pentalty. Most TypeTraits in traitlets opt out. cls._instance_inits.append(self.instance_init)
(self, cls: type[traitlets.traitlets.HasTraits]) -> NoneType
13,538
traitlets.traitlets
validate
null
def validate(self, obj: t.Any, value: t.Any) -> T | None: assert self.klass is not None if self.allow_none and value is None: return value if isinstance(value, self.klass): # type:ignore[arg-type] return t.cast(T, value) else: self.error(obj, value)
(self, obj: Any, value: Any) -> Optional[~T]
13,539
ipywidgets.widgets.trait_types
InstanceDict
An instance trait which coerces a dict to an instance. This lets the instance be specified as a dict, which is used to initialize the instance. Also, we default to a trivial instance, even if args and kwargs is not specified.
class InstanceDict(traitlets.Instance): """An instance trait which coerces a dict to an instance. This lets the instance be specified as a dict, which is used to initialize the instance. Also, we default to a trivial instance, even if args and kwargs is not specified.""" def validate(self, obj, value): if isinstance(value, dict): return super().validate(obj, self.klass(**value)) else: return super().validate(obj, value) def make_dynamic_default(self): return self.klass(*(self.default_args or ()), **(self.default_kwargs or {}))
(klass: str | type[~T] | None = None, args: 'tuple[t.Any, ...] | None' = None, kw: 'dict[str, t.Any] | None' = None, allow_none: bool = False, read_only: bool = None, help: 'str | None' = None, **kwargs: 't.Any') -> 'None'
13,559
ipywidgets.widgets.trait_types
make_dynamic_default
null
def make_dynamic_default(self): return self.klass(*(self.default_args or ()), **(self.default_kwargs or {}))
(self)
13,564
ipywidgets.widgets.trait_types
validate
null
def validate(self, obj, value): if isinstance(value, dict): return super().validate(obj, self.klass(**value)) else: return super().validate(obj, value)
(self, obj, value)
13,565
traitlets.traitlets
Int
An int trait.
class Int(TraitType[G, S]): """An int trait.""" default_value = 0 info_text = "an int" @t.overload def __init__( self: Int[int, int], default_value: int | Sentinel = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., config: t.Any | None = ..., **kwargs: t.Any, ) -> None: ... @t.overload def __init__( self: Int[int | None, int | None], default_value: int | Sentinel | None = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., config: t.Any | None = ..., **kwargs: t.Any, ) -> None: ... def __init__( self, default_value: t.Any = Undefined, allow_none: bool = False, read_only: bool | None = None, help: str | None = None, config: t.Any | None = None, **kwargs: t.Any, ) -> None: self.min = kwargs.pop("min", None) self.max = kwargs.pop("max", None) super().__init__( default_value=default_value, allow_none=allow_none, read_only=read_only, help=help, config=config, **kwargs, ) def validate(self, obj: t.Any, value: t.Any) -> G: if not isinstance(value, int): self.error(obj, value) return t.cast(G, _validate_bounds(self, obj, value)) def from_string(self, s: str) -> G: if self.allow_none and s == "None": return t.cast(G, None) return t.cast(G, int(s)) def subclass_init(self, cls: type[t.Any]) -> None: pass # fully opt out of instance_init
(default_value: Any = traitlets.Undefined, allow_none: bool = False, read_only: bool = None, help: 'str | None' = None, config: 't.Any | None' = None, **kwargs: 't.Any') -> 'None'
13,567
traitlets.traitlets
__init__
null
def __init__( self, default_value: t.Any = Undefined, allow_none: bool = False, read_only: bool | None = None, help: str | None = None, config: t.Any | None = None, **kwargs: t.Any, ) -> None: self.min = kwargs.pop("min", None) self.max = kwargs.pop("max", None) super().__init__( default_value=default_value, allow_none=allow_none, read_only=read_only, help=help, config=config, **kwargs, )
(self, default_value: Any = traitlets.Undefined, allow_none: bool = False, read_only: Optional[bool] = None, help: Optional[str] = None, config: Optional[Any] = None, **kwargs: Any) -> NoneType
13,576
traitlets.traitlets
from_string
null
def from_string(self, s: str) -> G: if self.allow_none and s == "None": return t.cast(G, None) return t.cast(G, int(s))
(self, s: str) -> ~G
13,587
traitlets.traitlets
validate
null
def validate(self, obj: t.Any, value: t.Any) -> G: if not isinstance(value, int): self.error(obj, value) return t.cast(G, _validate_bounds(self, obj, value))
(self, obj: Any, value: Any) -> ~G
13,588
ipyleaflet.leaflet
InteractMixin
Abstract InteractMixin class.
class InteractMixin(object): """Abstract InteractMixin class.""" def interact(self, **kwargs): c = [] for name, abbrev in kwargs.items(): default = getattr(self, name) widget = interactive.widget_from_abbrev(abbrev, default) if not widget.description: widget.description = name widget.link = link((widget, "value"), (self, name)) c.append(widget) cont = Box(children=c) return cont
()
13,590
ipyleaflet.leaflet
Layer
Abstract Layer class. Base class for all layers in ipyleaflet. Attributes ---------- name : string Custom name for the layer, which will be used by the LayersControl. popup: object Interactive widget that will be shown in a Popup when clicking on the layer. pane: string Name of the pane to use for the layer.
class Layer(Widget, InteractMixin): """Abstract Layer class. Base class for all layers in ipyleaflet. Attributes ---------- name : string Custom name for the layer, which will be used by the LayersControl. popup: object Interactive widget that will be shown in a Popup when clicking on the layer. pane: string Name of the pane to use for the layer. """ _view_name = Unicode("LeafletLayerView").tag(sync=True) _model_name = Unicode("LeafletLayerModel").tag(sync=True) _view_module = Unicode("jupyter-leaflet").tag(sync=True) _model_module = Unicode("jupyter-leaflet").tag(sync=True) _view_module_version = Unicode(EXTENSION_VERSION).tag(sync=True) _model_module_version = Unicode(EXTENSION_VERSION).tag(sync=True) name = Unicode("").tag(sync=True) base = Bool(False).tag(sync=True) bottom = Bool(False).tag(sync=True) popup = Instance(Widget, allow_none=True, default_value=None).tag( sync=True, **widget_serialization ) popup_min_width = Int(50).tag(sync=True) popup_max_width = Int(300).tag(sync=True) popup_max_height = Int(default_value=None, allow_none=True).tag(sync=True) pane = Unicode("").tag(sync=True) options = List(trait=Unicode()).tag(sync=True) subitems = Tuple().tag(trait=Instance(Widget), sync=True, **widget_serialization) @validate("subitems") def _validate_subitems(self, proposal): """Validate subitems list. Makes sure only one instance of any given subitem can exist in the subitem list. """ subitem_ids = [subitem.model_id for subitem in proposal.value] if len(set(subitem_ids)) != len(subitem_ids): raise Exception("duplicate subitem detected, only use each subitem once") return proposal.value def __init__(self, **kwargs): super(Layer, self).__init__(**kwargs) self.on_msg(self._handle_mouse_events) @default("options") def _default_options(self): return [name for name in self.traits(o=True)] # Event handling _click_callbacks = Instance(CallbackDispatcher, ()) _dblclick_callbacks = Instance(CallbackDispatcher, ()) _mousedown_callbacks = Instance(CallbackDispatcher, ()) _mouseup_callbacks = Instance(CallbackDispatcher, ()) _mouseover_callbacks = Instance(CallbackDispatcher, ()) _mouseout_callbacks = Instance(CallbackDispatcher, ()) def _handle_mouse_events(self, _, content, buffers): event_type = content.get("type", "") if event_type == "click": self._click_callbacks(**content) if event_type == "dblclick": self._dblclick_callbacks(**content) if event_type == "mousedown": self._mousedown_callbacks(**content) if event_type == "mouseup": self._mouseup_callbacks(**content) if event_type == "mouseover": self._mouseover_callbacks(**content) if event_type == "mouseout": self._mouseout_callbacks(**content) def on_click(self, callback, remove=False): """Add a click event listener. Parameters ---------- callback : callable Callback function that will be called on click event. remove: boolean Whether to remove this callback or not. Defaults to False. """ self._click_callbacks.register_callback(callback, remove=remove) def on_dblclick(self, callback, remove=False): """Add a double-click event listener. Parameters ---------- callback : callable Callback function that will be called on double-click event. remove: boolean Whether to remove this callback or not. Defaults to False. """ self._dblclick_callbacks.register_callback(callback, remove=remove) def on_mousedown(self, callback, remove=False): """Add a mouse-down event listener. Parameters ---------- callback : callable Callback function that will be called on mouse-down event. remove: boolean Whether to remove this callback or not. Defaults to False. """ self._mousedown_callbacks.register_callback(callback, remove=remove) def on_mouseup(self, callback, remove=False): """Add a mouse-up event listener. Parameters ---------- callback : callable Callback function that will be called on mouse-up event. remove: boolean Whether to remove this callback or not. Defaults to False. """ self._mouseup_callbacks.register_callback(callback, remove=remove) def on_mouseover(self, callback, remove=False): """Add a mouse-over event listener. Parameters ---------- callback : callable Callback function that will be called on mouse-over event. remove: boolean Whether to remove this callback or not. Defaults to False. """ self._mouseover_callbacks.register_callback(callback, remove=remove) def on_mouseout(self, callback, remove=False): """Add a mouse-out event listener. Parameters ---------- callback : callable Callback function that will be called on mouse-out event. remove: boolean Whether to remove this callback or not. Defaults to False. """ self._mouseout_callbacks.register_callback(callback, remove=remove)
(**kwargs)
13,655
ipyleaflet.leaflet
LayerException
Custom LayerException class.
class LayerException(TraitError): """Custom LayerException class.""" pass
null
13,656
ipyleaflet.leaflet
LayerGroup
LayerGroup class. A group of layers that you can put on the map like other layers. Attributes ---------- layers: list, default [] List of layers to include in the group.
class LayerGroup(Layer): """LayerGroup class. A group of layers that you can put on the map like other layers. Attributes ---------- layers: list, default [] List of layers to include in the group. """ _view_name = Unicode("LeafletLayerGroupView").tag(sync=True) _model_name = Unicode("LeafletLayerGroupModel").tag(sync=True) layers = Tuple().tag(trait=Instance(Layer), sync=True, **widget_serialization) _layer_ids = List() @validate("layers") def _validate_layers(self, proposal): """Validate layers list. Makes sure only one instance of any given layer can exist in the layers list. """ self._layer_ids = [layer.model_id for layer in proposal.value] if len(set(self._layer_ids)) != len(self._layer_ids): raise LayerException("duplicate layer detected, only use each layer once") return proposal.value def add_layer(self, layer): """Add a new layer to the group. .. deprecated :: 0.17.0 Use add method instead. Parameters ---------- layer: layer instance The new layer to include in the group. """ warnings.warn("add_layer is deprecated, use add instead", DeprecationWarning) self.add(layer) def remove_layer(self, rm_layer): """Remove a layer from the group. .. deprecated :: 0.17.0 Use remove method instead. Parameters ---------- layer: layer instance The layer to remove from the group. """ warnings.warn( "remove_layer is deprecated, use remove instead", DeprecationWarning ) self.remove(rm_layer) def substitute_layer(self, old, new): """Substitute a layer with another one in the group. .. deprecated :: 0.17.0 Use substitute method instead. Parameters ---------- old: layer instance The layer to remove from the group. new: layer instance The new layer to include in the group. """ warnings.warn( "substitute_layer is deprecated, use substitute instead", DeprecationWarning ) self.substitute(old, new) def clear_layers(self): """Remove all layers from the group. .. deprecated :: 0.17.0 Use clear method instead. """ warnings.warn( "clear_layers is deprecated, use clear instead", DeprecationWarning ) self.layers = () def add(self, layer): """Add a new layer to the group. Parameters ---------- layer: layer instance The new layer to include in the group. This can also be an object with an ``as_leaflet_layer`` method which generates a compatible layer type. """ if isinstance(layer, dict): layer = basemap_to_tiles(layer) if layer.model_id in self._layer_ids: raise LayerException("layer already in layergroup: %r" % layer) self.layers = tuple([layer for layer in self.layers] + [layer]) def remove(self, rm_layer): """Remove a layer from the group. Parameters ---------- layer: layer instance The layer to remove from the group. """ if rm_layer.model_id not in self._layer_ids: raise LayerException("layer not on in layergroup: %r" % rm_layer) self.layers = tuple( [layer for layer in self.layers if layer.model_id != rm_layer.model_id] ) def substitute(self, old, new): """Substitute a layer with another one in the group. Parameters ---------- old: layer instance The layer to remove from the group. new: layer instance The new layer to include in the group. """ if isinstance(new, dict): new = basemap_to_tiles(new) if old.model_id not in self._layer_ids: raise LayerException("Could not substitute layer: layer not in layergroup.") self.layers = tuple( [new if layer.model_id == old.model_id else layer for layer in self.layers] ) def clear(self): """Remove all layers from the group.""" self.layers = ()
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
13,729
ipyleaflet.leaflet
LayersControl
LayersControl class, with Control as parent class. A control which allows hiding/showing different layers on the Map. Attributes ---------------------- collapsed: bool, default True Set whether control should be open or closed by default
class LayersControl(Control): """LayersControl class, with Control as parent class. A control which allows hiding/showing different layers on the Map. Attributes ---------------------- collapsed: bool, default True Set whether control should be open or closed by default """ _view_name = Unicode("LeafletLayersControlView").tag(sync=True) _model_name = Unicode("LeafletLayersControlModel").tag(sync=True) collapsed = Bool(True).tag(sync=True, o=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
13,786
ipyleaflet.leaflet
LegendControl
LegendControl class, with Control as parent class. A control which contains a legend. .. deprecated :: 0.17.0 The constructor argument 'name' is deprecated, use the 'title' argument instead. Attributes ---------- title: str, default 'Legend' The title of the legend. legend: dict, default 'Legend' A dictionary containing names as keys and CSS colors as values.
class LegendControl(Control): """LegendControl class, with Control as parent class. A control which contains a legend. .. deprecated :: 0.17.0 The constructor argument 'name' is deprecated, use the 'title' argument instead. Attributes ---------- title: str, default 'Legend' The title of the legend. legend: dict, default 'Legend' A dictionary containing names as keys and CSS colors as values. """ _view_name = Unicode("LeafletLegendControlView").tag(sync=True) _model_name = Unicode("LeafletLegendControlModel").tag(sync=True) title = Unicode("Legend").tag(sync=True) legend = Dict( default_value={"value 1": "#AAF", "value 2": "#55A", "value 3": "#005"} ).tag(sync=True) def __init__(self, legend, *args, **kwargs): kwargs["legend"] = legend # For backwards compatibility with ipyleaflet<=0.16.0 if "name" in kwargs: warnings.warn( "the name argument is deprecated, use title instead", DeprecationWarning ) kwargs.setdefault("title", kwargs["name"]) del kwargs["name"] super().__init__(*args, **kwargs) @property def name(self): """The title of the legend. .. deprecated :: 0.17.0 Use title attribute instead. """ warnings.warn(".name is deprecated, use .title instead", DeprecationWarning) return self.title @name.setter def name(self, title): warnings.warn(".name is deprecated, use .title instead", DeprecationWarning) self.title = title @property def legends(self): """The legend information. .. deprecated :: 0.17.0 Use legend attribute instead. """ warnings.warn(".legends is deprecated, use .legend instead", DeprecationWarning) return self.legend @legends.setter def legends(self, legends): warnings.warn(".legends is deprecated, use .legend instead", DeprecationWarning) self.legend = legends @property def positioning(self): """The position information. .. deprecated :: 0.17.0 Use position attribute instead. """ warnings.warn( ".positioning is deprecated, use .position instead", DeprecationWarning ) return self.position @positioning.setter def positioning(self, position): warnings.warn( ".positioning is deprecated, use .position instead", DeprecationWarning ) self.position = position @property def positionning(self): """The position information. .. deprecated :: 0.17.0 Use position attribute instead. """ warnings.warn( ".positionning is deprecated, use .position instead", DeprecationWarning ) return self.position @positionning.setter def positionning(self, position): warnings.warn( ".positionning is deprecated, use .position instead", DeprecationWarning ) self.position = position def add_legend_element(self, key, value): """Add a new legend element. Parameters ---------- key: str The key for the legend element. value: CSS Color The value for the legend element. """ self.legend[key] = value self.send_state() def remove_legend_element(self, key): """Remove a legend element. Parameters ---------- key: str The element to remove. """ del self.legend[key] self.send_state()
(legend, *args, **kwargs)
13,791
ipyleaflet.leaflet
__init__
null
def __init__(self, legend, *args, **kwargs): kwargs["legend"] = legend # For backwards compatibility with ipyleaflet<=0.16.0 if "name" in kwargs: warnings.warn( "the name argument is deprecated, use title instead", DeprecationWarning ) kwargs.setdefault("title", kwargs["name"]) del kwargs["name"] super().__init__(*args, **kwargs)
(self, legend, *args, **kwargs)
13,815
ipyleaflet.leaflet
add_legend_element
Add a new legend element. Parameters ---------- key: str The key for the legend element. value: CSS Color The value for the legend element.
def add_legend_element(self, key, value): """Add a new legend element. Parameters ---------- key: str The key for the legend element. value: CSS Color The value for the legend element. """ self.legend[key] = value self.send_state()
(self, key, value)
13,831
ipyleaflet.leaflet
remove_legend_element
Remove a legend element. Parameters ---------- key: str The element to remove.
def remove_legend_element(self, key): """Remove a legend element. Parameters ---------- key: str The element to remove. """ del self.legend[key] self.send_state()
(self, key)
13,845
traitlets.traitlets
List
An instance of a Python list.
class List(Container[t.List[T]]): """An instance of a Python list.""" klass = list # type:ignore[assignment] _cast_types: t.Any = (tuple,) def __init__( self, trait: t.List[T] | t.Tuple[T] | t.Set[T] | Sentinel | TraitType[T, t.Any] | None = None, default_value: t.List[T] | t.Tuple[T] | t.Set[T] | Sentinel | None = Undefined, minlen: int = 0, maxlen: int = sys.maxsize, **kwargs: t.Any, ) -> None: """Create a List trait type from a list, set, or tuple. The default value is created by doing ``list(default_value)``, which creates a copy of the ``default_value``. ``trait`` can be specified, which restricts the type of elements in the container to that TraitType. If only one arg is given and it is not a Trait, it is taken as ``default_value``: ``c = List([1, 2, 3])`` Parameters ---------- trait : TraitType [ optional ] the type for restricting the contents of the Container. If unspecified, types are not checked. default_value : SequenceType [ optional ] The default value for the Trait. Must be list/tuple/set, and will be cast to the container type. minlen : Int [ default 0 ] The minimum length of the input list maxlen : Int [ default sys.maxsize ] The maximum length of the input list """ self._maxlen = maxlen self._minlen = minlen super().__init__(trait=trait, default_value=default_value, **kwargs) def length_error(self, obj: t.Any, value: t.Any) -> None: e = ( "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." % (self.name, class_of(obj), self._minlen, self._maxlen, value) ) raise TraitError(e) def validate_elements(self, obj: t.Any, value: t.Any) -> t.Any: length = len(value) if length < self._minlen or length > self._maxlen: self.length_error(obj, value) return super().validate_elements(obj, value) def set(self, obj: t.Any, value: t.Any) -> None: if isinstance(value, str): return super().set(obj, [value]) # type:ignore[list-item] else: return super().set(obj, value)
(trait: 't.List[T] | t.Tuple[T] | t.Set[T] | Sentinel | TraitType[T, t.Any] | None' = None, default_value: Any = traitlets.Undefined, minlen: 'int' = 0, maxlen: 'int' = 9223372036854775807, **kwargs: 't.Any') -> 'None'
13,847
traitlets.traitlets
__init__
Create a List trait type from a list, set, or tuple. The default value is created by doing ``list(default_value)``, which creates a copy of the ``default_value``. ``trait`` can be specified, which restricts the type of elements in the container to that TraitType. If only one arg is given and it is not a Trait, it is taken as ``default_value``: ``c = List([1, 2, 3])`` Parameters ---------- trait : TraitType [ optional ] the type for restricting the contents of the Container. If unspecified, types are not checked. default_value : SequenceType [ optional ] The default value for the Trait. Must be list/tuple/set, and will be cast to the container type. minlen : Int [ default 0 ] The minimum length of the input list maxlen : Int [ default sys.maxsize ] The maximum length of the input list
def __init__( self, trait: t.List[T] | t.Tuple[T] | t.Set[T] | Sentinel | TraitType[T, t.Any] | None = None, default_value: t.List[T] | t.Tuple[T] | t.Set[T] | Sentinel | None = Undefined, minlen: int = 0, maxlen: int = sys.maxsize, **kwargs: t.Any, ) -> None: """Create a List trait type from a list, set, or tuple. The default value is created by doing ``list(default_value)``, which creates a copy of the ``default_value``. ``trait`` can be specified, which restricts the type of elements in the container to that TraitType. If only one arg is given and it is not a Trait, it is taken as ``default_value``: ``c = List([1, 2, 3])`` Parameters ---------- trait : TraitType [ optional ] the type for restricting the contents of the Container. If unspecified, types are not checked. default_value : SequenceType [ optional ] The default value for the Trait. Must be list/tuple/set, and will be cast to the container type. minlen : Int [ default 0 ] The minimum length of the input list maxlen : Int [ default sys.maxsize ] The maximum length of the input list """ self._maxlen = maxlen self._minlen = minlen super().__init__(trait=trait, default_value=default_value, **kwargs)
(self, trait: Union[List[~T], Tuple[~T], Set[~T], traitlets.utils.sentinel.Sentinel, traitlets.traitlets.TraitType[~T, Any], NoneType] = None, default_value: Union[List[~T], Tuple[~T], Set[~T], traitlets.utils.sentinel.Sentinel, NoneType] = traitlets.Undefined, minlen: int = 0, maxlen: int = 9223372036854775807, **kwargs: Any) -> NoneType
13,854
traitlets.traitlets
class_init
null
def class_init(self, cls: type[t.Any], name: str | None) -> None: if isinstance(self._trait, TraitType): self._trait.class_init(cls, None) super().class_init(cls, name)
(self, cls: type[typing.Any], name: str | None) -> NoneType
13,858
traitlets.traitlets
from_string
Load value from a single string
def from_string(self, s: str) -> T | None: """Load value from a single string""" if not isinstance(s, str): raise TraitError(f"Expected string, got {s!r}") try: test = literal_eval(s) except Exception: test = None return self.validate(None, test)
(self, s: str) -> Optional[~T]
13,859
traitlets.traitlets
from_string_list
Return the value from a list of config strings This is where we parse CLI configuration
def from_string_list(self, s_list: list[str]) -> T | None: """Return the value from a list of config strings This is where we parse CLI configuration """ assert self.klass is not None if len(s_list) == 1: # check for deprecated --Class.trait="['a', 'b', 'c']" r = s_list[0] if r == "None" and self.allow_none: return None if len(r) >= 2 and any( r.startswith(start) and r.endswith(end) for start, end in self._literal_from_string_pairs ): if self.this_class: clsname = self.this_class.__name__ + "." else: clsname = "" assert self.name is not None warn( "--{0}={1} for containers is deprecated in traitlets 5.0. " "You can pass `--{0} item` ... multiple times to add items to a list.".format( clsname + self.name, r ), DeprecationWarning, stacklevel=2, ) return self.klass(literal_eval(r)) # type:ignore[call-arg] sig = inspect.signature(self.item_from_string) if "index" in sig.parameters: item_from_string = self.item_from_string else: # backward-compat: allow item_from_string to ignore index arg def item_from_string(s: str, index: int | None = None) -> T | str: return t.cast(T, self.item_from_string(s)) return self.klass( # type:ignore[call-arg] [item_from_string(s, index=idx) for idx, s in enumerate(s_list)] )
(self, s_list: list[str]) -> Optional[~T]
13,866
traitlets.traitlets
item_from_string
Cast a single item from a string Evaluated when parsing CLI configuration from a string
def item_from_string(self, s: str, index: int | None = None) -> T | str: """Cast a single item from a string Evaluated when parsing CLI configuration from a string """ if self._trait: return t.cast(T, self._trait.from_string(s)) else: return s
(self, s: str, index: Optional[int] = None) -> Union[~T, str]
13,867
traitlets.traitlets
length_error
null
def length_error(self, obj: t.Any, value: t.Any) -> None: e = ( "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." % (self.name, class_of(obj), self._minlen, self._maxlen, value) ) raise TraitError(e)
(self, obj: Any, value: Any) -> NoneType
13,869
traitlets.traitlets
set
null
def set(self, obj: t.Any, value: t.Any) -> None: if isinstance(value, str): return super().set(obj, [value]) # type:ignore[list-item] else: return super().set(obj, value)
(self, obj: Any, value: Any) -> NoneType
13,871
traitlets.traitlets
subclass_init
null
def subclass_init(self, cls: type[t.Any]) -> None: if isinstance(self._trait, TraitType): self._trait.subclass_init(cls) # explicitly not calling super().subclass_init(cls) # to opt out of instance_init
(self, cls: type[typing.Any]) -> NoneType
13,873
traitlets.traitlets
validate
null
def validate(self, obj: t.Any, value: t.Any) -> T | None: if isinstance(value, self._cast_types): assert self.klass is not None value = self.klass(value) # type:ignore[call-arg] value = super().validate(obj, value) if value is None: return value value = self.validate_elements(obj, value) return t.cast(T, value)
(self, obj: Any, value: Any) -> Optional[~T]
13,874
traitlets.traitlets
validate_elements
null
def validate_elements(self, obj: t.Any, value: t.Any) -> t.Any: length = len(value) if length < self._minlen or length > self._maxlen: self.length_error(obj, value) return super().validate_elements(obj, value)
(self, obj: Any, value: Any) -> Any
13,875
ipyleaflet.leaflet
LocalTileLayer
LocalTileLayer class. Custom tile layer using local tile files. Attributes ---------- path: string, default "" Path to your local tiles. In the classic Jupyter Notebook, the path is relative to the Notebook you are working on. In JupyterLab, the path is relative to the server (where you started JupyterLab) and you need to prefix the path with “files/”.
class LocalTileLayer(TileLayer): """LocalTileLayer class. Custom tile layer using local tile files. Attributes ---------- path: string, default "" Path to your local tiles. In the classic Jupyter Notebook, the path is relative to the Notebook you are working on. In JupyterLab, the path is relative to the server (where you started JupyterLab) and you need to prefix the path with “files/”. """ _view_name = Unicode("LeafletLocalTileLayerView").tag(sync=True) _model_name = Unicode("LeafletLocalTileLayerModel").tag(sync=True) path = Unicode("").tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
13,880
ipyleaflet.leaflet
__init__
null
def __init__(self, **kwargs): super(TileLayer, self).__init__(**kwargs) self.on_msg(self._handle_leaflet_event)
(self, **kwargs)
13,891
ipyleaflet.leaflet
_handle_leaflet_event
null
def _handle_leaflet_event(self, _, content, buffers): if content.get("event", "") == "load": self._load_callbacks(**content)
(self, _, content, buffers)
13,920
ipyleaflet.leaflet
on_load
Add a load event listener. Parameters ---------- callback : callable Callback function that will be called when the tiles have finished loading. remove: boolean Whether to remove this callback or not. Defaults to False.
def on_load(self, callback, remove=False): """Add a load event listener. Parameters ---------- callback : callable Callback function that will be called when the tiles have finished loading. remove: boolean Whether to remove this callback or not. Defaults to False. """ self._load_callbacks.register_callback(callback, remove=remove)
(self, callback, remove=False)
13,929
ipyleaflet.leaflet
redraw
Force redrawing the tiles. This is especially useful when you are sure the server updated the tiles and you need to refresh the layer.
def redraw(self): """Force redrawing the tiles. This is especially useful when you are sure the server updated the tiles and you need to refresh the layer. """ self.send({"msg": "redraw"})
(self)
13,943
ipyleaflet.leaflet
MagnifyingGlass
MagnifyingGlass class. Attributes ---------- radius: int, default 100 The radius of the magnifying glass, in pixels. zoom_offset: int, default 3 The zoom level offset between the main map zoom and the magnifying glass. fixed_zoom: int, default -1 If different than -1, defines a fixed zoom level to always use in the magnifying glass, ignoring the main map zoom and the zoomOffet value. fixed_position: boolean, default False If True, the magnifying glass will stay at the same position on the map, not following the mouse cursor. lat_lng: list, default [0, 0] The initial position of the magnifying glass, both on the main map and as the center of the magnified view. If fixed_position is True, it will always keep this position. layers: list, default [] Set of layers to display in the magnified view. These layers shouldn't be already added to a map instance.
class MagnifyingGlass(RasterLayer): """MagnifyingGlass class. Attributes ---------- radius: int, default 100 The radius of the magnifying glass, in pixels. zoom_offset: int, default 3 The zoom level offset between the main map zoom and the magnifying glass. fixed_zoom: int, default -1 If different than -1, defines a fixed zoom level to always use in the magnifying glass, ignoring the main map zoom and the zoomOffet value. fixed_position: boolean, default False If True, the magnifying glass will stay at the same position on the map, not following the mouse cursor. lat_lng: list, default [0, 0] The initial position of the magnifying glass, both on the main map and as the center of the magnified view. If fixed_position is True, it will always keep this position. layers: list, default [] Set of layers to display in the magnified view. These layers shouldn't be already added to a map instance. """ _view_name = Unicode("LeafletMagnifyingGlassView").tag(sync=True) _model_name = Unicode("LeafletMagnifyingGlassModel").tag(sync=True) # Options radius = Int(100).tag(sync=True, o=True) zoom_offset = Int(3).tag(sync=True, o=True) fixed_zoom = Int(-1).tag(sync=True, o=True) fixed_position = Bool(False).tag(sync=True, o=True) lat_lng = List(def_loc).tag(sync=True, o=True) layers = Tuple().tag( trait=Instance(Layer), sync=True, o=True, **widget_serialization ) _layer_ids = List() @validate("layers") def _validate_layers(self, proposal): """Validate layers list. Makes sure only one instance of any given layer can exist in the layers list. """ self._layer_ids = [layer.model_id for layer in proposal.value] if len(set(self._layer_ids)) != len(self._layer_ids): raise LayerException("duplicate layer detected, only use each layer once") return proposal.value
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
14,008
ipyleaflet.leaflet
Map
Map class. The Map class is the main widget in ipyleaflet. Attributes ---------- layers: list of Layer instances The list of layers that are currently on the map. controls: list of Control instances The list of controls that are currently on the map. center: list, default [0, 0] The current center of the map. zoom: float, default 12 The current zoom value of the map. max_zoom: float, default None Maximal zoom value. min_zoom: float, default None Minimal zoom value. zoom_snap: float, default 1 Forces the map’s zoom level to always be a multiple of this. zoom_delta: float, default 1 Controls how much the map’s zoom level will change after pressing + or - on the keyboard, or using the zoom controls. crs: projection, default projections.EPSG3857 Coordinate reference system, which can be ‘Earth’, ‘EPSG3395’, ‘EPSG3857’, ‘EPSG4326’, ‘Base’, ‘Simple’ or user defined projection. dragging: boolean, default True Whether the map be draggable with mouse/touch or not. touch_zoom: boolean, default True Whether the map can be zoomed by touch-dragging with two fingers on mobile. scroll_wheel_zoom: boolean,default False Whether the map can be zoomed by using the mouse wheel. double_click_zoom: boolean, default True Whether the map can be zoomed in by double clicking on it and zoomed out by double clicking while holding shift. box_zoom: boolean, default True Whether the map can be zoomed to a rectangular area specified by dragging the mouse while pressing the shift key tap: boolean, default True Enables mobile hacks for supporting instant taps. tap_tolerance: int, default 15 The max number of pixels a user can shift his finger during touch for it to be considered a valid tap. world_copy_jump: boolean, default False With this option enabled, the map tracks when you pan to another “copy” of the world and seamlessly jumps to. close_popup_on_click: boolean, default True Set it to False if you don’t want popups to close when user clicks the map. bounce_at_zoom_limits: boolean, default True Set it to False if you don’t want the map to zoom beyond min/max zoom and then bounce back when pinch-zooming. keyboard: booelan, default True Makes the map focusable and allows users to navigate the map with keyboard arrows and +/- keys. keyboard_pan_offset: int, default 80 keyboard_zoom_offset: int, default 1 inertia: boolean, default True If enabled, panning of the map will have an inertia effect. inertia_deceleration: float, default 3000 The rate with which the inertial movement slows down, in pixels/second². inertia_max_speed: float, default 1500 Max speed of the inertial movement, in pixels/second. zoom_control: boolean, default True attribution_control: boolean, default True zoom_animation_threshold: int, default 4
class Map(DOMWidget, InteractMixin): """Map class. The Map class is the main widget in ipyleaflet. Attributes ---------- layers: list of Layer instances The list of layers that are currently on the map. controls: list of Control instances The list of controls that are currently on the map. center: list, default [0, 0] The current center of the map. zoom: float, default 12 The current zoom value of the map. max_zoom: float, default None Maximal zoom value. min_zoom: float, default None Minimal zoom value. zoom_snap: float, default 1 Forces the map’s zoom level to always be a multiple of this. zoom_delta: float, default 1 Controls how much the map’s zoom level will change after pressing + or - on the keyboard, or using the zoom controls. crs: projection, default projections.EPSG3857 Coordinate reference system, which can be ‘Earth’, ‘EPSG3395’, ‘EPSG3857’, ‘EPSG4326’, ‘Base’, ‘Simple’ or user defined projection. dragging: boolean, default True Whether the map be draggable with mouse/touch or not. touch_zoom: boolean, default True Whether the map can be zoomed by touch-dragging with two fingers on mobile. scroll_wheel_zoom: boolean,default False Whether the map can be zoomed by using the mouse wheel. double_click_zoom: boolean, default True Whether the map can be zoomed in by double clicking on it and zoomed out by double clicking while holding shift. box_zoom: boolean, default True Whether the map can be zoomed to a rectangular area specified by dragging the mouse while pressing the shift key tap: boolean, default True Enables mobile hacks for supporting instant taps. tap_tolerance: int, default 15 The max number of pixels a user can shift his finger during touch for it to be considered a valid tap. world_copy_jump: boolean, default False With this option enabled, the map tracks when you pan to another “copy” of the world and seamlessly jumps to. close_popup_on_click: boolean, default True Set it to False if you don’t want popups to close when user clicks the map. bounce_at_zoom_limits: boolean, default True Set it to False if you don’t want the map to zoom beyond min/max zoom and then bounce back when pinch-zooming. keyboard: booelan, default True Makes the map focusable and allows users to navigate the map with keyboard arrows and +/- keys. keyboard_pan_offset: int, default 80 keyboard_zoom_offset: int, default 1 inertia: boolean, default True If enabled, panning of the map will have an inertia effect. inertia_deceleration: float, default 3000 The rate with which the inertial movement slows down, in pixels/second². inertia_max_speed: float, default 1500 Max speed of the inertial movement, in pixels/second. zoom_control: boolean, default True attribution_control: boolean, default True zoom_animation_threshold: int, default 4 """ _view_name = Unicode("LeafletMapView").tag(sync=True) _model_name = Unicode("LeafletMapModel").tag(sync=True) _view_module = Unicode("jupyter-leaflet").tag(sync=True) _model_module = Unicode("jupyter-leaflet").tag(sync=True) _view_module_version = Unicode(EXTENSION_VERSION).tag(sync=True) _model_module_version = Unicode(EXTENSION_VERSION).tag(sync=True) # URL of the window where the map is displayed window_url = Unicode(read_only=True).tag(sync=True) # Map options center = List(def_loc).tag(sync=True, o=True) zoom = CFloat(12).tag(sync=True, o=True) max_zoom = CFloat(default_value=None, allow_none=True).tag(sync=True, o=True) min_zoom = CFloat(default_value=None, allow_none=True).tag(sync=True, o=True) zoom_delta = CFloat(1).tag(sync=True, o=True) zoom_snap = CFloat(1).tag(sync=True, o=True) interpolation = Unicode("bilinear").tag(sync=True, o=True) crs = Dict(default_value=projections.EPSG3857).tag(sync=True) prefer_canvas = Bool(False).tag(sync=True, o=True) # Specification of the basemap basemap = Union( (Dict(), Instance(xyzservices.lib.TileProvider), Instance(TileLayer)), default_value=xyzservices.providers.OpenStreetMap.Mapnik, ) modisdate = Unicode((date.today() - timedelta(days=1)).strftime("%Y-%m-%d")).tag( sync=True ) # Interaction options dragging = Bool(True).tag(sync=True, o=True) touch_zoom = Bool(True).tag(sync=True, o=True) scroll_wheel_zoom = Bool(False).tag(sync=True, o=True) double_click_zoom = Bool(True).tag(sync=True, o=True) box_zoom = Bool(True).tag(sync=True, o=True) tap = Bool(True).tag(sync=True, o=True) tap_tolerance = Int(15).tag(sync=True, o=True) world_copy_jump = Bool(False).tag(sync=True, o=True) close_popup_on_click = Bool(True).tag(sync=True, o=True) bounce_at_zoom_limits = Bool(True).tag(sync=True, o=True) keyboard = Bool(True).tag(sync=True, o=True) keyboard_pan_offset = Int(80).tag(sync=True, o=True) keyboard_zoom_offset = Int(1).tag(sync=True, o=True) inertia = Bool(True).tag(sync=True, o=True) inertia_deceleration = Int(3000).tag(sync=True, o=True) inertia_max_speed = Int(1500).tag(sync=True, o=True) # inertia_threshold = Int(?, o=True).tag(sync=True) # fade_animation = Bool(?).tag(sync=True, o=True) # zoom_animation = Bool(?).tag(sync=True, o=True) zoom_animation_threshold = Int(4).tag(sync=True, o=True) # marker_zoom_animation = Bool(?).tag(sync=True, o=True) fullscreen = Bool(False).tag(sync=True, o=True) options = List(trait=Unicode()).tag(sync=True) style = InstanceDict(MapStyle).tag(sync=True, **widget_serialization) default_style = InstanceDict(MapStyle).tag(sync=True, **widget_serialization) dragging_style = InstanceDict(MapStyle).tag(sync=True, **widget_serialization) zoom_control = Bool(True) attribution_control = Bool(True) @default("dragging_style") def _default_dragging_style(self): return {"cursor": "move"} @default("options") def _default_options(self): return [name for name in self.traits(o=True)] south = Float(def_loc[0], read_only=True).tag(sync=True) north = Float(def_loc[0], read_only=True).tag(sync=True) east = Float(def_loc[1], read_only=True).tag(sync=True) west = Float(def_loc[1], read_only=True).tag(sync=True) bottom = Float(0, read_only=True).tag(sync=True) top = Float(9007199254740991, read_only=True).tag(sync=True) right = Float(0, read_only=True).tag(sync=True) left = Float(9007199254740991, read_only=True).tag(sync=True) panes = Dict().tag(sync=True) layers = Tuple().tag(trait=Instance(Layer), sync=True, **widget_serialization) @default("layers") def _default_layers(self): basemap = ( self.basemap if isinstance(self.basemap, TileLayer) else basemap_to_tiles(self.basemap, day=self.modisdate) ) basemap.base = True return (basemap,) bounds = Tuple(read_only=True) bounds_polygon = Tuple(read_only=True) pixel_bounds = Tuple(read_only=True) @observe("south", "north", "east", "west") def _observe_bounds(self, change): self.set_trait("bounds", ((self.south, self.west), (self.north, self.east))) self.set_trait( "bounds_polygon", ( (self.north, self.west), (self.north, self.east), (self.south, self.east), (self.south, self.west), ), ) @observe("bottom", "top", "right", "left") def _observe_pixel_bounds(self, change): self.set_trait( "pixel_bounds", ((self.left, self.top), (self.right, self.bottom)) ) def __init__(self, **kwargs): self.zoom_control_instance = None self.attribution_control_instance = None super(Map, self).__init__(**kwargs) self.on_msg(self._handle_leaflet_event) if self.zoom_control: self.zoom_control_instance = ZoomControl() self.add(self.zoom_control_instance) if self.attribution_control: self.attribution_control_instance = AttributionControl( position="bottomright" ) self.add(self.attribution_control_instance) @observe("zoom_control") def observe_zoom_control(self, change): if change["new"]: self.zoom_control_instance = ZoomControl() self.add(self.zoom_control_instance) else: if ( self.zoom_control_instance is not None and self.zoom_control_instance in self.controls ): self.remove(self.zoom_control_instance) @observe("attribution_control") def observe_attribution_control(self, change): if change["new"]: self.attribution_control_instance = AttributionControl( position="bottomright" ) self.add(self.attribution_control_instance) else: if ( self.attribution_control_instance is not None and self.attribution_control_instance in self.controls ): self.remove(self.attribution_control_instance) @validate("panes") def _validate_panes(self, proposal): """Validate panes.""" error_msg = "Panes should look like: {'pane_name': {'zIndex': 650, 'pointerEvents': 'none'}, ...}" for k1, v1 in proposal.value.items(): if not isinstance(k1, str) or not isinstance(v1, dict): raise PaneException(error_msg) for k2, v2 in v1.items(): if not isinstance(k2, str) or not isinstance(v2, (str, int, float)): raise PaneException(error_msg) return proposal.value _layer_ids = List() @validate("layers") def _validate_layers(self, proposal): """Validate layers list. Makes sure only one instance of any given layer can exist in the layers list. """ self._layer_ids = [layer.model_id for layer in proposal.value] if len(set(self._layer_ids)) != len(self._layer_ids): raise LayerException("duplicate layer detected, only use each layer once") return proposal.value def add_layer(self, layer): """Add a layer on the map. .. deprecated :: 0.17.0 Use add method instead. Parameters ---------- layer: Layer instance The new layer to add. """ warnings.warn("add_layer is deprecated, use add instead", DeprecationWarning) self.add(layer) def remove_layer(self, rm_layer): """Remove a layer from the map. .. deprecated :: 0.17.0 Use remove method instead. Parameters ---------- layer: Layer instance The layer to remove. """ warnings.warn( "remove_layer is deprecated, use remove instead", DeprecationWarning ) self.remove(rm_layer) def substitute_layer(self, old, new): """Replace a layer with another one on the map. .. deprecated :: 0.17.0 Use substitute method instead. Parameters ---------- old: Layer instance The old layer to remove. new: Layer instance The new layer to add. """ warnings.warn( "substitute_layer is deprecated, use substitute instead", DeprecationWarning ) self.substitute(old, new) def clear_layers(self): """Remove all layers from the map. .. deprecated :: 0.17.0 Use add method instead. """ warnings.warn( "clear_layers is deprecated, use clear instead", DeprecationWarning ) self.layers = () controls = Tuple().tag(trait=Instance(Control), sync=True, **widget_serialization) _control_ids = List() @validate("controls") def _validate_controls(self, proposal): """Validate controls list. Makes sure only one instance of any given layer can exist in the controls list. """ self._control_ids = [c.model_id for c in proposal.value] if len(set(self._control_ids)) != len(self._control_ids): raise ControlException( "duplicate control detected, only use each control once" ) return proposal.value def add_control(self, control): """Add a control on the map. .. deprecated :: 0.17.0 Use add method instead. Parameters ---------- control: Control instance The new control to add. """ warnings.warn("add_control is deprecated, use add instead", DeprecationWarning) self.add(control) def remove_control(self, control): """Remove a control from the map. .. deprecated :: 0.17.0 Use remove method instead. Parameters ---------- control: Control instance The control to remove. """ warnings.warn( "remove_control is deprecated, use remove instead", DeprecationWarning ) self.remove(control) def clear_controls(self): """Remove all controls from the map. .. deprecated :: 0.17.0 Use clear method instead. """ warnings.warn( "clear_controls is deprecated, use clear instead", DeprecationWarning ) self.controls = () def save(self, outfile, **kwargs): """Save the Map to an .html file. Parameters ---------- outfile: str or file-like object The file to write the HTML output to. kwargs: keyword-arguments Extra parameters to pass to the ipywidgets.embed.embed_minimal_html function. """ embed_minimal_html(outfile, views=[self], **kwargs) def __iadd__(self, item): self.add(item) return self def __isub__(self, item): self.remove(item) return self def __add__(self, item): return self.add(item) def add(self, item, index=None): """Add an item on the map: either a layer or a control. Parameters ---------- item: Layer or Control instance The layer or control to add. index: int The index to insert a Layer. If not specified, the layer is added to the end (on top). """ if hasattr(item, "as_leaflet_layer"): item = item.as_leaflet_layer() if isinstance(item, Layer): if isinstance(item, dict): item = basemap_to_tiles(item) if item.model_id in self._layer_ids: raise LayerException("layer already on map: %r" % item) if index is not None: if not isinstance(index, int) or index < 0 or index > len(self.layers): raise ValueError("Invalid index value") self.layers = tuple( list(self.layers)[:index] + [item] + list(self.layers)[index:] ) else: self.layers = tuple([layer for layer in self.layers] + [item]) elif isinstance(item, Control): if item.model_id in self._control_ids: raise ControlException("control already on map: %r" % item) self.controls = tuple([control for control in self.controls] + [item]) return self def remove(self, item): """Remove an item from the map : either a layer or a control. Parameters ---------- item: Layer or Control instance The layer or control to remove. """ if isinstance(item, Layer): if item.model_id not in self._layer_ids: raise LayerException("layer not on map: %r" % item) self.layers = tuple( [layer for layer in self.layers if layer.model_id != item.model_id] ) elif isinstance(item, Control): if item.model_id not in self._control_ids: raise ControlException("control not on map: %r" % item) self.controls = tuple( [ control for control in self.controls if control.model_id != item.model_id ] ) return self def clear(self): "Clear all layers and controls." self.controls = () self.layers = () return self def substitute(self, old, new): """Replace an item (layer or control) with another one on the map. Parameters ---------- old: Layer or control instance The old layer or control to remove. new: Layer or control instance The new layer or control to add. """ if isinstance(new, Layer): if isinstance(new, dict): new = basemap_to_tiles(new) if old.model_id not in self._layer_ids: raise LayerException("Could not substitute layer: layer not on map.") self.layers = tuple( [ new if layer.model_id == old.model_id else layer for layer in self.layers ] ) elif isinstance(new, Control): if old.model_id not in self._control_ids: raise ControlException( "Could not substitute control: control not on map." ) self.controls = tuple( [ new if control.model_id == old.model_id else control for control in self.controls ] ) return self # Event handling _interaction_callbacks = Instance(CallbackDispatcher, ()) def _handle_leaflet_event(self, _, content, buffers): if content.get("event", "") == "interaction": self._interaction_callbacks(**content) def on_interaction(self, callback, remove=False): self._interaction_callbacks.register_callback(callback, remove=remove) def fit_bounds(self, bounds): """Sets a map view that contains the given geographical bounds with the maximum zoom level possible. Parameters ---------- bounds: list of lists The lat/lon bounds in the form [[south, west], [north, east]]. """ asyncio.ensure_future(self._fit_bounds(bounds)) async def _fit_bounds(self, bounds): (b_south, b_west), (b_north, b_east) = bounds center = b_south + (b_north - b_south) / 2, b_west + (b_east - b_west) / 2 if center != self.center: self.center = center await wait_for_change(self, "bounds") zoomed_out = False # zoom out while True: if self.zoom <= 1: break (south, west), (north, east) = self.bounds if south > b_south or north < b_north or west > b_west or east < b_east: self.zoom -= 1 await wait_for_change(self, "bounds") zoomed_out = True else: break if not zoomed_out: # zoom in while True: (south, west), (north, east) = self.bounds if ( south < b_south and north > b_north and west < b_west and east > b_east ): self.zoom += 1 await wait_for_change(self, "bounds") else: self.zoom -= 1 await wait_for_change(self, "bounds") break
(**kwargs)
14,009
ipyleaflet.leaflet
__add__
null
def __add__(self, item): return self.add(item)
(self, item)
14,014
ipyleaflet.leaflet
__iadd__
null
def __iadd__(self, item): self.add(item) return self
(self, item)
14,015
ipyleaflet.leaflet
__init__
null
def __init__(self, **kwargs): self.zoom_control_instance = None self.attribution_control_instance = None super(Map, self).__init__(**kwargs) self.on_msg(self._handle_leaflet_event) if self.zoom_control: self.zoom_control_instance = ZoomControl() self.add(self.zoom_control_instance) if self.attribution_control: self.attribution_control_instance = AttributionControl( position="bottomright" ) self.add(self.attribution_control_instance)
(self, **kwargs)
14,016
ipyleaflet.leaflet
__isub__
null
def __isub__(self, item): self.remove(item) return self
(self, item)
14,023
ipyleaflet.leaflet
_fit_bounds
null
def fit_bounds(self, bounds): """Sets a map view that contains the given geographical bounds with the maximum zoom level possible. Parameters ---------- bounds: list of lists The lat/lon bounds in the form [[south, west], [north, east]]. """ asyncio.ensure_future(self._fit_bounds(bounds))
(self, bounds)
14,028
ipyleaflet.leaflet
_handle_leaflet_event
null
def _handle_leaflet_event(self, _, content, buffers): if content.get("event", "") == "interaction": self._interaction_callbacks(**content)
(self, _, content, buffers)
14,042
ipyleaflet.leaflet
add
Add an item on the map: either a layer or a control. Parameters ---------- item: Layer or Control instance The layer or control to add. index: int The index to insert a Layer. If not specified, the layer is added to the end (on top).
def add(self, item, index=None): """Add an item on the map: either a layer or a control. Parameters ---------- item: Layer or Control instance The layer or control to add. index: int The index to insert a Layer. If not specified, the layer is added to the end (on top). """ if hasattr(item, "as_leaflet_layer"): item = item.as_leaflet_layer() if isinstance(item, Layer): if isinstance(item, dict): item = basemap_to_tiles(item) if item.model_id in self._layer_ids: raise LayerException("layer already on map: %r" % item) if index is not None: if not isinstance(index, int) or index < 0 or index > len(self.layers): raise ValueError("Invalid index value") self.layers = tuple( list(self.layers)[:index] + [item] + list(self.layers)[index:] ) else: self.layers = tuple([layer for layer in self.layers] + [item]) elif isinstance(item, Control): if item.model_id in self._control_ids: raise ControlException("control already on map: %r" % item) self.controls = tuple([control for control in self.controls] + [item]) return self
(self, item, index=None)
14,044
ipyleaflet.leaflet
add_control
Add a control on the map. .. deprecated :: 0.17.0 Use add method instead. Parameters ---------- control: Control instance The new control to add.
def add_control(self, control): """Add a control on the map. .. deprecated :: 0.17.0 Use add method instead. Parameters ---------- control: Control instance The new control to add. """ warnings.warn("add_control is deprecated, use add instead", DeprecationWarning) self.add(control)
(self, control)
14,045
ipyleaflet.leaflet
add_layer
Add a layer on the map. .. deprecated :: 0.17.0 Use add method instead. Parameters ---------- layer: Layer instance The new layer to add.
def add_layer(self, layer): """Add a layer on the map. .. deprecated :: 0.17.0 Use add method instead. Parameters ---------- layer: Layer instance The new layer to add. """ warnings.warn("add_layer is deprecated, use add instead", DeprecationWarning) self.add(layer)
(self, layer)
14,048
ipyleaflet.leaflet
clear
Clear all layers and controls.
def clear(self): "Clear all layers and controls." self.controls = () self.layers = () return self
(self)
14,049
ipyleaflet.leaflet
clear_controls
Remove all controls from the map. .. deprecated :: 0.17.0 Use clear method instead.
def clear_controls(self): """Remove all controls from the map. .. deprecated :: 0.17.0 Use clear method instead. """ warnings.warn( "clear_controls is deprecated, use clear instead", DeprecationWarning ) self.controls = ()
(self)
14,050
ipyleaflet.leaflet
clear_layers
Remove all layers from the map. .. deprecated :: 0.17.0 Use add method instead.
def clear_layers(self): """Remove all layers from the map. .. deprecated :: 0.17.0 Use add method instead. """ warnings.warn( "clear_layers is deprecated, use clear instead", DeprecationWarning ) self.layers = ()
(self)
14,052
ipyleaflet.leaflet
fit_bounds
Sets a map view that contains the given geographical bounds with the maximum zoom level possible. Parameters ---------- bounds: list of lists The lat/lon bounds in the form [[south, west], [north, east]].
def fit_bounds(self, bounds): """Sets a map view that contains the given geographical bounds with the maximum zoom level possible. Parameters ---------- bounds: list of lists The lat/lon bounds in the form [[south, west], [north, east]]. """ asyncio.ensure_future(self._fit_bounds(bounds))
(self, bounds)
14,064
ipyleaflet.leaflet
on_interaction
null
def on_interaction(self, callback, remove=False): self._interaction_callbacks.register_callback(callback, remove=remove)
(self, callback, remove=False)
14,069
ipyleaflet.leaflet
remove
Remove an item from the map : either a layer or a control. Parameters ---------- item: Layer or Control instance The layer or control to remove.
def remove(self, item): """Remove an item from the map : either a layer or a control. Parameters ---------- item: Layer or Control instance The layer or control to remove. """ if isinstance(item, Layer): if item.model_id not in self._layer_ids: raise LayerException("layer not on map: %r" % item) self.layers = tuple( [layer for layer in self.layers if layer.model_id != item.model_id] ) elif isinstance(item, Control): if item.model_id not in self._control_ids: raise ControlException("control not on map: %r" % item) self.controls = tuple( [ control for control in self.controls if control.model_id != item.model_id ] ) return self
(self, item)
14,071
ipyleaflet.leaflet
remove_control
Remove a control from the map. .. deprecated :: 0.17.0 Use remove method instead. Parameters ---------- control: Control instance The control to remove.
def remove_control(self, control): """Remove a control from the map. .. deprecated :: 0.17.0 Use remove method instead. Parameters ---------- control: Control instance The control to remove. """ warnings.warn( "remove_control is deprecated, use remove instead", DeprecationWarning ) self.remove(control)
(self, control)
14,072
ipyleaflet.leaflet
remove_layer
Remove a layer from the map. .. deprecated :: 0.17.0 Use remove method instead. Parameters ---------- layer: Layer instance The layer to remove.
def remove_layer(self, rm_layer): """Remove a layer from the map. .. deprecated :: 0.17.0 Use remove method instead. Parameters ---------- layer: Layer instance The layer to remove. """ warnings.warn( "remove_layer is deprecated, use remove instead", DeprecationWarning ) self.remove(rm_layer)
(self, rm_layer)
14,073
ipyleaflet.leaflet
save
Save the Map to an .html file. Parameters ---------- outfile: str or file-like object The file to write the HTML output to. kwargs: keyword-arguments Extra parameters to pass to the ipywidgets.embed.embed_minimal_html function.
def save(self, outfile, **kwargs): """Save the Map to an .html file. Parameters ---------- outfile: str or file-like object The file to write the HTML output to. kwargs: keyword-arguments Extra parameters to pass to the ipywidgets.embed.embed_minimal_html function. """ embed_minimal_html(outfile, views=[self], **kwargs)
(self, outfile, **kwargs)
14,079
ipyleaflet.leaflet
substitute
Replace an item (layer or control) with another one on the map. Parameters ---------- old: Layer or control instance The old layer or control to remove. new: Layer or control instance The new layer or control to add.
def substitute(self, old, new): """Replace an item (layer or control) with another one on the map. Parameters ---------- old: Layer or control instance The old layer or control to remove. new: Layer or control instance The new layer or control to add. """ if isinstance(new, Layer): if isinstance(new, dict): new = basemap_to_tiles(new) if old.model_id not in self._layer_ids: raise LayerException("Could not substitute layer: layer not on map.") self.layers = tuple( [ new if layer.model_id == old.model_id else layer for layer in self.layers ] ) elif isinstance(new, Control): if old.model_id not in self._control_ids: raise ControlException( "Could not substitute control: control not on map." ) self.controls = tuple( [ new if control.model_id == old.model_id else control for control in self.controls ] ) return self
(self, old, new)
14,080
ipyleaflet.leaflet
substitute_layer
Replace a layer with another one on the map. .. deprecated :: 0.17.0 Use substitute method instead. Parameters ---------- old: Layer instance The old layer to remove. new: Layer instance The new layer to add.
def substitute_layer(self, old, new): """Replace a layer with another one on the map. .. deprecated :: 0.17.0 Use substitute method instead. Parameters ---------- old: Layer instance The old layer to remove. new: Layer instance The new layer to add. """ warnings.warn( "substitute_layer is deprecated, use substitute instead", DeprecationWarning ) self.substitute(old, new)
(self, old, new)
14,089
ipyleaflet.leaflet
MapStyle
Map Style Widget Custom map style. Attributes ---------- cursor: str, default 'grab' The cursor to use for the mouse when it's on the map. Should be a valid CSS cursor value.
class MapStyle(Style, Widget): """Map Style Widget Custom map style. Attributes ---------- cursor: str, default 'grab' The cursor to use for the mouse when it's on the map. Should be a valid CSS cursor value. """ _model_name = Unicode("LeafletMapStyleModel").tag(sync=True) _model_module = Unicode("jupyter-leaflet").tag(sync=True) _model_module_version = Unicode(EXTENSION_VERSION).tag(sync=True) cursor = Enum(values=allowed_cursor, default_value="grab").tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
14,146
ipyleaflet.leaflet
Marker
Marker class. Clickable/Draggable marker on the map. Attributes ---------- location: tuple, default (0, 0) The tuple containing the latitude/longitude of the marker. opacity: float, default 1. Opacity of the marker between 0. (fully transparent) and 1. (fully opaque). visible: boolean, default True Whether the marker is visible or not. icon: object, default None Icon used for the marker, it can be an Icon or an AwesomeIcon instance. By default it will use a blue icon. draggable: boolean, default True Whether the marker is draggable with the mouse or not. keyboard: boolean, default True Whether the marker can be tabbed to with a keyboard and clicked by pressing enter. title: string, default '' Text for the browser tooltip that appear on marker hover (no tooltip by default). alt: string, default '' Text for the alt attribute of the icon image (useful for accessibility). rotation_angle: float, default 0. The rotation angle of the marker in degrees. rotation_origin: string, default '' The rotation origin of the marker. z_index_offset: int, default 0 opacity: float, default 1.0 rise_offset: int, default 250 The z-index offset used for the rise_on_hover feature
class Marker(UILayer): """Marker class. Clickable/Draggable marker on the map. Attributes ---------- location: tuple, default (0, 0) The tuple containing the latitude/longitude of the marker. opacity: float, default 1. Opacity of the marker between 0. (fully transparent) and 1. (fully opaque). visible: boolean, default True Whether the marker is visible or not. icon: object, default None Icon used for the marker, it can be an Icon or an AwesomeIcon instance. By default it will use a blue icon. draggable: boolean, default True Whether the marker is draggable with the mouse or not. keyboard: boolean, default True Whether the marker can be tabbed to with a keyboard and clicked by pressing enter. title: string, default '' Text for the browser tooltip that appear on marker hover (no tooltip by default). alt: string, default '' Text for the alt attribute of the icon image (useful for accessibility). rotation_angle: float, default 0. The rotation angle of the marker in degrees. rotation_origin: string, default '' The rotation origin of the marker. z_index_offset: int, default 0 opacity: float, default 1.0 rise_offset: int, default 250 The z-index offset used for the rise_on_hover feature """ _view_name = Unicode("LeafletMarkerView").tag(sync=True) _model_name = Unicode("LeafletMarkerModel").tag(sync=True) location = List(def_loc).tag(sync=True) opacity = Float(1.0, min=0.0, max=1.0).tag(sync=True) visible = Bool(True).tag(sync=True) icon = Union( (Instance(Icon), Instance(AwesomeIcon), Instance(DivIcon)), allow_none=True, default_value=None, ).tag(sync=True, **widget_serialization) # Options z_index_offset = Int(0).tag(sync=True, o=True) draggable = Bool(True).tag(sync=True, o=True) keyboard = Bool(True).tag(sync=True, o=True) title = Unicode("").tag(sync=True, o=True) alt = Unicode("").tag(sync=True, o=True) rise_on_hover = Bool(False).tag(sync=True, o=True) rise_offset = Int(250).tag(sync=True, o=True) rotation_angle = Float(0).tag(sync=True, o=True) rotation_origin = Unicode("").tag(sync=True, o=True) _move_callbacks = Instance(CallbackDispatcher, ()) def __init__(self, **kwargs): super(Marker, self).__init__(**kwargs) self.on_msg(self._handle_leaflet_event) def _handle_leaflet_event(self, _, content, buffers): if content.get("event", "") == "move": self._move_callbacks(**content) def on_move(self, callback, remove=False): """Add a move event listener. Parameters ---------- callback : callable Callback function that will be called on move event. remove: boolean Whether to remove this callback or not. Defaults to False. """ self._move_callbacks.register_callback(callback, remove=remove)
(**kwargs)
14,151
ipyleaflet.leaflet
__init__
null
def __init__(self, **kwargs): super(Marker, self).__init__(**kwargs) self.on_msg(self._handle_leaflet_event)
(self, **kwargs)
14,162
ipyleaflet.leaflet
_handle_leaflet_event
null
def _handle_leaflet_event(self, _, content, buffers): if content.get("event", "") == "move": self._move_callbacks(**content)
(self, _, content, buffers)
14,195
ipyleaflet.leaflet
on_move
Add a move event listener. Parameters ---------- callback : callable Callback function that will be called on move event. remove: boolean Whether to remove this callback or not. Defaults to False.
def on_move(self, callback, remove=False): """Add a move event listener. Parameters ---------- callback : callable Callback function that will be called on move event. remove: boolean Whether to remove this callback or not. Defaults to False. """ self._move_callbacks.register_callback(callback, remove=remove)
(self, callback, remove=False)