Example #1
0
    def __init__(self,
                 html=None,
                 parse_html=False,
                 max_width='100%',
                 show=False,
                 sticky=False):
        super(Popup, self).__init__()
        self._name = 'Popup'
        self.header = Element()
        self.html = Element()
        self.script = Element()

        self.header._parent = self
        self.html._parent = self
        self.script._parent = self

        script = not parse_html

        if isinstance(html, Element):
            self.html.add_child(html)
        elif isinstance(html, text_type) or isinstance(html, binary_type):
            self.html.add_child(Html(text_type(html), script=script))

        self.max_width = max_width
        self.show = show
        self.sticky = sticky
Example #2
0
    def __init__(self,
                 html=None,
                 parse_html=False,
                 max_width='100%',
                 show=False,
                 sticky=False,
                 **kwargs):
        super(Popup, self).__init__()
        self._name = 'Popup'
        self.header = Element()
        self.html = Element()
        self.script = Element()

        self.header._parent = self
        self.html._parent = self
        self.script._parent = self

        script = not parse_html

        if isinstance(html, Element):
            self.html.add_child(html)
        elif isinstance(html, str):
            self.html.add_child(Html(html, script=script))

        self.show = show
        self.options = parse_options(
            max_width=max_width,
            autoClose=False if show or sticky else None,
            closeOnClick=False if sticky else None,
            **kwargs)
Example #3
0
    def render(self, **kwargs):
        super(Draw, self).render()

        figure = self.get_root()
        assert isinstance(figure, Figure), ('You cannot render this Element '
                                            'if it is not in a Figure.')

        figure.header.add_child(
            JavascriptLink('https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.2/leaflet.draw.js'))
        figure.header.add_child(
            CssLink('https://raw.githubusercontent.com/Leaflet/Leaflet.draw/v1.0.2/src/leaflet.draw.css'))

        export_style = """<style>
        #export {
        position: absolute;
        top: 5px;
        right: 10px;
        z-index: 999;
        background: white;
        color: black;
        padding: 6px;
        border-radius: 4px;
        font-family: 'Helvetica Neue';
        cursor: pointer;
        font-size: 18px;
        text-decoration: none;
        top: 50px;
        }
        </style>"""
        export_button = """<a href='#' id='export'>Export-t</a>"""
        if self.export:
            figure.header.add_child(Element(export_style), name='export')
            figure.html.add_child(Element(export_button), name='export_button')
Example #4
0
    def render(self, **kwargs):
        """Renders the HTML representation of the element."""
        figure = self.get_root()
        assert isinstance(figure, Figure), ("You cannot render this Element "
                                            "if it's not in a Figure.")

        # Import Javascripts
        for name, url in _default_js:
            figure.header.add_children(JavascriptLink(url), name=name)

        # Import Css
        for name, url in _default_css:
            figure.header.add_children(CssLink(url), name=name)

        figure.header.add_children(Element(
            '<style>html, body {'
            'width: 100%;'
            'height: 100%;'
            'margin: 0;'
            'padding: 0;'
            '}'
            '</style>'), name='css_style')

        figure.header.add_children(Element(
            '<style>#map {'
            'position:absolute;'
            'top:0;'
            'bottom:0;'
            'right:0;'
            'left:0;'
            '}'
            '</style>'), name='map_style')

        super(LegacyMap, self).render(**kwargs)
Example #5
0
File: map.py Project: pmains/folium
    def __init__(self, html=None, parse_html=False, max_width=300):
        super(Popup, self).__init__()
        self._name = 'Popup'
        self.header = Element()
        self.html = Element()
        self.script = Element()

        self.header._parent = self
        self.html._parent = self
        self.script._parent = self

        script = not parse_html

        if isinstance(html, Element):
            self.html.add_child(html)
        elif isinstance(html, text_type) or isinstance(html, binary_type):
            self.html.add_child(Html(text_type(html), script=script))

        self.max_width = max_width

        self._template = Template(u"""
            var {{this.get_name()}} = L.popup({maxWidth: '{{this.max_width}}'});

            {% for name, element in this.html._children.items() %}
                var {{name}} = $('{{element.render(**kwargs).replace('\\n',' ')}}')[0];
                {{this.get_name()}}.setContent({{name}});
            {% endfor %}

            {{this._parent.get_name()}}.bindPopup({{this.get_name()}});

            {% for name, element in this.script._children.items() %}
                {{element.render()}}
            {% endfor %}
        """)  # noqa
