o
    Pf                    @   sd  d Z ddlZddlZddlZddlZddlmZmZmZm	Z	m
Z
mZmZmZmZ ddlZddlZddlmZmZmZ ddlmZmZmZmZmZmZ ddlmZ ddlm Z  ddl!m"Z" dd	l#m$Z$ dd
l%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z: ddl;m<Z<m=Z=m>Z>m?Z? G dd de"e)Z@G dd de"eZAG dd deZBG dd de(ZCeeDeeDe
eeDeEf  f f ZFG dd dZGG dd de"e(ZHG dd deZIG dd deIZJG dd deIZKG dd  d e&ZLG d!d" d"eZMG d#d$ d$eZNG d%d& d&eZOG d'd( d(eZPG d)d* d*e'ZQG d+d, d,e&ZRdS )-z.
Leaflet GeoJson and miscellaneous features.

    N)	AnyCallableDictIterableListOptionalSequenceTupleUnion)ColorMapLinearColormapStepColormap)ElementFigureHtmlIFrameJavascriptLinkMacroElement)color_brewer)Template)
JSCSSMixin)Map)FeatureGroupIconLayerMarkerPopupTooltip)TypeJsonValueTypeLineTypePathOptions_parse_sizecamelizeescape_backticks
get_boundsget_obj_in_upper_treeimage_to_url,javascript_identifier_path_to_array_notationnone_maxnone_minparse_optionsvalidate_locations)CircleCircleMarkerPolyLinepath_optionsc                       sp   e Zd ZdZedZdgZ					ddee d	e	d
e	de	de
eedf de
eedf def fddZ  ZS )RegularPolygonMarkera  
    Custom markers using the Leaflet Data Vis Framework.

    Parameters
    ----------
    location: tuple or list
        Latitude and Longitude of Marker (Northing, Easting)
    number_of_sides: int, default 4
        Number of polygon sides
    rotation: int, default 0
        Rotation angle in degrees
    radius: int, default 15
        Marker radius, in pixels
    popup: string or Popup, optional
        Input text or visualization for object displayed when clicking.
    tooltip: str or folium.Tooltip, optional
        Display a text when hovering over the object.
    **kwargs:
        See vector layers path_options for additional arguments.

    https://humangeo.github.io/leaflet-dvf/

    a  
        {% macro script(this, kwargs) %}
            var {{ this.get_name() }} = new L.RegularPolygonMarker(
                {{ this.location|tojson }},
                {{ this.options|tojson }}
            ).addTo({{ this._parent.get_name() }});
        {% endmacro %}
        )dvf_jszShttps://cdnjs.cloudflare.com/ajax/libs/leaflet-dvf/0.3.0/leaflet-dvf.markers.min.js   r      Nlocationnumber_of_sidesrotationradiuspopuptooltipkwargsc                    sF   t  j|||d d| _tdd|d|| _| jt||d d S )N)r8   r9   r0   F)liner7   )r5   r6    )super__init___namer/   optionsupdater*   )selfr4   r5   r6   r7   r8   r9   r:   	__class__r<   [/home/deployuser/azure_apps/autowriter/venv/lib/python3.10/site-packages/folium/features.pyr>   T   s   
zRegularPolygonMarker.__init__)r2   r   r3   NN)__name__
__module____qualname____doc__r   	_template
default_jsr   floatintr
   r   strr   r    r>   __classcell__r<   r<   rC   rE   r0   )   s6    
r0   c                       s   e Zd ZdZedZg dZ					ddedee	e
df d	ee	e
df d
ee	e
f dee	e
f de
f fddZd fddZ  ZS )Vegaa?  
    Creates a Vega chart element.

    Parameters
    ----------
    data: JSON-like str or object
        The Vega description of the chart.
        It can also be any object that has a method `to_json`,
        so that you can (for instance) provide a `vincent` chart.
    width: int or str, default None
        The width of the output element.
        If None, either data['width'] (if available) or '100%' will be used.
        Ex: 120, '120px', '80%'
    height: int or str, default None
        The height of the output element.
        If None, either data['width'] (if available) or '100%' will be used.
        Ex: 120, '120px', '80%'
    left: int or str, default '0%'
        The horizontal distance of the output with respect to the parent
        HTML object. Ex: 120, '120px', '80%'
    top: int or str, default '0%'
        The vertical distance of the output with respect to the parent
        HTML object. Ex: 120, '120px', '80%'
    position: str, default 'relative'
        The `position` argument that the CSS shall contain.
        Ex: 'relative', 'absolute'

     ))d3z9https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js)vegaz=https://cdnjs.cloudflare.com/ajax/libs/vega/1.4.3/vega.min.js)jqueryz+https://code.jquery.com/jquery-3.7.1.min.jsN0%relativedatawidthheightlefttoppositionc                    s   t    d| _t|dr| n|| _t| jtr!t	| j| _t
|d u r-| jddn|| _t
|d u r=| jddn|| _t
|| _t
|| _|| _d S )NrP   to_jsonrX   100%rY   )r=   r>   r?   hasattrr]   rW   
isinstancerN   jsonloadsr!   getrX   rY   rZ   r[   r\   rB   rW   rX   rY   rZ   r[   r\   rC   r<   rE   r>      s   
	


zVega.__init__returnc                    s   t  jdi | t| j| _| jjjtt	dj| |d| 
 d | jjjtt	dj| d| 
 d |  }t|tsDJ d|jjtt	djdd| i|| 
 d |jjt	d	d
d dS )/Renders the HTML representation of the element.>
            <div id="{{this.get_name()}}"></div>
            thisr:   namezH
            vega_parse({{this.json}},{{this.get_name()}});
            ri   8You cannot render this Element if it is not in a Figure.b  
            <style> #{{this.get_name()}} {
                position : {{this.position}};
                width : {{this.width[0]}}{{this.width[1]}};
                height: {{this.height[0]}}{{this.height[1]}};
                left: {{this.left[0]}}{{this.left[1]}};
                top: {{this.top[0]}}{{this.top[1]}};
            </style>
            ri   zqfunction vega_parse(spec, div) {
            vg.parse.spec(spec, function(chart) { chart({el:div}).update(); });}
vega_parseNr<   )r=   renderra   dumpsrW   _parenthtml	add_childr   r   get_namescriptget_rootr`   r   header)rB   r:   figurerC   r<   rE   rp      s`   



zVega.renderNNrU   rU   rV   re   N)rF   rG   rH   rI   r   rJ   rK   r   r
   rM   rN   r>   rp   rO   r<   r<   rC   rE   rP   i   s.    	