Example #6
0
    def render(self, **kwargs):
        """Renders the HTML representation of the element."""
        figure = self.get_root()
        assert isinstance(figure, Figure), ('You cannot render this Element '
                                            'if it is not in a Figure.')

        # Set global switches
        figure.header.add_child(self.global_switches, name='global_switches')

        figure.header.add_child(Element('<style>html, body {'
                                        'width: 100%;'
                                        'height: 100%;'
                                        'margin: 0;'
                                        'padding: 0;'
                                        '}'
                                        '</style>'),
                                name='css_style')

        figure.header.add_child(Element('<style>#map {'
                                        'position:absolute;'
                                        'top:0;'
                                        'bottom:0;'
                                        'right:0;'
                                        'left:0;'
                                        '}'
                                        '</style>'),
                                name='map_style')

        super(Map, self).render(**kwargs)
Example #7
0
    def render(self, **kwargs):
        super(Draw, self).render(**kwargs)

        figure = self.get_root()
        assert isinstance(figure, Figure), ('You cannot render this Element '
                                            'if it is not in a Figure.')

        export_style = """
            <style>
                #export {
                    position: absolute;
                    top: 5px;
                    right: 10px;
                    z-index: 999;
                    background: white;
                    color: black;
                    padding: 6px;
                    border-radius: 4px;
                    font-family: 'Helvetica Neue';
                    cursor: pointer;
                    font-size: 12px;
                    text-decoration: none;
                    top: 90px;
                }
            </style>
        """
        export_button = """<a href='#' id='export'>Export</a>"""
        if self.export:
            figure.header.add_child(Element(export_style), name='export')
            figure.html.add_child(Element(export_button), name='export_button')
Example #8
0
File: map.py Project: pmains/folium
class Popup(Element):
    """Create a Popup instance that can be linked to a Layer.

    Parameters
    ----------
    html: string or Element
        Content of the Popup.
    parse_html: bool, default False
        True if the popup is a template that needs to the rendered first.
    max_width: int, default 300
        The maximal width of the popup.
    """
    def __init__(self, html=None, parse_html=False, max_width=300):
        super(Popup, self).__init__()
        self._name = 'Popup'
        self.header = Element()
        self.html = Element()
        self.script = Element()

        self.header._parent = self
        self.html._parent = self
        self.script._parent = self

        script = not parse_html

        if isinstance(html, Element):
            self.html.add_child(html)
        elif isinstance(html, text_type) or isinstance(html, binary_type):
            self.html.add_child(Html(text_type(html), script=script))

        self.max_width = max_width

        self._template = Template(u"""
            var {{this.get_name()}} = L.popup({maxWidth: '{{this.max_width}}'});

            {% for name, element in this.html._children.items() %}
                var {{name}} = $('{{element.render(**kwargs).replace('\\n',' ')}}')[0];
                {{this.get_name()}}.setContent({{name}});
            {% endfor %}

            {{this._parent.get_name()}}.bindPopup({{this.get_name()}});

            {% for name, element in this.script._children.items() %}
                {{element.render()}}
            {% endfor %}
        """)  # noqa

    def render(self, **kwargs):
        """Renders the HTML representation of the element."""
        for name, child in self._children.items():
            child.render(**kwargs)

        figure = self.get_root()
        assert isinstance(figure, Figure), ('You cannot render this Element '
                                            'if it is not in a Figure.')

        figure.script.add_child(Element(
            self._template.render(this=self, kwargs=kwargs)),
                                name=self.get_name())
Example #9
0
class Popup(Element):
    """Create a Popup instance that can be linked to a Layer.

    Parameters
    ----------
    html: string or Element
        Content of the Popup.
    parse_html: bool, default False
        True if the popup is a template that needs to the rendered first.
    max_width: int, default 300
        The maximal width of the popup.
    """
    def __init__(self, html=None, parse_html=False, max_width=300):
        super(Popup, self).__init__()
        self._name = 'Popup'
        self.header = Element()
        self.html = Element()
        self.script = Element()

        self.header._parent = self
        self.html._parent = self
        self.script._parent = self

        script = not parse_html

        if isinstance(html, Element):
            self.html.add_child(html)
        elif isinstance(html, text_type) or isinstance(html, binary_type):
            self.html.add_child(Html(text_type(html), script=script))

        self.max_width = max_width

        self._template = Template(u"""
            var {{this.get_name()}} = L.popup({maxWidth: '{{this.max_width}}'});

            {% for name, element in this.html._children.items() %}
                var {{name}} = $('{{element.render(**kwargs).replace('\\n',' ')}}')[0];
                {{this.get_name()}}.setContent({{name}});
            {% endfor %}

            {{this._parent.get_name()}}.bindPopup({{this.get_name()}});

            {% for name, element in this.script._children.items() %}
                {{element.render()}}
            {% endfor %}
        """)  # noqa

    def render(self, **kwargs):
        """Renders the HTML representation of the element."""
        for name, child in self._children.items():
            child.render(**kwargs)

        figure = self.get_root()
        assert isinstance(figure, Figure), ('You cannot render this Element '
                                            'if it is not in a Figure.')

        figure.script.add_child(Element(
            self._template.render(this=self, kwargs=kwargs)),
            name=self.get_name())
Example #10
0
 def __init__(self, script=None, html=None, args=None):
     super(JavaScript, self).__init__()
     self.script = Element(script)
     self.html = Element(html)
     self._name = "JavaScript"
     if args is None:
         args = {}
     self.args = args
Example #11
0
    def render(self, **kwargs):
        """Renders the HTML representation of the element."""
        self.json = json.dumps(self.data)

        self._parent.html.add_child(Element(
            Template("""
            <div id="{{this.get_name()}}"></div>
            """).render(this=self, kwargs=kwargs)),
                                    name=self.get_name())

        self._parent.script.add_child(Element(
            Template("""
            var embedSpec = {
                mode: "vega-lite",
                spec: {{this.json}}
            };
            vg.embed(
                {{this.get_name()}}, embedSpec, function(error, result) {}
            );
        """).render(this=self)),
                                      name=self.get_name())

        figure = self.get_root()
        assert isinstance(figure, Figure), ('You cannot render this Element '
                                            'if it is not in a Figure.')

        figure.header.add_child(Element(
            Template("""
            <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>
            """).render(this=self, **kwargs)),
                                name=self.get_name())

        figure.header.add_child(
            JavascriptLink('https://d3js.org/d3.v3.min.js'), name='d3')

        figure.header.add_child(
            JavascriptLink(
                'https://cdnjs.cloudflare.com/ajax/libs/vega/2.6.5/vega.min.js'
            ),  # noqa
            name='vega')

        figure.header.add_child(
            JavascriptLink(
                'https://cdnjs.cloudflare.com/ajax/libs/vega-lite/1.3.1/vega-lite.min.js'
            ),  # noqa
            name='vega-lite')

        figure.header.add_child(
            JavascriptLink(
                'https://cdnjs.cloudflare.com/ajax/libs/vega-embed/2.2.0/vega-embed.min.js'
            ),  # noqa
            name='vega-embed')
Example #12
0
class Popup(Element):
    """Create a Popup instance that can be linked to a Layer.

    Parameters
    ----------
    html: string or Element
        Content of the Popup.
	script: boolean
		If True, popup text will be embedded without escaping
		(suitable for embedding html-ready code)
    max_width: int, default 300
        The maximal width of the popup.
    """
    def __init__(self, html=None, script=False, max_width=300):
        super(Popup, self).__init__()
        self._name = 'Popup'
        self.header = Element()
        self.html = Element()
        self.script = Element()

        self.header._parent = self
        self.html._parent = self
        self.script._parent = self

        if isinstance(html, Element):
            self.html.add_children(html)
        elif isinstance(html, text_type) or isinstance(html, binary_type):
            self.html.add_children(Html(text_type(html), script=script))

        self.max_width = max_width

        self._template = Template(u"""
            var {{this.get_name()}} = L.popup({maxWidth: '{{this.max_width}}'});

            {% for name, element in this.html._children.items() %}
                var {{name}} = $('{{element.render(**kwargs).replace('\\n',' ')}}')[0];
                {{this.get_name()}}.setContent({{name}});
            {% endfor %}

            {{this._parent.get_name()}}.bindPopup({{this.get_name()}});

            {% for name, element in this.script._children.items() %}
                {{element.render()}}
            {% endfor %}
        """)  # noqa

    def render(self, **kwargs):
        """Renders the HTML representation of the element."""
        for name, child in self._children.items():
            child.render(**kwargs)

        figure = self.get_root()
        assert isinstance(figure, Figure), ("You cannot render this Element "
                                            "if it's not in a Figure.")

        figure.script.add_children(Element(
            self._template.render(this=self, kwargs=kwargs)),
            name=self.get_name())
Example #13
0
def add_on_click_handler_to_marker(folium_map, marker, cluster_id, host_url):
    my_js = """
            {0}.on('click', function(e) {{
                parent.postMessage({1}, "{2}");
            }});
            """.format(marker.get_name(), cluster_id, host_url)
    e = Element(my_js)
    html = folium_map.get_root()
    html.script.get_root().render()
    html.script._children[e.get_name()] = e