rP   c                       s   e Zd ZdZedZ					d dedeee	df deee	df d	eee	f d
eee	f de	f fddZ
d!ddZedee fddZdeddfddZdeddfddZdeddfddZdeddfddZd!ddZdeddfddZ  ZS )"VegaLiteaI  
    Creates a Vega-Lite chart element.

    Parameters
    ----------
    data: JSON-like str or object
        The Vega-Lite description of the chart.
        It can also be any object that has a method `to_json`,
        so that you can (for instance) provide an `Altair` chart.
    width: int or str, default None
        The width of the output element.
        If None, either data['width'] (if available) or '100%' will be used.
        Ex: 120, '120px', '80%'
    height: int or str, default None
        The height of the output element.
        If None, either data['width'] (if available) or '100%' will be used.
        Ex: 120, '120px', '80%'
    left: int or str, default '0%'
        The horizontal distance of the output with respect to the parent
        HTML object. Ex: 120, '120px', '80%'
    top: int or str, default '0%'
        The vertical distance of the output with respect to the parent
        HTML object. Ex: 120, '120px', '80%'
    position: str, default 'relative'
        The `position` argument that the CSS shall contain.
        Ex: 'relative', 'absolute'

    rQ   NrU   rV   rW   rX   rY   rZ   r[   r\   c                    s   t | j|   d| _t|dr| n|| _t| jtr$t	
| j| _t	| j| _	t|d u r7| jddn|| _t|d u rG| jddn|| _t|| _t|| _|| _d S )Nr|   r]   rX   r^   rY   )r=   rD   r>   r?   r_   r]   rW   r`   rN   ra   rb   rq   r!   rc   rX   rY   rZ   r[   r\   rd   rC   r<   rE   r>     s   	


zVegaLite.__init__re   c                 K   s   | j jjttdj| |d|  d |  }t|t	s!J d|j
jttdjd	d| i||  d | j| j| j| j| jd}|| j| j}|| dS )
rf   rg   rh   rj   rm   rn   ri   )         r2      Nr<   )rr   rs   rt   r   r   rp   ru   rw   r`   r   rx   _embed_vegalite_v1_embed_vegalite_v2_embed_vegalite_v3_embed_vegalite_v4_embed_vegalite_v5rc   vegalite_major_version)rB   r:   ry   embed_mappingembed_vegaliter<   r<   rE   rp      sP   


	zVegaLite.renderc                 C   s:   d| j vrd S | j d }t|dd dd dS )Nz$schema/.r   v)rW   rM   splitlstrip)rB   schemar<   r<   rE   r   Q  s   

"zVegaLite.vegalite_major_versionry   c                 C   H   |    |jjtddd |jjtddd |jjtddd d S )N$https://cdn.jsdelivr.net/npm//vega@5rS   rj   z(https://cdn.jsdelivr.net/npm/vega-lite@5	vega-lite)https://cdn.jsdelivr.net/npm/vega-embed@6
vega-embed_vega_embedrx   rt   r   rB   ry   r<   r<   rE   r   Z     
zVegaLite._embed_vegalite_v5c                 C   r   )Nr   rS   rj   z(https://cdn.jsdelivr.net/npm/vega-lite@4r   r   r   r   r   r<   r<   rE   r   h  r   zVegaLite._embed_vegalite_v4c                 C   r   )Nz#https://cdn.jsdelivr.net/npm/vega@4rS   rj   z(https://cdn.jsdelivr.net/npm/vega-lite@3r   )https://cdn.jsdelivr.net/npm/vega-embed@3r   r   r   r<   r<   rE   r   v  r   zVegaLite._embed_vegalite_v3c                 C   r   )Nz#https://cdn.jsdelivr.net/npm/vega@3rS   rj   z(https://cdn.jsdelivr.net/npm/vega-lite@2r   r   r   r   r   r<   r<   rE   r     r   zVegaLite._embed_vegalite_v2c                 C   s*   | j jjttdj| d|  d d S )Nz
                    vegaEmbed({{this.get_name()}}, {{this.json}})
                        .then(function(result) {})
                        .catch(console.error);
                rl   rj   )rr   rv   rt   r   r   rp   ru   rB   r<   r<   rE   r     s   	
zVegaLite._vega_embedc                 C   sz   | j jjttdj| d|  d |jjtddd |jjtddd |jjtdd	d |jjtd
dd d S )Na-  
                    var embedSpec = {
                        mode: "vega-lite",
                        spec: {{this.json}}
                    };
                    vg.embed(
                        {{this.get_name()}}, embedSpec, function(error, result) {}
                    );
                rl   rj   zhttps://d3js.org/d3.v3.min.jsrR   z9https://cdnjs.cloudflare.com/ajax/libs/vega/2.6.5/vega.jsrS   zChttps://cdnjs.cloudflare.com/ajax/libs/vega-lite/1.3.1/vega-lite.jsr   zEhttps://cdnjs.cloudflare.com/ajax/libs/vega-embed/2.2.0/vega-embed.jsr   )	rr   rv   rt   r   r   rp   ru   rx   r   r   r<   r<   rE   r     s:   

zVegaLite._embed_vegalite_v1rz   r{   )rF   rG   rH   rI   r   rJ   r   r
   rM   rN   r>   rp   propertyr   r   r   r   r   r   r   r   r   rO   r<   r<   rC   rE   r|      s<    