Example #14
0
    def render(self, **kwargs):
        """Renders the HTML representation of the element."""
        self.json = json.dumps(self.data)

        self._parent.html.add_child(Element(
            Template("""
            <div id="{{this.get_name()}}"></div>
            """).render(this=self, kwargs=kwargs)),
                                    name=self.get_name())

        self._parent.script.add_child(Element(
            Template("""
            vega_parse({{this.json}},{{this.get_name()}});
            """).render(this=self)),
                                      name=self.get_name())

        figure = self.get_root()
        assert isinstance(figure, Figure), ("You cannot render this Element "
                                            "if it's not in a Figure.")

        figure.header.add_child(Element(
            Template("""
            <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>
            """).render(this=self, **kwargs)),
                                name=self.get_name())

        figure.header.add_child(
            JavascriptLink(
                "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"
            ),  # noqa
            name='d3')

        figure.header.add_child(
            JavascriptLink(
                "https://cdnjs.cloudflare.com/ajax/libs/vega/1.4.3/vega.min.js"
            ),  # noqa
            name='vega')

        figure.header.add_child(
            JavascriptLink("https://code.jquery.com/jquery-2.1.0.min.js"),
            name='jquery')

        figure.script.add_child(
            Template("""function vega_parse(spec, div) {
            vg.parse.spec(spec, function(chart) { chart({el:div}).update(); });}"""
                     ),  # noqa
            name='vega_parse')
Example #15
0
    def __init__(self, html=None, parse_html=False, max_width='100%',
                 show=False, sticky=False, **kwargs):
        super(Popup, self).__init__()
        self._name = 'Popup'
        self.header = Element()
        self.html = Element()
        self.script = Element()

        self.header._parent = self
        self.html._parent = self
        self.script._parent = self

        script = not parse_html

        if isinstance(html, Element):
            self.html.add_child(html)
        elif isinstance(html, str):
            self.html.add_child(Html(html, script=script))

        self.show = show
        self.options = parse_options(
            max_width=max_width,
            autoClose=False if show or sticky else None,
            closeOnClick=False if sticky else None,
            **kwargs
        )
Example #16
0
    def __init__(self, html=None, max_width=300):
        super(Popup, self).__init__()
        self._name = 'Popup'
        self.header = Element()
        self.html = Element()
        self.script = Element()

        self.header._parent = self
        self.html._parent = self
        self.script._parent = self

        if isinstance(html, Element):
            self.html.add_children(html)
        elif isinstance(html, text_type) or isinstance(html, binary_type):
            self.html.add_children(Html(text_type(html)))

        self.max_width = max_width

        self._template = Template(u"""
            var {{this.get_name()}} = L.popup({maxWidth: '{{this.max_width}}'});

            {% for name, element in this.html._children.items() %}
                var {{name}} = $('{{element.render(**kwargs).replace('\\n',' ')}}')[0];
                {{this.get_name()}}.setContent({{name}});
            {% endfor %}

            {{this._parent.get_name()}}.bindPopup({{this.get_name()}});

            {% for name, element in this.script._children.items() %}
                {{element.render()}}
            {% endfor %}
        """)  # noqa
Example #17
0
    def render(self, **kwargs):
        # pylint: disable=import-outside-toplevel
        from branca.element import CssLink, Element, Figure, JavascriptLink

        super().render(**kwargs)

        figure = self.get_root()
        assert isinstance(figure, Figure), ("You cannot render this Element "
                                            "if it is not in a Figure.")

        figure.header.add_child(
            JavascriptLink(
                "https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.2/"
                "leaflet.draw.js"))  # noqa
        figure.header.add_child(
            CssLink(
                "https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.2/"
                "leaflet.draw.css"))  # noqa

        export_style = """
            <style>
                #export {
                    position: absolute;
                    top: 270px;
                    left: 11px;
                    z-index: 999;
                    padding: 6px;
                    border-radius: 3px;
                    box-sizing: border-box;
                    color: #333;
                    background-color: #fff;
                    border: 2px solid rgba(0,0,0,0.5);
                    box-shadow: None;
                    font-family: 'Helvetica Neue';
                    cursor: pointer;
                    font-size: 17px;
                    text-decoration: none;
                    text-align: center;
                    font-weight: bold;
                }
            </style>
        """
        # TODO: How to change hover color?
        export_button = """<a href='#' id='export'>Export as<br/>GeoJson</a>"""
        if self.export:
            figure.header.add_child(Element(export_style), name="export")
            figure.html.add_child(Element(export_button), name="export_button")
Example #18
0
def plot_plotly(chart, width='100%', height=525):
    # produce the html in Ipython compatible format
    plot_html, plotdivid, width, height = _plot_html(chart, {'showLink': False}, True, width, height, True)
    # define the plotly js library source url
    head = '<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>'
    # extract the div element from the ipython html
    div = plot_html[0:plot_html.index('<script')]
    # extract the script element from the ipython html
    script = plot_html[plot_html.index('Plotly.newPlot'):plot_html.index('});</script>')] + ';'
    # combine div and script to build the body contents
    body = '<body>{div}<script>{script}</script></body>'.format(div=div, script=script)
    # instantiate a figure object
    figure = Figure()
    # add the head
    figure.header.add_child(Element(head))
    # add the body
    figure.html.add_child(Element(body))

    return figure
Example #19
0
File: map.py Project: pmains/folium
    def render(self, **kwargs):
        """Renders the HTML representation of the element."""
        for name, child in self._children.items():
            child.render(**kwargs)

        figure = self.get_root()
        assert isinstance(figure, Figure), ('You cannot render this Element '
                                            'if it is not in a Figure.')

        figure.script.add_child(Element(
            self._template.render(this=self, kwargs=kwargs)),
                                name=self.get_name())
Example #20
0
    def render(self, **kwargs):
        super(ImageOverlay, self).render()

        figure = self.get_root()
        assert isinstance(figure, Figure), ('You cannot render this Element '
                                            'if it is not in a Figure.')
        pixelated = """<style>
        .leaflet-image-layer {
        image-rendering: -webkit-optimize-contrast; /* old android/safari*/
        image-rendering: crisp-edges; /* safari */
        image-rendering: pixelated; /* chrome */
        image-rendering: -moz-crisp-edges; /* firefox */
        image-rendering: -o-crisp-edges; /* opera */
        -ms-interpolation-mode: nearest-neighbor; /* ie */
        }
        </style>"""

        if self.pixelated:
            figure.header.add_child(Element(pixelated), name='leaflet-image-layer')  # noqa
Example #21
0
    def __init__(self, html=None, parse_html=False, max_width=300, show=False, sticky=False):
        super(Popup, self).__init__()
        self._name = 'Popup'
        self.header = Element()
        self.html = Element()
        self.script = Element()

        self.header._parent = self
        self.html._parent = self
        self.script._parent = self

        script = not parse_html

        if isinstance(html, Element):
            self.html.add_child(html)
        elif isinstance(html, text_type) or isinstance(html, binary_type):
            self.html.add_child(Html(text_type(html), script=script))

        self.max_width = max_width
        self.show = show
        self.sticky = sticky
Example #22
0
def main():
    cfg = pathlib.Path('~/.bliptools')
    parser = argparse.ArgumentParser()
    parser.add_argument('input',
                        metavar='NAME',
                        type=pathlib.Path,
                        help='read journal data from file NAME')
    parser.add_argument('--output',
                        '-o',
                        metavar='NAME',
                        type=pathlib.Path,
                        help='write geojson to file NAME')
    parser.add_argument(
        '-c',
        '--config',
        metavar='CFG',
        type=pathlib.Path,
        default=cfg,
        help='read configuration from CFG, default {}'.format(cfg))
    parser.add_argument('-t',
                        '--twitter',
                        metavar="HANDLE",
                        help="twitter handler")
    parser.add_argument('--verbose',
                        action='store_true',
                        default=False,
                        help='be verbose')

    args = parser.parse_args()

    if args.verbose:
        level = logging.DEBUG
    else:
        level = logging.INFO

    logging.basicConfig(format='%(levelname)s:%(message)s', level=level)
    cfg = readConfig(args.config)

    db = BlipDB('sqlite:///{}'.format(args.input))

    if args.output is None:
        out = args.input.stem + '.html'
    else:
        out = str(args.output)

    popup = """<p>
<a href="https://blipfoto.com/entry/{e.entry_id}"><img width="200px" src="{e.image_url}"></a>
<strong>{e.date}:</strong> {e.title}
</p>
"""

    m = folium.Map(location=[55.952060, -3.196480])
    mc = MarkerCluster()
    for e in db.get_entries_with_location():
        mc.add_child(
            folium.Marker(location=[e.lat, e.lon], popup=popup.format(e=e)))

    m.add_child(mc)

    html = m.get_root()
    description = "Interactive map showing all geotagged entries of blip journal https://www.blipfoto.com/{e.username}".format(
        e=e)
    html.header.add_child(
        Element('<meta name="description" content="{description}" />'.format(
            description=description)))
    html.header.add_child(
        Element('<meta name="twitter:card" content="summary_large_image">'))
    if args.twitter is not None:
        html.header.add_child(
            Element('<meta name="twitter:site" content="{handle}">'.format(
                handle=args.twitter)))
    html.header.add_child(
        Element('<meta name="twitter:title" content="{title}">'.format(
            title=e.username)))
    html.header.add_child(
        Element(
            '<meta name="twitter:description" content="{description}">'.format(
                description=description)))
    html.header.add_child(
        Element('<meta name="twitter:image" content="{img}">'.format(
            img=e.image_url)))

    m.save(out)