1
r|   c                !       s(  e Zd ZdZedZ													d*dedee dee d	e	d
ee
 de	de	de	dee dee
eddf de	ded de	deeeedf def fddZdedefddZde
defddZd+dd Zd!ed
e
ddfd"d#Zde
fd$d%Zdeeee   fd&d'Zd+ fd(d)Z  ZS ),GeoJsona  
    Creates a GeoJson object for plotting into a Map.

    Parameters
    ----------
    data: file, dict or str.
        The GeoJSON data you want to plot.
        * If file, then data will be read in the file and fully
        embedded in Leaflet's JavaScript.
        * If dict, then data will be converted to JSON and embedded
        in the JavaScript.
        * If str, then data will be passed to the JavaScript as-is.
        * If `__geo_interface__` is available, the `__geo_interface__`
        dictionary will be serialized to JSON and
        reprojected if `to_crs` is available.

    style_function: function, default None
        Function mapping a GeoJson Feature to a style dict.
    highlight_function: function, default None
        Function mapping a GeoJson Feature to a style dict for mouse events.
    popup_keep_highlighted: bool, default False
        Whether to keep the highlighting active while the popup is open
    name : string, default None
        The name of the Layer, as it will appear in LayerControls
    overlay : bool, default True
        Adds the layer as an optional overlay (True) or the base layer (False).
    control : bool, default True
        Whether the Layer will be included in LayerControls
    show: bool, default True
        Whether the layer will be shown on opening.
    smooth_factor: float, default None
        How much to simplify the polyline on each zoom level. More means
        better performance and smoother look, and less means more accurate
        representation. Leaflet defaults to 1.0.
    tooltip: GeoJsonTooltip, Tooltip or str, default None
        Display a text when hovering over the object. Can utilize the data,
        see folium.GeoJsonTooltip for info on how to do that.
    popup: GeoJsonPopup, optional
        Show a different popup for each feature by passing a GeoJsonPopup object.
    marker: Circle, CircleMarker or Marker, optional
        If your data contains Point geometry, you can format the markers by passing a Circle,
        CircleMarker or Marker object with your wanted options. The `style_function` and
        `highlight_function` will also target the marker object you passed.
    embed: bool, default True
        Whether to embed the data in the html file or not. Note that disabling
        embedding is only supported if you provide a file link or URL.
    zoom_on_click: bool, default False
        Set to True to enable zooming in on a geometry when clicking on it.
    **kwargs
        Keyword arguments are passed to the geoJson object as extra options.

    Examples
    --------
    >>> # Providing filename that shall be embedded.
    >>> GeoJson("foo.json")
    >>> # Providing filename that shall not be embedded.
    >>> GeoJson("foo.json", embed=False)
    >>> # Providing dict.
    >>> GeoJson(json.load(open("foo.json")))
    >>> # Providing string.
    >>> GeoJson(open("foo.json").read())

    >>> # Provide a style_function that color all states green but Alabama.
    >>> style_function = lambda x: {
    ...     "fillColor": (
    ...         "#0000ff" if x["properties"]["name"] == "Alabama" else "#00ff00"
    ...     )
    ... }
    >>> GeoJson(geojson, style_function=style_function)

    a  
        {% macro script(this, kwargs) %}
        {%- if this.style %}
        function {{ this.get_name() }}_styler(feature) {
            switch({{ this.feature_identifier }}) {
                {%- for style, ids_list in this.style_map.items() if not style == 'default' %}
                {% for id_val in ids_list %}case {{ id_val|tojson }}: {% endfor %}
                    return {{ style }};
                {%- endfor %}
                default:
                    return {{ this.style_map['default'] }};
            }
        }
        {%- endif %}
        {%- if this.highlight %}
        function {{ this.get_name() }}_highlighter(feature) {
            switch({{ this.feature_identifier }}) {
                {%- for style, ids_list in this.highlight_map.items() if not style == 'default' %}
                {% for id_val in ids_list %}case {{ id_val|tojson }}: {% endfor %}
                    return {{ style }};
                {%- endfor %}
                default:
                    return {{ this.highlight_map['default'] }};
            }
        }
        {%- endif %}

        {%- if this.marker %}
        function {{ this.get_name() }}_pointToLayer(feature, latlng) {
            var opts = {{ this.marker.options | tojson | safe }};
            {% if this.marker._name == 'Marker' and this.marker.icon %}
            const iconOptions = {{ this.marker.icon.options | tojson | safe }}
            const iconRootAlias = L{%- if this.marker.icon._name == "Icon" %}.AwesomeMarkers{%- endif %}
            opts.icon = new iconRootAlias.{{ this.marker.icon._name }}(iconOptions)
            {% endif %}
            {%- if this.style_function %}
            let style = {{ this.get_name()}}_styler(feature)
            Object.assign({%- if this.marker.icon -%}opts.icon.options{%- else -%} opts {%- endif -%}, style)
            {% endif %}
            return new L.{{this.marker._name}}(latlng, opts)
        }
        {%- endif %}

        function {{this.get_name()}}_onEachFeature(feature, layer) {
            layer.on({
                {%- if this.highlight %}
                mouseout: function(e) {
                    if(typeof e.target.setStyle === "function"){
                        {%- if this.popup_keep_highlighted %}
                        if (!e.target.isPopupOpen())
                        {%- endif %}
                            {{ this.get_name() }}.resetStyle(e.target);
                    }
                },
                mouseover: function(e) {
                    if(typeof e.target.setStyle === "function"){
                        const highlightStyle = {{ this.get_name() }}_highlighter(e.target.feature)
                        e.target.setStyle(highlightStyle);
                    }
                },
                {%- if this.popup_keep_highlighted %}
                popupopen: function(e) {
                    if(typeof e.target.setStyle === "function"){
                        const highlightStyle = {{ this.get_name() }}_highlighter(e.target.feature)
                        e.target.setStyle(highlightStyle);
                        e.target.bindPopup(e.popup)
                    }
                },
                popupclose: function(e) {
                    if(typeof e.target.setStyle === "function"){
                        {{ this.get_name() }}.resetStyle(e.target);
                        e.target.unbindPopup()
                    }
                },
                {%- endif %}
                {%- endif %}
                {%- if this.zoom_on_click %}
                click: function(e) {
                    if (typeof e.target.getBounds === 'function') {
                        {{ this.parent_map.get_name() }}.fitBounds(e.target.getBounds());
                    }
                    else if (typeof e.target.getLatLng === 'function'){
                        let zoom = {{ this.parent_map.get_name() }}.getZoom()
                        zoom = zoom > 12 ? zoom : zoom + 1
                        {{ this.parent_map.get_name() }}.flyTo(e.target.getLatLng(), zoom)
                    }
                }
                {%- endif %}
            });
        };
        var {{ this.get_name() }} = L.geoJson(null, {
            {%- if this.smooth_factor is not none  %}
                smoothFactor: {{ this.smooth_factor|tojson }},
            {%- endif %}
                onEachFeature: {{ this.get_name() }}_onEachFeature,
            {% if this.style %}
                style: {{ this.get_name() }}_styler,
            {%- endif %}
            {%- if this.marker %}
                pointToLayer: {{ this.get_name() }}_pointToLayer,
            {%- endif %}
            {%- for key, value in this.options.items() %}
                {{ key }}: {{ value|tojson }},
            {%- endfor %}
        });

        function {{ this.get_name() }}_add (data) {
            {{ this.get_name() }}
                .addData(data);
        }
        {%- if this.embed %}
            {{ this.get_name() }}_add({{ this.data|tojson }});
        {%- else %}
            $.ajax({{ this.embed_link|tojson }}, {dataType: 'json', async: false})
                .done({{ this.get_name() }}_add);
        {%- endif %}

        {%- if not this.style %}
        {{this.get_name()}}.setStyle(function(feature) {return feature.properties.style;});
        {%- endif %}

        {% endmacro %}
        NFTrW   style_functionhighlight_functionpopup_keep_highlightedrk   overlaycontrolshowsmooth_factorr9   GeoJsonTooltipembedr8   GeoJsonPopupzoom_on_clickmarkerr:   c                    sX  t  j||||d d| _|| _d | _d | _d | _|	| _|d u| _|d u| _	|| _
|r7t|tttfs7td|rA|d u rAtd|| _|| _tdi || _| || _| js[| j	r|   |d uro| |d || _i | _|d ur| |d || _i | _|  | _t|
tt fr| !|
 n|
d ur| !t |
 t|t"t#fr| !| d S d S )Nrk   r   r   r   r   zLOnly Marker, Circle, and CircleMarker are supported as GeoJson marker types.z;A popup is needed to use the popup_keep_highlighted featurer   r   r<   )$r=   r>   r?   r   
embed_linkra   
parent_mapr   style	highlightr   r`   r,   r-   r   	TypeError
ValueErrorr   r   r*   r@   process_datarW   convert_to_feature_collection_validate_functionr   	style_mapr   highlight_mapfind_identifierfeature_identifierr   r   rt   r   r   )rB   rW   r   r   r   rk   r   r   r   r   r9   r   r8   r   r   r:   rC   r<   rE   r>     sR   


zGeoJson.__init__re   c                 C   s   t |tr
d| _|S t |trT| dr!| js|| _| |S | d dv r1d| _t	
|S | js7|| _t|}t	
| W  d   S 1 sMw   Y  dS t|drod| _t|drf|d}t	
t	|jS td	|)
z8Convert an unknown data input into a geojson dictionary.T)zhttp:zftp:zhttps:r   z[{N__geo_interface__to_crsz	EPSG:4326z3Cannot render objects with any missing geometries: )r`   dictr   rN   lower
startswithr   get_geojson_from_webr   ra   rb   openreadr_   r   rq   r   r   )rB   rW   fr<   r<   rE   r     s0   




$


zGeoJson.process_dataurlc                 C   s   t | S N)requestsrc   ra   )rB   r   r<   r<   rE   r     s   zGeoJson.get_geojson_from_webc                 C   sP   | j d dkr	dS | jstdd| j  vrd| j d| _ d| j gd| _ dS )	z;Convert data into a FeatureCollection if it is not already.typeFeatureCollectionNzData is not a FeatureCollection, but it should be to apply style or highlight. Because `embed=False` it cannot be converted into one.
Either change your geojson data to a FeatureCollection, set `embed=True` or disable styling.geometryFeature)r   r   )r   features)rW   r   r   keysr   r<   r<   rE   r     s   z%GeoJson.convert_to_feature_collectionfuncc                 C   sD   | j d sdS | j d d }t|rt||ts t| ddS )z
        Tests `self.style_function` and `self.highlight_function` to ensure
        they are functions returning dictionaries.
        r   Nr   zX should be a function that accepts items from data['features'] and returns a dictionary.)rW   callabler`   r   r   )rB   r   rk   test_featurer<   r<   rE   r     s   
zGeoJson._validate_functionc                    s   | j d }dd |D }d|vrt|t|krdS tdd |D rD|d d	 D ]  fd
d|D }t|t|krCd    S q)| jrXt|D ]
\}}t||d< qKdS td)a'  Find a unique identifier for each feature, create it if needed.

        According to the GeoJSON specs a feature:
         - MAY have an 'id' field with a string or numerical value.
         - MUST have a 'properties' field. The content can be any json object
           or even null.

        r   c                 S   s   h | ]}| d dqS )idNrc   .0featr<   r<   rE   	<setcomp>  s    z*GeoJson.find_identifier.<locals>.<setcomp>Nz
feature.idc                 s   s"    | ]}t |d dtV  qdS 
propertiesN)r`   rc   r   r   r<   r<   rE   	<genexpr>  s     z*GeoJson.find_identifier.<locals>.<genexpr>r   r   c                    s6   h | ]}t |d   dttfr|d   dqS r   )r`   rc   rN   rM   r   keyr<   rE   r      s    zfeature.properties.r   zThere is no unique identifier for each feature and because `embed=False` it cannot be added. Consider adding an `id` field to your geojson data or set `embed=True`. )rW   lenallr   	enumeraterN   r   )rB   feats
unique_idsunique_valuesifeaturer<   r   rE   r     s&   
	
zGeoJson.find_identifierc                 C   s   t | jddS )z
        Computes the bounds of the object itself (not including it's children)
        in the form [[lat_min, lon_min], [lat_max, lon_max]].

        T)lonlat)r$   rW   r   r<   r<   rE   _get_self_bounds2  s   zGeoJson._get_self_boundsc                    sh   t | t| _| js| jr-| jd r-t| j| j| }| jr#|| j	| _
| jr-|| j| _t   d S )Nr   )r%   r   r   r   r   rW   GeoJsonStyleMapperr   get_style_mapr   r   get_highlight_mapr   r   r=   rp   )rB   r:   mapperrC   r<   rE   rp   :  s   zGeoJson.render)NNFNTTTNNTNFNr{   )rF   rG   rH   rI   r   rJ   r   r   r   boolrN   rL   r
   r   r,   r-   r   r   r>   r   r   r   r   r   r   r   r   rp   rO   r<   r<   rC   rE   r     sr    H 	
@
#r   c                   @   s   e Zd ZdZdededefddZdede	fd	d
Z
dede	fddZdedede	fddZdedeeef fddZededefddZede	ddfddZdS )r   zKCreate dicts that map styling to GeoJson features.

    :meta private:
    rW   r   geojson_objc                 C   s   || _ || _|| _d S r   )rW   r   r   )rB   rW   r   r   r<   r<   rE   r>   O  s   
zGeoJsonStyleMapper.__init__r   re   c                 C      |  |dS )z5Return a dict that maps style parameters to features.r   _create_mapping)rB   r   r<   r<   rE   r   Y     z GeoJsonStyleMapper.get_style_mapr   c                 C   r   )z9Return a dict that maps highlight parameters to features.r   r   )rB   r   r<   r<   rE   r   ]  r   z$GeoJsonStyleMapper.get_highlight_mapr   switchc           	      C   s   i }| j d D ]B}||}|dkr6| D ] \}}t|tr5|jdu r+| j|_|  d|  d ||< q| |}| 	|}|
|g | q| | |S )z(Internal function to create the mapping.r   r   Nz{{'z'}})rW   itemsr`   r   rr   r   rp   ru   _to_keyget_feature_id
setdefaultappend_set_default_key)	rB   r   r   mappingr   contentr   value
feature_idr<   r<   rE   r   a  s    