Example #23
0
    def render(self, **kwargs):
        super(TileLayer, self).render()

        figure = self.get_root()
        assert isinstance(figure, Figure), ('You cannot render this Element '
                                            'if it is not in a Figure.')

        figure.header.add_child(
            JavascriptLink('https://rawgit.com/socib/Leaflet.TimeDimension/master/dist/leaflet.timedimension.min.js'),  # noqa
            name='leaflet.timedimension.min.js')

        figure.header.add_child(
            JavascriptLink(
                'https://cdnjs.cloudflare.com/ajax/libs/heatmap.js/2.0.2/heatmap.min.js'),
            name='heatmap.min.js')

        figure.header.add_child(
            JavascriptLink('https://rawgit.com/pa7/heatmap.js/develop/plugins/leaflet-heatmap/leaflet-heatmap.js'),  # noqa
            name='leaflet-heatmap.js')

        figure.header.add_child(
            CssLink('http://apps.socib.es/Leaflet.TimeDimension/dist/leaflet.timedimension.control.min.css'),  # noqa
            name='leaflet.timedimension.control.min.css')

        figure.header.add_child(
            Element(
                """
            <script>
                var TDHeatmap = L.TimeDimension.Layer.extend({

            initialize: function(data, options) {
                var heatmapCfg = {
                    radius: 15,
                    maxOpacity: 1.,
                    scaleRadius: false,
                    useLocalExtrema: false,
                    latField: 'lat',
                    lngField: 'lng',
                    valueField: 'count',
                    defaultWeight : 1,
                };
                heatmapCfg = $.extend({}, heatmapCfg, options.heatmapOptions || {});
                var layer = new HeatmapOverlay(heatmapCfg);
                L.TimeDimension.Layer.prototype.initialize.call(this, layer, options);
                this._currentLoadedTime = 0;
                this._currentTimeData = {
                    data: []
                    };
                this.data= data;
                this.defaultWeight = heatmapCfg.defaultWeight || 1;
            },
            onAdd: function(map) {
                L.TimeDimension.Layer.prototype.onAdd.call(this, map);
                map.addLayer(this._baseLayer);
                if (this._timeDimension) {
                    this._getDataForTime(this._timeDimension.getCurrentTime());
                }
            },
            _onNewTimeLoading: function(ev) {
                this._getDataForTime(ev.time);
                return;
            },
            isReady: function(time) {
                return (this._currentLoadedTime == time);
            },
            _update: function() {
                this._baseLayer.setData(this._currentTimeData);
                return true;
            },
            _getDataForTime: function(time) {
                    delete this._currentTimeData.data;
                    this._currentTimeData.data = [];
                    var data = this.data[time-1];
                    for (var i = 0; i < data.length; i++) {
                        this._currentTimeData.data.push({
                                lat: data[i][0],
                                lng: data[i][1],
                                count: data[i].length>2 ? data[i][2] : this.defaultWeight
                            });
                        }
                    this._currentLoadedTime = time;
                    if (this._timeDimension && time == this._timeDimension.getCurrentTime() && !this._timeDimension.isLoading()) {
                        this._update();
                    }
                    this.fire('timeload', {
                        time: time
                    });
                }
        });

        L.Control.TimeDimensionCustom = L.Control.TimeDimension.extend({
            initialize: function(index, options) {
                var playerOptions = {
                    buffer: 1,
                    minBufferReady: -1
                    };
                options.playerOptions = $.extend({}, playerOptions, options.playerOptions || {});
                L.Control.TimeDimension.prototype.initialize.call(this, options);
                this.index = index;
                },
            _getDisplayDateFormat: function(date){
                return this.index[date.getTime()-1];
                }
            });
            </script>
                """,  # noqa
                template_name='timeControlScript'
            )
        )
    def render(self, **kwargs):
        super(HeatMapWithTime, self).render(**kwargs)

        figure = self.get_root()
        assert isinstance(figure, Figure), (
            'You cannot render this Element if it is not in a Figure.')

        # Import Javascripts
        for name, url in _default_js:
            figure.header.add_child(JavascriptLink(url), name=name)

        # Import Css
        for name, url in _default_css:
            figure.header.add_child(CssLink(url), name=name)

        figure.header.add_child(
            Element(
                """
			<script>
				var TDHeatmap = L.TimeDimension.Layer.extend({

			initialize: function(data, options) {
				var heatmapCfg = {
					radius: 15,
					maxOpacity: 1.,
					scaleRadius: false,
					useLocalExtrema: false,
					latField: 'lat',
					lngField: 'lng',
					valueField: 'count',
					defaultWeight : 1,
				};
				heatmapCfg = $.extend({}, heatmapCfg, options.heatmapOptions || {});
				var layer = new HeatmapOverlay(heatmapCfg);
				L.TimeDimension.Layer.prototype.initialize.call(this, layer, options);
				this._currentLoadedTime = 0;
				this._currentTimeData = {
					data: []
					};
				this.data= data;
				this.defaultWeight = heatmapCfg.defaultWeight || 1;
			},
			onAdd: function(map) {
				L.TimeDimension.Layer.prototype.onAdd.call(this, map);
				map.addLayer(this._baseLayer);
				if (this._timeDimension) {
					this._getDataForTime(this._timeDimension.getCurrentTime());
				}
			},
			_onNewTimeLoading: function(ev) {
				this._getDataForTime(ev.time);
				return;
			},
			isReady: function(time) {
				return (this._currentLoadedTime == time);
			},
			_update: function() {
				this._baseLayer.setData(this._currentTimeData);
				return true;
			},
			_getDataForTime: function(time) {
					delete this._currentTimeData.data;
					this._currentTimeData.data = [];
					var data = this.data[time-1];
					for (var i = 0; i < data.length; i++) {
						this._currentTimeData.data.push({
								lat: data[i][0],
								lng: data[i][1],
								count: data[i].length>2 ? data[i][2] : this.defaultWeight
							});
						}
					this._currentLoadedTime = time;
					if (this._timeDimension && time == this._timeDimension.getCurrentTime() && !this._timeDimension.isLoading()) {
						this._update();
					}
					this.fire('timeload', {
						time: time
					});
				}
		});

		L.Control.TimeDimensionCustom = L.Control.TimeDimension.extend({
			initialize: function(index, options) {
				var playerOptions = {
					buffer: 1,
					minBufferReady: -1
					};
				options.playerOptions = $.extend({}, playerOptions, options.playerOptions || {});
				L.Control.TimeDimension.prototype.initialize.call(this, options);
				this.index = index;
				},
			_getDisplayDateFormat: function(date){
				return this.index[date.getTime()-1];
				}
			});
			</script>
				""",  # noqa
                template_name='timeControlScript'))