z"GeoJsonStyleMapper._create_mappingr   c                 C   s:   | j ddd }ttj||}t|ttfsJ |S )z'Return a value identifying the feature.r   r}   N)	r   r   	functoolsreduceoperatorgetitemr`   rN   rM   )rB   r   fieldsr   r<   r<   rE   r   u  s   z!GeoJsonStyleMapper.get_feature_iddc                 C   s"   t j| dd}|ddddS )z6Convert dict to str and enable Jinja2 template syntax.T)	sort_keysz"{{z{{z}}"z}})ra   rq   replace)r   as_strr<   r<   rE   r   |  s   zGeoJsonStyleMapper._to_keyr   Nc                 C   s    t | | jd}|| d< | |= dS )z@Replace the field with the most features with a 'default' field.r   defaultN)maxrc   )r   key_longestr<   r<   rE   r     s   
z#GeoJsonStyleMapper._set_default_key)rF   rG   rH   rI   r   rN   r   r>   r   TypeStyleMappingr   r   r   r
   rM   r   staticmethodr   r   r<   r<   r<   rE   r   I  s"    

r   c                       s   e Zd ZdZedZdgZ							ddedede	e
 d	e	e d
ededede	e deeedf f fddZdddZd fddZdeee  fddZ  ZS )TopoJsona  
    Creates a TopoJson object for plotting into a Map.

    Parameters
    ----------
    data: file, dict or str.
        The TopoJSON data you want to plot.
        * If file, then data will be read in the file and fully
        embedded in Leaflet's JavaScript.
        * If dict, then data will be converted to JSON and embedded
        in the JavaScript.
        * If str, then data will be passed to the JavaScript as-is.

    object_path: str
        The path of the desired object into the TopoJson structure.
        Ex: 'objects.myobject'.
    style_function: function, default None
        A function mapping a TopoJson geometry to a style dict.
    name : string, default None
        The name of the Layer, as it will appear in LayerControls
    overlay : bool, default False
        Adds the layer as an optional overlay (True) or the base layer (False).
    control : bool, default True
        Whether the Layer will be included in LayerControls.
    show: bool, default True
        Whether the layer will be shown on opening.
    smooth_factor: float, default None
        How much to simplify the polyline on each zoom level. More means
        better performance and smoother look, and less means more accurate
        representation. Leaflet defaults to 1.0.
    tooltip: GeoJsonTooltip, Tooltip or str, default None
        Display a text when hovering over the object. Can utilize the data,
        see folium.GeoJsonTooltip for info on how to do that.

    Examples
    --------
    >>> # Providing file that shall be embedded.
    >>> TopoJson(open("foo.json"), "object.myobject")
    >>> # Providing filename that shall not be embedded.
    >>> TopoJson("foo.json", "object.myobject")
    >>> # Providing dict.
    >>> TopoJson(json.load(open("foo.json")), "object.myobject")
    >>> # Providing string.
    >>> TopoJson(open("foo.json").read(), "object.myobject")

    >>> # Provide a style_function that color all states green but Alabama.
    >>> style_function = lambda x: {
    ...     "fillColor": (
    ...         "#0000ff" if x["properties"]["name"] == "Alabama" else "#00ff00"
    ...     )
    ... }
    >>> TopoJson(topo_json, "object.myobject", style_function=style_function)

    a  
        {% macro script(this, kwargs) %}
            var {{ this.get_name() }}_data = {{ this.data|tojson }};
            var {{ this.get_name() }} = L.geoJson(
                topojson.feature(
                    {{ this.get_name() }}_data,
                    {{ this.get_name() }}_data{{ this._safe_object_path }}
                ),
                {
                {%- if this.smooth_factor is not none %}
                    smoothFactor: {{ this.smooth_factor|tojson }},
                {%- endif %}
                }
            ).addTo({{ this._parent.get_name() }});
            {{ this.get_name() }}.setStyle(function(feature) {
                return feature.properties.style;
            });
        {% endmacro %}
        )topojsonzEhttps://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.jsNTrW   object_pathr   rk   r   r   r   r   r9   c
           
         s   t  j||||d d| _dt|v rd| _t|| _nt|t	u r*d| _|| _nd| _|| _|| _
t|| _|p=dd | _|| _t|	ttfrP| |	 d S |	d ur]| t|	 d S d S )Nr   r  r   TFc                 S   s   i S r   r<   xr<   r<   rE   <lambda>  s    z#TopoJson.__init__.<locals>.<lambda>)r=   r>   r?   dirr   ra   loadrW   r   r   r  r'   _safe_object_pathr   r   r`   r   r   rt   )
rB   rW   r  r   rk   r   r   r   r   r9   rC   r<   rE   r>     s*   zTopoJson.__init__re   c                    sR    fdd  | j | jdd }|D ]}|di di | | qdS )z9Applies self.style_function to each feature of self.data.c                    s(   t |r | |d |dd  S | S )Nr   r}   )r   rc   )rW   r   recursive_getr<   rE   r  	  s   z*TopoJson.style_data.<locals>.recursive_getr   
geometriesr   r   N)rW   r  r   r   rA   r   )rB   r  r   r<   r  rE   
style_data  s   zTopoJson.style_datac                    s   |    t jdi | dS )rf   Nr<   )r  r=   rp   rB   r:   rC   r<   rE   rp     s   zTopoJson.renderc           
      C   s  | j stdd\}}}}| jd D ])}d\}}|D ] \}}	||7 }||	7 }t||}t||}t||}t||}qq| jd d d | jd d d |  | jd d d	 | jd d d	 |  g| jd d d | jd d d |  | jd d d	 | jd d d	 |  ggS )
z
        Computes the bounds of the object itself (not including it's children)
        in the form [[lat_min, lon_min], [lat_max, lon_max]]

        z/Cannot compute bounds of non-embedded TopoJSON.)NNNNarcs)r   r   	transform	translater}   scaler   )r   r   rW   r)   r(   )
rB   xminxmaxyminymaxarcr  ydxdyr<   r<   rE   r$     s8   


	zTopoJson.get_bounds)NNTTTNNr{   )rF   rG   rH   rI   r   rJ   rK   r   rN   r   r   r   rL   r
   r   r>   r  rp   r   r$   rO   r<   r<   rC   rE   r    sH    7	

'r  c                       sr   e Zd ZdZdZ					ddee deee  d	ed
edee def fddZ	dddZ
d fddZ  ZS )GeoJsonDetailzHBase class for GeoJsonTooltip and GeoJsonPopup.

    :meta private:
    a  
    function(layer){
    let div = L.DomUtil.create('div');
    {% if this.fields %}
    let handleObject = feature=>typeof(feature)=='object' ? JSON.stringify(feature) : feature;
    let fields = {{ this.fields | tojson | safe }};
    let aliases = {{ this.aliases | tojson | safe }};
    let table = '<table>' +
        String(
        fields.map(
        (v,i)=>
        `<tr>{% if this.labels %}
            <th>${aliases[i]{% if this.localize %}.toLocaleString(){% endif %}}</th>
            {% endif %}
            <td>${handleObject(layer.feature.properties[v]){% if this.localize %}.toLocaleString(){% endif %}}</td>
        </tr>`).join(''))
    +'</table>';
    div.innerHTML=table;
    {% endif %}
    return div
    }
    NTFgeojsondetailr   aliaseslabelslocalizer   
class_namec                    s   t    t|ttfsJ d|d ur)t|ttfsJ t|t|ks)J dt|ts2J dt|ts;J dd| _|| _|d urG|n|| _	|| _
|| _|| _|rct|ts^J d|| _d S d S )Nz&Please pass a list or tuple to fields.z-fields and aliases must have the same length.z labels requires a boolean value.zlocalize must be bool.r  z8Pass a valid inline HTML style property string to style.)r=   r>   r`   listtupler   r   r?   r   r   r!  r"  r#  rN   r   )rB   r   r   r!  r"  r   r#  rC   r<   rE   r>   ]  s:   
	
zGeoJsonDetail.__init__re   c                 C   sD   dd t | jjd D }t|r t| j d| dt dS dS )zRChecks for GeoJson GeometryCollection features to warn user about incompatibility.c                 S   sD   g | ]\}}|d  r |d  d dkr| ddur| dn|qS )r   r   GeometryCollectionr   Nr   )r   r   r   r<   r<   rE   
<listcomp>  s    z?GeoJsonDetail.warn_for_geometry_collections.<locals>.<listcomp>r   zr is not configured to render for GeoJson GeometryCollection geometries. Please consider reworking these features: zS to MultiPolygon for full functionality.
https://tools.ietf.org/html/rfc7946#page-9N)r   rr   rW   anywarningswarnr?   UserWarning)rB   geom_collectionsr<   r<   rE   warn_for_geometry_collections~  s   z+GeoJsonDetail.warn_for_geometry_collectionsc                    s  |   }t| jtr%t| jjd r| jjd d d  ng }|   n+t| jtrG| jj	
dd }t| jjd | d d d  }n	td| j d	td
d |D }| jD ]}||v smJ d| d| dq\|jjttdj| d|  d d t   dS )rf   r   r   r   r   r   objectsr  zYou cannot add a z5 to anything other than a GeoJson or TopoJson object.c                 s   s    | ]	}|d vr|V  qdS ))r   r   Nr<   )r   r  r<   r<   rE   r     s    z'GeoJsonDetail.render.<locals>.<genexpr>z
The field z, is not available in the data. Choose from: a=  
                    <style>
                        .{{ this.class_name }} {
                            {{ this.style }}
                        }
                       .{{ this.class_name }} table{
                            margin: auto;
                        }
                        .{{ this.class_name }} tr{
                            text-align: left;
                        }
                        .{{ this.class_name }} th{
                            padding: 2px; padding-right: 8px;
                        }
                    </style>
            rl   
tablestylerj   N)rw   r`   rr   r   r%  rW   r   r-  r  r  r   r   r?   r   rx   rt   r   r   rp   ru   r=   )rB   r:   ry   r   obj_namer   rC   r<   rE   rp     sF   




zGeoJsonDetail.render)NTFNr  r{   )rF   rG   rH   rI   base_templater   rN   r   r   r>   r-  rp   rO   r<   r<   rC   rE   r  @  s.    