Example #25
0
class Popup(Element):
    """Create a Popup instance that can be linked to a Layer.

    Parameters
    ----------
    html: string or Element
        Content of the Popup.
    parse_html: bool, default False
        True if the popup is a template that needs to the rendered first.
    max_width: int for pixels or text for percentages, default '100%'
        The maximal width of the popup.
    show: bool, default False
        True renders the popup open on page load.
    sticky: bool, default False
        True prevents map and other popup clicks from closing.
    """
    _template = Template(u"""
        var {{this.get_name()}} = L.popup({{ this.options|tojson }});

        {% for name, element in this.html._children.items() %}
            var {{ name }} = $(`{{ element.render(**kwargs).replace('\\n',' ') }}`)[0];
            {{ this.get_name() }}.setContent({{ name }});
        {% endfor %}

        {{ this._parent.get_name() }}.bindPopup({{ this.get_name() }})
        {% if this.show %}.openPopup(){% endif %};

        {% for name, element in this.script._children.items() %}
            {{element.render()}}
        {% endfor %}
    """)  # noqa

    def __init__(self, html=None, parse_html=False, max_width='100%',
                 show=False, sticky=False, **kwargs):
        super(Popup, self).__init__()
        self._name = 'Popup'
        self.header = Element()
        self.html = Element()
        self.script = Element()

        self.header._parent = self
        self.html._parent = self
        self.script._parent = self

        script = not parse_html

        if isinstance(html, Element):
            self.html.add_child(html)
        elif isinstance(html, str):
            self.html.add_child(Html(html, script=script))

        self.show = show
        self.options = parse_options(
            max_width=max_width,
            autoClose=False if show or sticky else None,
            closeOnClick=False if sticky else None,
            **kwargs
        )

    def render(self, **kwargs):
        """Renders the HTML representation of the element."""
        for name, child in self._children.items():
            child.render(**kwargs)

        figure = self.get_root()
        assert isinstance(figure, Figure), ('You cannot render this Element '
                                            'if it is not in a Figure.')

        figure.script.add_child(Element(
            self._template.render(this=self, kwargs=kwargs)),
            name=self.get_name())
Example #26
0
class Popup(Element):
    """Create a Popup instance that can be linked to a Layer.

    Parameters
    ----------
    html: string or Element
        Content of the Popup.
    parse_html: bool, default False
        True if the popup is a template that needs to the rendered first.
    max_width: int for pixels or text for percentages, default '100%'
        The maximal width of the popup.
    show: bool, default False
        True renders the popup open on page load.
    sticky: bool, default False
        True prevents map and other popup clicks from closing.
    """
    _template = Template(u"""
            var {{this.get_name()}} = L.popup({maxWidth: '{{this.max_width}}'
            {% if this.show or this.sticky %}, autoClose: false{% endif %}
            {% if this.sticky %}, closeOnClick: false{% endif %}});

            {% for name, element in this.html._children.items() %}
                var {{ name }} = $(`{{ element.render(**kwargs).replace('\\n',' ') }}`)[0];
                {{this.get_name()}}.setContent({{name}});
            {% endfor %}

            {{this._parent.get_name()}}.bindPopup({{this.get_name()}})
            {% if this.show %}.openPopup(){% endif %};

            {% for name, element in this.script._children.items() %}
                {{element.render()}}
            {% endfor %}
        """)  # noqa

    def __init__(self,
                 html=None,
                 parse_html=False,
                 max_width='100%',
                 show=False,
                 sticky=False):
        super(Popup, self).__init__()
        self._name = 'Popup'
        self.header = Element()
        self.html = Element()
        self.script = Element()

        self.header._parent = self
        self.html._parent = self
        self.script._parent = self

        script = not parse_html

        if isinstance(html, Element):
            self.html.add_child(html)
        elif isinstance(html, text_type) or isinstance(html, binary_type):
            self.html.add_child(Html(text_type(html), script=script))

        self.max_width = max_width
        self.show = show
        self.sticky = sticky

    def render(self, **kwargs):
        """Renders the HTML representation of the element."""
        for name, child in self._children.items():
            child.render(**kwargs)

        figure = self.get_root()
        assert isinstance(figure, Figure), ('You cannot render this Element '
                                            'if it is not in a Figure.')

        figure.script.add_child(Element(
            self._template.render(this=self, kwargs=kwargs)),
                                name=self.get_name())