!r  c                       sr   e Zd ZdZedej d Z						ddee	 d	e
ee	  d
edede
e	 de	dedef fddZ  ZS )r   aK  
    Create a tooltip that uses data from either geojson or topojson.

    Parameters
    ----------
    fields: list or tuple.
        Labels of GeoJson/TopoJson 'properties' or GeoPandas GeoDataFrame
        columns you'd like to display.
    aliases: list/tuple of strings, same length/order as fields, default None.
        Optional aliases you'd like to display in the tooltip as field name
        instead of the keys of `fields`.
    labels: bool, default True.
        Set to False to disable displaying the field names or aliases.
    localize: bool, default False.
        This will use JavaScript's .toLocaleString() to format 'clean' values
        as strings for the user's location; i.e. 1,000,000.00 comma separators,
        float truncation, etc.
        Available for most of JavaScript's primitive types (any data you'll
        serve into the template).
    style: str, default None.
        HTML inline style properties like font and colors. Will be applied to
        a div with the text in it.
    sticky: bool, default True
        Whether the tooltip should follow the mouse.
    **kwargs: Assorted.
        These values will map directly to the Leaflet Options. More info
        available here: https://leafletjs.com/reference.html#tooltip

    Examples
    --------
    # Provide fields and aliases, with Style.
    >>> GeoJsonTooltip(
    ...     fields=["CNTY_NM", "census-pop-2015", "census-md-income-2015"],
    ...     aliases=["County", "2015 Census Population", "2015 Median Income"],
    ...     localize=True,
    ...     style=(
    ...         "background-color: grey; color: white; font-family:"
    ...         "courier new; font-size: 24px; padding: 10px;"
    ...     ),
    ... )
    # Provide fields, with labels off and fixed tooltip positions.
    >>> GeoJsonTooltip(fields=("CNTY_NM",), labels=False, sticky=False)
    zT
    {% macro script(this, kwargs) %}
    {{ this._parent.get_name() }}.bindTooltip(zg,{{ this.tooltip_options | tojson | safe }});
                     {% endmacro %}
                     NTFfoliumtooltipr   r   r!  r"  r   r#  stickyr:   c           	         sJ   t  j||||||d d| _ ||d  fdd  D | _d S )N)r   r   r!  r"  r   r#  r   )r3  r#  c                    s   i | ]	}t | | qS r<   r"   )r   r   r:   r<   rE   
<dictcomp>      z+GeoJsonTooltip.__init__.<locals>.<dictcomp>)r=   r>   r?   rA   r   tooltip_options)	rB   r   r   r!  r"  r   r#  r3  r:   rC   r5  rE   r>     s   zGeoJsonTooltip.__init__)NTFNr2  TrF   rG   rH   rI   r   r  r1  rJ   r   rN   r   r   r   r>   rO   r<   r<   rC   rE   r     s@    ,
	r   c                       sh   e Zd ZdZedej d Z					ddee	 d	e
ee	  d
ede	de	dedef fddZ  ZS )r   a  
    Create a popup feature to bind to each element of a GeoJson layer based on
    its attributes.

    Parameters
    ----------
    fields: list or tuple.
        Labels of GeoJson/TopoJson 'properties' or GeoPandas GeoDataFrame
        columns you'd like to display.
    aliases: list/tuple of strings, same length/order as fields, default None.
        Optional aliases you'd like to display in the tooltip as field name
        instead of the keys of `fields`.
    labels: bool, default True.
        Set to False to disable displaying the field names or aliases.
    localize: bool, default False.
        This will use JavaScript's .toLocaleString() to format 'clean' values
        as strings for the user's location; i.e. 1,000,000.00 comma separators,
        float truncation, etc.
        Available for most of JavaScript's primitive types (any data you'll
        serve into the template).
    style: str, default None.
        HTML inline style properties like font and colors. Will be applied to
        a div with the text in it.

    Examples
    ---
    gjson = folium.GeoJson(gdf).add_to(m)

    folium.features.GeoJsonPopup(fields=['NAME'],
                                labels=False
                                ).add_to(gjson)
    zR
    {% macro script(this, kwargs) %}
    {{ this._parent.get_name() }}.bindPopup(ze,{{ this.popup_options | tojson | safe }});
                     {% endmacro %}
                     NTmargin: auto;foliumpopupr   r   r!  r   r#  r"  r:   c                    sF   t  j||||||d d| _|d| ji dd | D | _d S )N)r   r   r!  r"  r#  r   r   r#  c                 S   s   i | ]	\}}t ||qS r<   r4  )r   r   r   r<   r<   rE   r6  S  r7  z)GeoJsonPopup.__init__.<locals>.<dictcomp>)r=   r>   r?   rA   r#  r   popup_options)rB   r   r   r!  r   r#  r"  r:   rC   r<   rE   r>   ?  s   
zGeoJsonPopup.__init__)NTr:  r;  Tr9  r<   r<   rC   rE   r     s:    !
r   c                +       s
  e Zd ZdZ																						d(d
edee deee  dee dee	ee
 f dee dede
dee
 dede
de
dee dededededee dee
 dedef* fdd Zed!eeef d"ed#ee
edf fd$d%Zd) fd&d'Z  ZS )*
Choropletha\  Apply a GeoJSON overlay to the map.

    Plot a GeoJSON overlay on the base map. There is no requirement
    to bind data (passing just a GeoJSON plots a single-color overlay),
    but there is a data binding option to map your columnar data to
    different feature objects with a color scale.

    If data is passed as a Pandas DataFrame, the "columns" and "key-on"
    keywords must be included, the first to indicate which DataFrame
    columns to use, the second to indicate the layer in the GeoJSON
    on which to key the data. The 'columns' keyword does not need to be
    passed for a Pandas series.

    Colors are generated from color brewer (https://colorbrewer2.org/)
    sequential palettes. By default, linear binning is used between
    the min and the max of the values. Custom binning can be achieved
    with the `bins` parameter.

    TopoJSONs can be passed as "geo_data", but the "topojson" keyword must
    also be passed with the reference to the topojson objects to convert.
    See the topojson.feature method in the TopoJSON API reference:
    https://github.com/topojson/topojson/wiki/API-Reference


    Parameters
    ----------
    geo_data: string/object
        URL, file path, or data (json, dict, geopandas, etc) to your GeoJSON
        geometries
    data: Pandas DataFrame or Series, default None
        Data to bind to the GeoJSON.
    columns: tuple with two values, default None
        If the data is a Pandas DataFrame, the columns of data to be bound.
        Must pass column 1 as the key, and column 2 the values.
    key_on: string, default None
        Variable in the `geo_data` GeoJSON file to bind the data to. Must
        start with 'feature' and be in JavaScript objection notation.
        Ex: 'feature.id' or 'feature.properties.statename'.
    bins: int or sequence of scalars or str, default 6
        If `bins` is an int, it defines the number of equal-width
        bins between the min and the max of the values.
        If `bins` is a sequence, it directly defines the bin edges.
        For more information on this parameter, have a look at
        numpy.histogram function.
    fill_color: string, optional
        Area fill color, defaults to blue. Can pass a hex code, color name,
        or if you are binding data, one of the following color brewer palettes:
        'BuGn', 'BuPu', 'GnBu', 'OrRd', 'PuBu', 'PuBuGn', 'PuRd', 'RdPu',
        'YlGn', 'YlGnBu', 'YlOrBr', and 'YlOrRd'.
    nan_fill_color: string, default 'black'
        Area fill color for nan or missing values.
        Can pass a hex code, color name.
    fill_opacity: float, default 0.6
        Area fill opacity, range 0-1.
    nan_fill_opacity: float, default fill_opacity
        Area fill opacity for nan or missing values, range 0-1.
    line_color: string, default 'black'
        GeoJSON geopath line color.
    line_weight: int, default 1
        GeoJSON geopath line weight.
    line_opacity: float, default 1
        GeoJSON geopath line opacity, range 0-1.
    legend_name: string, default empty string
        Title for data legend.
    topojson: string, default None
        If using a TopoJSON, passing "objects.yourfeature" to the topojson
        keyword argument will enable conversion to GeoJSON.
    smooth_factor: float, default None
        How much to simplify the polyline on each zoom level. More means
        better performance and smoother look, and less means more accurate
        representation. Leaflet defaults to 1.0.
    highlight: boolean, default False
        Enable highlight functionality when hovering over a GeoJSON area.
    use_jenks: bool, default False
        Use jenkspy to calculate bins using "natural breaks"
        (Fisher-Jenks algorithm). This is useful when your data is unevenly
        distributed.
    name : string, optional
        The name of the layer, as it will appear in LayerControls
    overlay : bool, default True
        Adds the layer as an optional overlay (True) or the base layer (False).
    control : bool, default True
        Whether the Layer will be included in LayerControls.
    show: bool, default True
        Whether the layer will be shown on opening.

    Returns
    -------
    GeoJSON data layer in obj.template_vars

    Examples
    --------
    >>> Choropleth(geo_data="us-states.json", line_color="blue", line_weight=3)
    >>> Choropleth(
    ...     geo_data="geo.json",
    ...     data=df,
    ...     columns=["Data 1", "Data 2"],
    ...     key_on="feature.properties.myvalue",
    ...     fill_color="PuBu",
    ...     bins=[0, 20, 30, 40, 50, 60],
    ... )
    >>> Choropleth(geo_data="countries.json", topojson="objects.countries")
    >>> Choropleth(
    ...     geo_data="geo.json",
    ...     data=df,
    ...     columns=["Data 1", "Data 2"],
    ...     key_on="feature.properties.myvalue",
    ...     fill_color="PuBu",
    ...     bins=[0, 20, 30, 40, 50, 60],
    ...     highlight=True,
    ... )
    N   black333333?r}   rQ   TFgeo_datarW   columnskey_onbins