Example #27
0
    def prepareMap(self):
        center = [40.8, -86]
        zoom = 8
        self.map = folium.Map(location=[40.8, -86])
        ##########################################################  scrollWheelZoom = false
        self.map._template = Template(u"""
            {% macro header(this, kwargs) %}
                <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>
            {% endmacro %}
            {% macro html(this, kwargs) %}
                <div class="folium-map" id="{{this.get_name()}}" ></div>
            {% endmacro %}
            {% macro script(this, kwargs) %}
                {% if this.max_bounds %}
                    var southWest = L.latLng({{ this.min_lat }}, {{ this.min_lon }});
                    var northEast = L.latLng({{ this.max_lat }}, {{ this.max_lon }});
                    var bounds = L.latLngBounds(southWest, northEast);
                {% else %}
                    var bounds = null;
                {% endif %}
                var {{this.get_name()}} = L.map(
                                      '{{this.get_name()}}',
                                      {center: [{{this.location[0]}},{{this.location[1]}}],
                                      zoom: 8,
                                      maxBounds: bounds,
                                      scrollWheelZoom: false,
                                      layers: [],
                                      worldCopyJump: false,
                                      crs: L.CRS.{{this.crs}}
                                     });
                {% if this.control_scale %}L.control.scale().addTo({{this.get_name()}});{% endif %}
            {% endmacro %}
            """)  # noqa

        self.map.get_root().header.add_child(Element(''' <style type=text/css>
                    .info {
                        padding: 6px 8px;
                        font: 14px/16px Arial, Helvetica, sans-serif;
                        background: white;
                        background: rgba(255,255,255,0.8);
                        box-shadow: 0 0 15px rgba(0,0,0,0.2);
                        border-radius: 5px;
                    }
                    .info h4 {
                        margin: 0 0 2px;
                        color: #777;
                    }
                    .imgButton {
                        padding: 6px 8px;
                        font: 14px/16px Arial, Helvetica, sans-serif;
                        background: transparent;
                        border-radius: 5px;
                    }
                    .legend {
                        line-height: 18px;
                        color: #555;
                    }
                    .legend i {
                        width: 22px;
                        height: 18px;
                        float: left;
                        margin-right: 8px;
                        opacity: 0.7;
                    }
                    .toggles {
                        width: 90px;
                    }
                    .radioLabel{
                        width: 60px;
                        padding-left: 5px;
                    }

                    #slider {
                        padding: 3px 180px;
                    }
                    ''' + self.loadingCSS + '''
                    </style>'''),
                                             name='map')

        self.map.get_root().header.add_child(
            JavascriptLink("https://code.highcharts.com/highcharts.js"),
            name="highcharts")
        self.map.get_root().header.add_child(
            JavascriptLink("https://code.highcharts.com/modules/exporting.js"),
            name="exporting")
        self.map.get_root().header.add_child(
            JavascriptLink("https://code.highcharts.com/highcharts-more.js"),
            name="highcharts-more")
        self.map.get_root().header.add_child(
            JavascriptLink("https://code.jquery.com/jquery-1.12.4.js"),
            name="jquery")
        self.map.get_root().header.add_child(
            JavascriptLink("https://code.jquery.com/ui/1.12.1/jquery-ui.js"),
            name="jquery-ui")
        # self.map.get_root().header.add_child(JavascriptLink("https://raw.githubusercontent.com/eligrey/FileSaver.js/master/FileSaver.min.js"), name="file-saver")
        self.map.get_root().header.add_child(CssLink(
            "https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"),
                                             name="jquery-ui-css")
        self.map.get_root().header.add_child(
            Element("<script>" + self.fileSaverJS + "</script>"),
            name='file-saver')
        self.map.get_root().header.add_child(
            Element("<script>" + self.jszipJS + "</script>"), name='jszip')
        self.map.get_root().script.add_child(Element(self.leafletHeatJS),
                                             name='leaflet-heat')