fill_colornan_fill_colorfill_opacitynan_fill_opacity
line_colorline_weightline_opacityrk   legend_namer   r   r   r  r   r   	use_jenksc                     s  t  j||||d d_p|d u rdnd|d ur#ts#tdd u r)d|v r=|d d ur7|d }tdt t|drV|d usHJ |	|d	 |d
  
 nt|dr`|
 n	|rgt|nd d _d urd urtt }|t|  }|rd	dlm} t|tstd| dtj|||td n	tj||d\} t t }}t||k ||kB rtdt d
 }t|dt |||d_ d	  d k} t t d |rd
ndtj  d<  drdd  n 
fddnfdd	fdd}	fdd}|r<t!||||d_"nt#||||rE|nd d_"$j" jr\$j d S d S ) Nr   r=  blueBlueszSPlease pass a valid color brewer code to fill_local. See docstring for valid codes.threshold_scalez[choropleth `threshold_scale` parameter is now depreciated in favor of the `bins` parameter.	set_indexr   r}   to_dict)jenks_breaksz?bins value must be an integer when using Jenks. Invalid value "z" received.)dtype)rD  zAll values are expected to fall into one of the provided bins (or to be Nan). Please check the `bins` parameter and/or your data.)n)indexvminvmaxcaptionr   zfeature.   c                    s    | }|d u rtddz| }W n< tyT   z!t|tr,t| }nt|tr8t| }nfW  Y S W n ttfyQ   f Y  Y S w Y nw t|r^fS tj| ddd }| fS )Nzkey_on `z` not found in GeoJSON.F)rightr}   )	_get_by_keyr   KeyErrorr`   rM   rN   npisnandigitize)r  key_of_x
value_of_x	color_idx)	bin_edges
color_datacolor_rangerG  rC  rF  rH  rB   r<   rE   color_scale_fun3  s,   


z,Choropleth.__init__.<locals>.color_scale_func                    s    fS r   r<   r  )rE  rG  r<   rE   rg  N  s   c                    s    | \}}||dS )N)weightopacitycolorfillOpacity	fillColorr<   )r  rj  ri  )rg  rI  rK  rJ  r<   rE   r   Q  s   z+Choropleth.__init__.<locals>.style_functionc                    s   d  d dS )Nr~   g?)rh  rk  r<   r  )rG  rJ  r<   rE   r   [  s   z/Choropleth.__init__.<locals>.highlight_function)r   r   )r   r   r   )%r=   r>   r?   r   r   r)  r*  DeprecationWarningr_   rQ  rR  r   color_scaler^  arrayr$  valuesr_  jenkspyrS  r`   rM   rL   	histogramminr   r(  r   r   astype	nextafterinfr   r  geojsonr   rt   ) rB   rA  rW   rB  rC  rD  rE  rF  rG  rH  rI  rJ  rK  rk   rL  r   r   r   r  r   r   rM  r:   real_valuesrS  _bins_minbins_maxnb_bins
increasingr   r   rC   )rd  re  rf  rg  rE  rG  rC  rI  rK  rJ  rF  rH  rB   rE   r>     s   








zChoropleth.__init__objr   re   c                 C   sb   | d}|d }| r|t| }n||d }t|dkr/d|dd  }| ||S |S )Nr   r   r}   )r   isdigitrM   rc   r   joinr\  )clsr~  r   	key_partsfirst_key_partr   new_keyr<   r<   rE   r\  q  s   
zChoropleth._get_by_keyc                    s:   | j rt| jtsJ d| j| j _t jdi | dS )z4Render the GeoJson/TopoJson and color scale objects.z)Choropleth must be added to a Map object.Nr<   )rn  r`   rr   r   r=   rp   r  rC   r<   rE   rp     s   
zChoropleth.render)NNNr>  Nr?  r@  Nr?  r}   r}   NrQ   TTTNNFFr{   )rF   rG   rH   rI   r   r   r   rN   r
   rM   rL   r   r>   classmethodr   r$  r\  rp   rO   r<   r<   rC   rE   r=  V  s    t
	
 **r=  c                       sr   e Zd ZdZedZ					ddee deee	e	f  deee	e	f  deee	e	f  d	ef
 fd
dZ
  ZS )DivIcona  
    Represents a lightweight icon for markers that uses a simple `div`
    element instead of an image.

    Parameters
    ----------
    icon_size : tuple of 2 int
        Size of the icon image in pixels.
    icon_anchor : tuple of 2 int
        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.
    popup_anchor : tuple of 2 int
        The coordinates of the point from which popups will "open",
        relative to the icon anchor.
    class_name : string
        A custom class name to assign to the icon.
        Leaflet defaults is 'leaflet-div-icon' which draws a little white
        square with a shadow.  We set it 'empty' in folium.
    html : string
        A custom HTML code to put inside the div element.

    See https://leafletjs.com/reference.html#divicon

    z
        {% macro script(this, kwargs) %}
            var {{ this.get_name() }} = L.divIcon({{ this.options|tojson }});
            {{this._parent.get_name()}}.setIcon({{this.get_name()}});
        {% endmacro %}
        Nemptyrs   	icon_sizeicon_anchorpopup_anchorr#  c                    s(   t    d| _t|||||d| _d S )Nr  )rs   r  r  r  r#  )r=   r>   r?   r*   r@   )rB   rs   r  r  r  r#  rC   r<   rE   r>     s   
zDivIcon.__init__)NNNNr  )rF   rG   rH   rI   r   rJ   r   rN   r	   rM   r>   rO   r<   r<   rC   rE   r    s*    r  c                       s(   e Zd ZdZedZ fddZ  ZS )LatLngPopupz
    When one clicks on a Map that contains a LatLngPopup,
    a popup is shown that displays the latitude and longitude of the pointer.

    a=  
            {% macro script(this, kwargs) %}
                var {{this.get_name()}} = L.popup();
                function latLngPop(e) {
                    {{this.get_name()}}
                        .setLatLng(e.latlng)
                        .setContent("Latitude: " + e.latlng.lat.toFixed(4) +
                                    "<br>Longitude: " + e.latlng.lng.toFixed(4))
                        .openOn({{this._parent.get_name()}});
                    }
                {{this._parent.get_name()}}.on('click', latLngPop);
            {% endmacro %}
            c                    s   t    d| _d S )Nr  )r=   r>   r?   r   rC   r<   rE   r>     s   

zLatLngPopup.__init__)rF   rG   rH   rI   r   rJ   r>   rO   r<   r<   rC   rE   r    s    r  c                       s<   e Zd ZdZedZddeeee	df f fddZ
  ZS )ClickForMarkera'  
    When one clicks on a Map that contains a ClickForMarker,
    a Marker is created at the pointer's position.

    Parameters
    ----------
    popup: str or IFrame or Html, default None
        Text to display in the markers' popups.
        This can also be an Element like IFrame or Html.
        If None, the popups will display the marker's latitude and longitude.
        You can include the latitude and longitude with ${lat} and ${lng}.


    Examples
    --------
    >>> ClickForMarker("<b>Lat:</b> ${lat}<br /><b>Lon:</b> ${lng}")

    a  
            {% macro script(this, kwargs) %}
                function newMarker(e){
                    var new_mark = L.marker().setLatLng(e.latlng).addTo({{this._parent.get_name()}});
                    new_mark.dragging.enable();
                    new_mark.on('dblclick', function(e){ {{this._parent.get_name()}}.removeLayer(e.target)})
                    var lat = e.latlng.lat.toFixed(4),
                       lng = e.latlng.lng.toFixed(4);
                    new_mark.bindPopup({{ this.popup }});
                    };
                {{this._parent.get_name()}}.on('click', newMarker);
            {% endmacro %}
            Nr8   c                    sF   t    d| _t|tr| }|rdt| d | _d S d| _d S )Nr  `z-"Latitude: " + lat + "<br>Longitude: " + lng )r=   r>   r?   r`   r   rp   r#   r8   )rB   r8   rC   r<   rE   r>     s   


zClickForMarker.__init__r   )rF   rG   rH   rI   r   rJ   r
   r   r   rN   r>   rO   r<   r<   rC   rE   r    s    (r  c                       s8   e Zd ZdZedZd	dee def fddZ	  Z
S )
ClickForLatLnga:  
    When one clicks on a Map that contains a ClickForLatLng,
    the coordinates of the pointer's position are copied to clipboard.

    Parameters
    ==========
    format_str : str, default 'lat + "," + lng'
        The javascript string used to format the text copied to clipboard.
        eg:
        format_str = 'lat + "," + lng'              >> 46.558860,3.397397
        format_str = '"[" + lat + "," + lng + "]"'  >> [46.558860,3.397397]
    alert : bool, default True
        Whether there should be an alert when something has been copied to clipboard.
    a  
            {% macro script(this, kwargs) %}
                function getLatLng(e){
                    var lat = e.latlng.lat.toFixed(6),
                        lng = e.latlng.lng.toFixed(6);
                    var txt = {{this.format_str}};
                    navigator.clipboard.writeText(txt);
                    {% if this.alert %}alert("Copied to clipboard : \n    " + txt);{% endif %}
                    };
                {{this._parent.get_name()}}.on('click', getLatLng);
            {% endmacro %}
            NT
format_stralertc                    s$   t    d| _|pd| _|| _d S )Nr  zlat + "," + lng)r=   r>   r?   r  r  )rB   r  r  rC   r<   rE   r>   .  s   


zClickForLatLng.__init__)NT)rF   rG   rH   rI   r   rJ   r   rN   r   r>   rO   r<   r<   rC   rE   r    s    $r  c                       s   e Zd ZdZedZ						ddedeee	e	f  deee	e	f  dedeee	e	f  d	eee	e	f  d
eee	e	f  f fddZ
  ZS )
CustomIcona<  
    Create a custom icon, based on an image.

    Parameters
    ----------
    icon_image :  string, file or array-like object
        The data you want to use as an icon.
        * If string, it will be written directly in the output file.
        * If file, it's content will be converted as embedded in the
        output file.
        * If array-like, it will be converted to PNG base64 string
        and embedded in the output.

    icon_size : tuple of 2 int, optional
        Size of the icon image in pixels.
    icon_anchor : tuple of 2 int, optional
        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.
    shadow_image :  string, file or array-like object, optional
        The data for the shadow image. If not specified,
        no shadow image will be created.
    shadow_size : tuple of 2 int, optional
        Size of the shadow image in pixels.
    shadow_anchor : tuple of 2 int, optional
        The coordinates of the "tip" of the shadow relative to its
        top left corner (the same as icon_anchor if not specified).
    popup_anchor : tuple of 2 int, optional
        The coordinates of the point from which popups will "open",
        relative to the icon anchor.

    z
        {% macro script(this, kwargs) %}
        var {{ this.get_name() }} = L.icon({{ this.options|tojson }});
        {{ this._parent.get_name() }}.setIcon({{ this.get_name() }});
        {% endmacro %}
        N
icon_imager  r  shadow_imageshadow_sizeshadow_anchorr  c              	      s<   t t|   d| _tt||||ot||||d| _d S )Nr  )icon_urlr  r  
shadow_urlr  r  r  )r=   r   r>   r?   r*   r&   r@   )rB   r  r  r  r  r  r  r  rC   r<   rE   r>   a  s   

zCustomIcon.__init__)NNNNNN)rF   rG   rH   rI   r   rJ   r   r   r	   rM   r>   rO   r<   r<   rC   rE   r  5  s4    "r  c                       sb   e Zd ZdZ				ddedee deee	e
 df dedee d	ee d
e
f fddZ  ZS )	ColorLinea  
    Draw data on a map with specified colors.

    Parameters
    ----------
    positions: iterable of (lat, lon) pairs
        The points on the line. Segments between points will be colored.
    colors: iterable of float
        Values that determine the color of a line segment.
        It must have length equal to `len(positions)-1`.
    colormap: branca.colormap.Colormap or list or tuple
        The colormap to use. If a list or tuple of colors is provided,
        a LinearColormap will be created from it.
    nb_steps: int, default 12
        The colormap will be discretized to this number of colors.
    opacity: float, default 1
        Line opacity, scale 0-1
    weight: int, default 2
        Stroke weight in pixels
    **kwargs
        Further parameters available. See folium.map.FeatureGroup

    Returns
    -------
    A ColorLine object that you can `add_to` a Map.

    N   	positionscolorscolormapnb_stepsrh  ri  r:   c              	      s  t  jdi | d| _t|}|d u r%tg dt|t|d|}	n&t|tr0||}	nt|t	s:t|t
rIt|t|t|d|}	n|}	i }
t|d d |dd  |D ]\\}}\}}}|
|	|g ||g||gg q[|
 D ]\}}| t||||d qzd S )Nr  )greenyellowred)rW  rX  r   r}   )rj  rh  ri  r<   )r=   r>   r?   r+   r   rs  r   to_stepr`   r$  r%  zipr   r   r   rt   r.   )rB   r  r  r  r  rh  ri  r:   coordscmoutlat1lng1lat2lng2rj  r   valrC   r<   rE   r>     s8   

.$zColorLine.__init__)Nr  NN)rF   rG   rH   rI   r   r   rL   r
   r   r   r   rM   r   r>   rO   r<   r<   rC   rE   r  x  s*     r  )SrI   r   ra   r   r)  typingr   r   r   r   r   r   r   r	   r
   numpyr^  r   branca.colormapr   r   r   branca.elementr   r   r   r   r   r   branca.utilitiesr   jinja2r   folium.elementsr   folium.foliumr   
folium.mapr   r   r   r   r   r   folium.utilitiesr   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   folium.vector_layersr,   r-   r.   r/   r0   rP   r|   r   rN   rM   r  r   r  r  r   r   r=  r  r  r  r  r  r  r<   r<   r<   rE   <module>   sT    ,  @@{ d    A 7 OC  780&C