예제 #1
0
    def test_feature_group(self):
        """Test FeatureGroup."""

        map = folium.Map()
        feature_group = FeatureGroup()
        feature_group.add_children(Marker([45, -30], popup=Popup('-30')))
        feature_group.add_children(Marker([45, 30], popup=Popup('30')))
        map.add_children(feature_group)
        map.add_children(folium.map.LayerControl())

        map._repr_html_()
예제 #2
0
파일: test_map.py 프로젝트: zewdu94/folium
def test_popup_show():
    m = Map()
    popup = Popup('Some text.', show=True).add_to(m)
    rendered = popup._template.render(this=popup, kwargs={})
    expected = """
    var {popup_name} = L.popup({{maxWidth: \'300\' , autoClose: false}});
    var {html_name} = $(`<div id="{html_name}" style="width: 100.0%; height: 100.0%;">Some text.</div>`)[0];
    {popup_name}.setContent({html_name});
    {map_name}.bindPopup({popup_name}).openPopup();
    """.format(popup_name=popup.get_name(),
               html_name=list(popup.html._children.keys())[0],
               map_name=m.get_name())
    assert _normalize(rendered) == _normalize(expected)
예제 #3
0
def test_popup_show():
    m = Map()
    popup = Popup('Some text.', show=True).add_to(m)
    rendered = popup._template.render(this=popup, kwargs={})
    expected = """
    var {popup_name} = L.popup({{maxWidth: \'100%\' , autoClose: false}});
    var {html_name} = $(`<div id="{html_name}" style="width: 100.0%; height: 100.0%;">Some text.</div>`)[0];
    {popup_name}.setContent({html_name});
    {map_name}.bindPopup({popup_name}).openPopup();
    """.format(popup_name=popup.get_name(),
               html_name=list(popup.html._children.keys())[0],
               map_name=m.get_name())
    assert _normalize(rendered) == _normalize(expected)
예제 #4
0
    def test_feature_group(self):
        """Test FeatureGroup."""

        map = folium.Map()
        feature_group = FeatureGroup()
        feature_group.add_child(Marker([45, -30], popup=Popup('-30')))
        feature_group.add_child(Marker([45, 30], popup=Popup('30')))
        map.add_child(feature_group)
        map.add_child(folium.map.LayerControl())

        map._repr_html_()

        bounds = map.get_bounds()
        assert bounds == [[45, -30], [45, 30]], bounds
예제 #5
0
    def __init__(self, locations, color=None, weight=None,
                 opacity=None, popup=None):
        super(PolyLine, self).__init__()
        self._name = 'PolyLine'
        self.data = _validate_coordinates(locations)
        self.color = color
        self.weight = weight
        self.opacity = opacity
        if isinstance(popup, text_type) or isinstance(popup, binary_type):
            self.add_child(Popup(popup))
        elif popup is not None:
            self.add_child(popup)

        self._template = Template(u"""
            {% macro script(this, kwargs) %}
                var {{this.get_name()}} = L.polyline(
                    {{this.data}},
                    {
                        {% if this.color != None %}color: '{{ this.color }}',{% endif %}
                        {% if this.weight != None %}weight: {{ this.weight }},{% endif %}
                        {% if this.opacity != None %}opacity: {{ this.opacity }},{% endif %}
                        });
                {{this._parent.get_name()}}.addLayer({{this.get_name()}});
            {% endmacro %}
            """)  # noqa
예제 #6
0
    def __init__(self, locations, popups=None, icons=None):
        super(MarkerCluster, self).__init__()
        self._name = 'MarkerCluster'

        if popups is None:
            popups = [None] * len(locations)
        if icons is None:
            icons = [None] * len(locations)

        for location, popup, icon in zip(locations, popups, icons):
            if popup is None or isinstance(popup, Popup):
                p = popup
            else:
                p = Popup(popup)
            if icon is None or isinstance(icon, Icon):
                i = icon
            else:
                i = Icon(icon)
            self.add_child(Marker(location, popup=p, icon=i))

        self._template = Template(u"""
            {% macro script(this, kwargs) %}
                var {{this.get_name()}} = L.markerClusterGroup();
                {{this._parent.get_name()}}.addLayer({{this.get_name()}});
            {% endmacro %}
            """)
예제 #7
0
    def __init__(self, locations=None, popups=None, icons=None, name=None,
                 overlay=True, control=True, show=True,
                 icon_create_function=None):
        super(MarkerCluster, self).__init__(name=name, overlay=overlay,
                                            control=control, show=show)

        if locations is not None:
            if popups is None:
                popups = [None]*len(locations)
            if icons is None:
                icons = [None]*len(locations)
            for location, popup, icon in zip(locations, popups, icons):
                p = popup if popup is None or isinstance(popup, Popup) else Popup(popup)  # noqa
                i = icon if icon is None or isinstance(icon, Icon) else Icon(icon)  # noqa
                self.add_child(Marker(location, popup=p, icon=i))

        self._name = 'MarkerCluster'
        self._icon_create_function = icon_create_function.strip() if icon_create_function else ''  # noqa
        self._template = Template(u"""
            {% macro script(this, kwargs) %}
            var {{this.get_name()}} = L.markerClusterGroup({
                {% if this._icon_create_function %}
                   iconCreateFunction: {{this._icon_create_function}}
                {% endif %}
            });
            {{this._parent.get_name()}}.addLayer({{this.get_name()}});
            {% endmacro %}
            """)
예제 #8
0
    def __init__(self,
                 locations=None,
                 popups=None,
                 icons=None,
                 name=None,
                 overlay=True,
                 control=True,
                 show=True,
                 icon_create_function=None,
                 options=None):
        super(MarkerCluster, self).__init__(name=name,
                                            overlay=overlay,
                                            control=control,
                                            show=show)
        self._name = 'MarkerCluster'

        if locations is not None:
            if popups is None:
                popups = [None] * len(locations)
            if icons is None:
                icons = [None] * len(locations)
            for location, popup, icon in zip(locations, popups, icons):
                p = popup if self._validate(popup, Popup) else Popup(popup)
                i = icon if self._validate(icon, Icon) else Icon(icon)
                self.add_child(Marker(location, popup=p, icon=i))

        options = {} if options is None else options
        self.options = json.dumps(options, sort_keys=True, indent=2)
        if icon_create_function is not None:
            assert isinstance(icon_create_function, str)
        self.icon_create_function = icon_create_function
예제 #9
0
    def __init__(self,
                 locations=None,
                 popups=None,
                 icons=None,
                 name=None,
                 overlay=True,
                 control=True,
                 show=True,
                 icon_create_function=None):
        super(MarkerCluster, self).__init__(name=name,
                                            overlay=overlay,
                                            control=control,
                                            show=show)

        if locations is not None:
            if popups is None:
                popups = [None] * len(locations)
            if icons is None:
                icons = [None] * len(locations)
            for location, popup, icon in zip(locations, popups, icons):
                p = popup if popup is None or isinstance(
                    popup, Popup) else Popup(popup)  # noqa
                i = icon if icon is None or isinstance(icon, Icon) else Icon(
                    icon)  # noqa
                self.add_child(Marker(location, popup=p, icon=i))

        self._name = 'MarkerCluster'
        self._icon_create_function = icon_create_function.strip(
        ) if icon_create_function else ''  # noqa
예제 #10
0
    def __init__(self,
                 locations=None,
                 popups=None,
                 icons=None,
                 name=None,
                 overlay=True,
                 control=True,
                 show=True,
                 icon_create_function=None,
                 options=None,
                 **kwargs):
        if options is not None:
            kwargs.update(options)  # options argument is legacy
        super(MarkerCluster, self).__init__(name=name,
                                            overlay=overlay,
                                            control=control,
                                            show=show)
        self._name = 'MarkerCluster'

        if locations is not None:
            if popups is None:
                popups = [None] * len(locations)
            if icons is None:
                icons = [None] * len(locations)
            for location, popup, icon in zip(locations, popups, icons):
                p = popup if self._validate(popup, Popup) else Popup(popup)
                i = icon if self._validate(icon, Icon) else Icon(icon)
                self.add_child(Marker(location, popup=p, icon=i))

        self.options = parse_options(**kwargs)
        if icon_create_function is not None:
            assert isinstance(icon_create_function, str)
        self.icon_create_function = icon_create_function
예제 #11
0
파일: test_map.py 프로젝트: xclu/folium
def test_popup_unicode():
    popup = Popup("Ça c'est chouette")
    _id = list(popup.html._children.keys())[0]
    kw = dict(id=_id,
              width='100.0%',
              height='100.0%',
              text="Ça c&#39;est chouette")
    assert popup.html.render().strip() == tmpl(**kw).strip()
예제 #12
0
파일: test_map.py 프로젝트: xclu/folium
def test_popup_ascii():
    popup = Popup('Some text.')
    _id = list(popup.html._children.keys())[0]
    kw = dict(id=_id,
              width='100.0%',
              height='100.0%',
              text='Some text.')
    assert popup.html.render().strip() == tmpl(**kw).strip()
예제 #13
0
파일: test_map.py 프로젝트: xclu/folium
def test_popup_quotes():
    popup = Popup("Let's try quotes")
    _id = list(popup.html._children.keys())[0]
    kw = dict(id=_id,
              width='100.0%',
              height='100.0%',
              text='Let&#39;s try quotes')
    assert popup.html.render().strip() == tmpl(**kw).strip()
예제 #14
0
def _add_label_icon(my_map, position, text, color, icon, icon_color):
    html = folium.Html(text, script=True)
    Marker(location=position,
           popup=Popup(html, True, 200, False, True),
           icon=folium.Icon(icon=icon,
                            color=color,
                            icon_color=icon_color,
                            prefix='fa')).add_to(my_map)
    return my_map
예제 #15
0
 def __init__(self, locations, popup=None, tooltip=None):
     super(BaseMultiLocation, self).__init__()
     self.locations = validate_locations(locations)
     if popup is not None:
         self.add_child(
             popup if isinstance(popup, Popup) else Popup(str(popup)))
     if tooltip is not None:
         self.add_child(tooltip if isinstance(tooltip, Tooltip
                                              ) else Tooltip(str(tooltip)))
예제 #16
0
def test_popup_unicode():
    popup = Popup(u"Ça c'est chouette", parse_html=True)
    _id = list(popup.html._children.keys())[0]
    kw = {
        'id': _id,
        'width': '100.0%',
        'height': '100.0%',
        'text': u'Ça c&#39;est chouette',
    }
    assert ''.join(popup.html.render().split()) == ''.join(tmpl(**kw).split())
예제 #17
0
def test_popup_quotes():
    popup = Popup("Let's try quotes", parse_html=True)
    _id = list(popup.html._children.keys())[0]
    kw = {
        'id': _id,
        'width': '100.0%',
        'height': '100.0%',
        'text': 'Let&#39;s try quotes',
    }
    assert ''.join(popup.html.render().split()) == ''.join(tmpl(**kw).split())
예제 #18
0
def test_popup_ascii():
    popup = Popup('Some text.')
    _id = list(popup.html._children.keys())[0]
    kw = {
        'id': _id,
        'width': '100.0%',
        'height': '100.0%',
        'text': 'Some text.',
    }
    assert ''.join(popup.html.render().split()) == ''.join(tmpl(**kw).split())
예제 #19
0
def mapData(pointList):

    m = folium.Map(location=[pointList[0].lat, pointList[0].long],
                   zoom_start=20)

    feature_group = folium.FeatureGroup("Locations")
    for i in range(len(pointList)):
        print str(pointList[i].lat) + "," + str(pointList[i].long)
        feature_group.add_child(
            folium.CircleMarker(location=(pointList[i].lat, pointList[i].long),
                                popup=Popup("Soruce: " + pointList[i].src,
                                            show=True),
                                color='red'))
        m.add_child(feature_group)

    #m = folium.Map(location=())
    #folium.CircleMarker(location=(lat,long), popup=Popup("Soruce: " + src, show=True), color = 'red').add_to(m)
    m.save('map.html')
예제 #20
0
    def __init__(self, locations, popups=None, icons=None):
        """Creates a MarkerCluster plugin to append into a map with
        Map.add_children.

        Parameters
        ----------
            locations: list of list or array of shape (n,2).
                Data points of the form [[lat, lng]].

            popups: list of length n.
                Popup for each marker.

            icons: list of length n.
                Icon for each marker.
        """
        super(MarkerCluster, self).__init__()
        self._name = 'MarkerCluster'

        if popups is None:
            popups = [None] * len(locations)
        if icons is None:
            icons = [None] * len(locations)

        for location, popup, icon in zip(locations, popups, icons):
            if popup is None or isinstance(popup, Popup):
                p = popup
            else:
                p = Popup(popup)
            if icon is None or isinstance(icon, Icon):
                i = icon
            else:
                i = Icon(icon)
            self.add_children(Marker(location, popup=p, icon=i))

        self._template = Template(u"""
            {% macro script(this, kwargs) %}
                var {{this.get_name()}} = L.markerClusterGroup();
                {{this._parent.get_name()}}.addLayer({{this.get_name()}});
            {% endmacro %}
            """)
예제 #21
0
파일: map.py 프로젝트: vicb/FAI-Airscore
def make_map(layer_geojson=None,
             points=None,
             circles=None,
             polyline=None,
             goal_line=None,
             margin=0,
             thermal_layer=False,
             show_thermal=False,
             waypoint_layer=False,
             show_waypoint=False,
             extra_tracks=None,
             airspace_layer=None,
             show_airspace=False,
             infringements=None,
             bbox=None,
             trackpoints=None):
    """Gets elements and layers from Flask, and returns map object"""
    '''creates layers'''
    if points is None:
        points = []

    if bbox:
        location = bbox_centre(bbox)
    else:
        location = [45, 10]

    folium_map = folium.Map(location=location,
                            position='relative',
                            zoom_start=13,
                            tiles="Stamen Terrain",
                            max_bounds=True,
                            min_zoom=5,
                            prefer_canvas=True)
    #     folium.LayerControl().add_to(folium_map)
    '''Define map borders'''
    # at this stage a track (layer_geojason has bbox inside,
    # otherwise (plotting wpts, airspace, task) we can use the bbox variable
    if bbox:
        folium_map.fit_bounds(bounds=bbox, max_zoom=13)

    if layer_geojson:
        '''Define map borders'''
        if layer_geojson["bbox"]:
            bbox = layer_geojson["bbox"]
            folium_map.fit_bounds(bounds=bbox, max_zoom=13)
        """Design track"""
        if layer_geojson["geojson"]:
            track = layer_geojson['geojson']['tracklog']
            folium.GeoJson(
                track, name='Flight',
                style_function=track_style_function).add_to(folium_map)
            if extra_tracks:
                extra_track_style_function = lambda colour: (lambda x: {
                    'color':
                    colour
                    if x['properties']['Track'] == 'Pre_Goal' else 'grey'
                })

                for extra_track in extra_tracks:
                    colour = extra_track['colour']
                    folium.GeoJson(extra_track['track'],
                                   name=extra_track['name'],
                                   style_function=extra_track_style_function(
                                       colour)).add_to(folium_map)

            if thermal_layer:
                thermals = layer_geojson['geojson']['thermals']
                thermal_group = FeatureGroup(name='Thermals',
                                             show=show_thermal)

                for t in thermals:
                    # icon = Icon(color='blue', icon_color='black', icon='sync-alt', angle=0, prefix='fas')
                    icon = CustomIcon('/app/airscore/static/img/thermal.png')
                    thermal_group.add_child(
                        Marker([t[1], t[0]], icon=icon, popup=Popup(t[2])))

                folium_map.add_child(thermal_group)

            if waypoint_layer:
                waypoints = layer_geojson['geojson']['waypoint_achieved']
                waypoint_group = FeatureGroup(name='Waypoints Taken',
                                              show=show_waypoint)
                for w in waypoints:
                    waypoint_group.add_child(
                        Marker([w[1], w[0]], popup=Popup(w[6], max_width=300)))

                folium_map.add_child(waypoint_group)
    """Design cylinders"""
    if circles:
        for c in circles:
            """create design based on type"""
            if c['type'] == 'launch':
                col = '#996633'
            elif c['type'] == 'speed':
                col = '#00cc00'
            elif c['type'] == 'endspeed':
                col = '#cc3333'
            elif c['type'] == 'restricted':
                col = '#ff0000'
            else:
                col = '#3186cc'

            popup = folium.Popup(
                f"<b>{c['name']}</b><br>Radius: {str(c['radius_label'])} m.",
                max_width=300)

            folium.Circle(location=(c['latitude'], c['longitude']),
                          radius=0.0 + c['radius'],
                          popup=popup,
                          color=col,
                          weight=2,
                          opacity=0.8,
                          fill=True,
                          fill_opacity=0.2,
                          fill_color=col).add_to(folium_map)
    """Plot tolerance cylinders"""
    if margin:
        for c in circles:
            """create two circles based on tolerance value"""
            folium.Circle(location=(c['latitude'], c['longitude']),
                          radius=0.0 + c['radius'] * (1 + margin),
                          popup=None,
                          color="#44cc44",
                          weight=0.75,
                          opacity=0.8,
                          fill=False).add_to(folium_map)

            folium.Circle(location=(c['latitude'], c['longitude']),
                          radius=0.0 + c['radius'] * (1 - margin),
                          popup=None,
                          color="#44cc44",
                          weight=0.75,
                          opacity=0.8,
                          fill=False).add_to(folium_map)
    """Plot waypoints"""
    if points:
        for p in points:
            folium.Marker(location=[p['latitude'], p['longitude']],
                          popup=p['name'],
                          icon=folium.features.DivIcon(
                              icon_size=(20, 20),
                              icon_anchor=(0, 0),
                              html='<div class="waypoint-label">%s</div>' %
                              p['name'],
                          )).add_to(folium_map)
    """Design optimised route"""
    if polyline:
        folium.PolyLine(locations=polyline,
                        weight=1.5,
                        opacity=0.75,
                        color='#2176bc').add_to(folium_map)

    if goal_line:
        folium.PolyLine(locations=goal_line,
                        weight=1.5,
                        opacity=0.75,
                        color='#800000').add_to(folium_map)

    if airspace_layer:
        airspace_group = FeatureGroup(name='Airspaces', show=show_airspace)
        for space in airspace_layer:
            airspace_group.add_child(space)
        if infringements:
            for i in infringements:
                popup = folium.Popup(
                    f"<b>{i[3]}</b><br>{i[5]}. separation: {i[4]} m. <br>"
                    f"{i[7]} - alt. {i[2]} m.",
                    max_width=300)
                icon = folium.Icon(color="red", icon="times", prefix='fa')
                airspace_group.add_child(
                    Marker([i[1], i[0]], icon=icon, popup=popup))
        folium_map.add_child(airspace_group)

    if trackpoints:
        trackpoints_group = FeatureGroup(name='Trackpoints', show=True)
        for i in trackpoints:
            tooltip = folium.Tooltip(
                f"Time UTC: <b>{i[5]}</b> Local Time: <b>{i[6]}</b><br>"
                f"lat: <b>{round(i[1], 4)}</b> lon: <b>{round(i[0], 4)}</b><br>"
                f"GPS alt: <b>{int(i[4])} m.</b> ISA Press alt: <b>{int(i[3])} m.</b>"
            )
            trackpoints_group.add_child(
                folium.CircleMarker((i[1], i[0]), radius=1, tooltip=tooltip))
        folium_map.add_child(trackpoints_group)

    folium.LayerControl().add_to(folium_map)
    folium.plugins.Fullscreen().add_to(folium_map)
    folium.plugins.MeasureControl().add_to(folium_map)
    return folium_map
예제 #22
0
def make_map(layer_geojson=None, points=None, circles=None, polyline=None, goal_line=None, margin=0,
             thermal_layer=False, waypoint_layer=False, extra_tracks=None, airspace_layer=None, bbox=None):
    if points is None:
        points = []

    if bbox:
        location = bbox_centre(bbox)
    else:
        location = [45, 10]
    folium_map = folium.Map(location=location, zoom_start=13, tiles="Stamen Terrain", width='100%',
                            height='75%')
    #     folium.LayerControl().add_to(folium_map)
    '''Define map borders'''
    # at this stage a track (layer_geojason has bbox inside,
    # otherwise (plotting wpts, airspace, task) we can use the bbox variable
    if bbox:
        folium_map.fit_bounds(bounds=bbox, max_zoom=13)

    if layer_geojson:

        '''Define map borders'''
        if layer_geojson["bbox"]:
            bbox = layer_geojson["bbox"]
            folium_map.fit_bounds(bounds=bbox, max_zoom=13)

        """Design track"""
        if layer_geojson["geojson"]:
            track = layer_geojson['geojson']['tracklog']
            folium.GeoJson(track, name='Flight', style_function=track_style_function).add_to(folium_map)
            if extra_tracks:
                extra_track_style_function = lambda colour: (
                    lambda x: {'color': colour if x['properties']['Track'] == 'Pre_Goal' else 'grey'})

                for extra_track in extra_tracks:
                    colour = extra_track['colour']
                    folium.GeoJson(extra_track['track'], name=extra_track['name'],
                                   style_function=extra_track_style_function(colour)).add_to(folium_map)

            if thermal_layer:
                thermals = layer_geojson['geojson']['thermals']
                thermal_group = FeatureGroup(name='Thermals', show=False)

                for t in thermals:
                    # icon = Icon(color='blue', icon_color='black', icon='sync-alt', angle=0, prefix='fas')
                    icon = CustomIcon('/app/airscore/static/img/thermal.png')
                    thermal_group.add_child(Marker([t[1], t[0]], icon=icon, popup=Popup(t[2])))

                folium_map.add_child(thermal_group)

            if waypoint_layer:
                waypoints = layer_geojson['geojson']['waypoint_achieved']
                waypoint_group = FeatureGroup(name='Waypoints Taken', show=False)
                for w in waypoints:
                    waypoint_group.add_child(Marker([w[1], w[0]], popup=Popup(w[5])))

                folium_map.add_child(waypoint_group)
    """Design cylinders"""
    if circles:
        for c in circles:
            """create design based on type"""
            if c['type'] == 'launch':
                col = '#996633'
            elif c['type'] == 'speed':
                col = '#00cc00'
            elif c['type'] == 'endspeed':
                col = '#cc3333'
            elif c['type'] == 'restricted':
                col = '#ff0000'
            else:
                col = '#3186cc'

            popup = folium.Popup(f"<b>{c['name']}</b><br>Radius: {str(c['radius_label'])} m.", max_width=300)

            folium.Circle(
                location=(c['latitude'], c['longitude']),
                radius=0.0 + c['radius'],
                popup=popup,
                color=col,
                weight=2,
                opacity=0.8,
                fill=True,
                fill_opacity=0.2,
                fill_color=col
            ).add_to(folium_map)

    """Plot tolerance cylinders"""
    if margin:
        for c in circles:
            """create two circles based on tolerance value"""
            folium.Circle(
                location=(c['latitude'], c['longitude']),
                radius=0.0 + c['radius'] * (1 + margin),
                popup=None,
                color="#44cc44",
                weight=0.75,
                opacity=0.8,
                fill=False
            ).add_to(folium_map)

            folium.Circle(
                location=(c['latitude'], c['longitude']),
                radius=0.0 + c['radius'] * (1 - margin),
                popup=None,
                color="#44cc44",
                weight=0.75,
                opacity=0.8,
                fill=False
            ).add_to(folium_map)

    """Plot waypoints"""
    if points:
        for p in points:
            folium.Marker(
                location=[p['latitude'], p['longitude']],
                popup=p['name'],
                icon=folium.features.DivIcon(
                    icon_size=(20, 20),
                    icon_anchor=(0, 0),
                    html='<div class="waypoint-label">%s</div>' % p['name'],
                )
            ).add_to(folium_map)

    """Design optimised route"""
    if polyline:
        folium.PolyLine(
            locations=polyline,
            weight=1.5,
            opacity=0.75,
            color='#2176bc'
        ).add_to(folium_map)

    if goal_line:
        folium.PolyLine(
            locations=goal_line,
            weight=1.5,
            opacity=0.75,
            color='#800000'
        ).add_to(folium_map)

    if airspace_layer:
        for space in airspace_layer:
            space.add_to(folium_map)

    # path where to save the map
    # folium_map.save('templates/map.html')
    folium.LayerControl().add_to(folium_map)
    folium.plugins.Fullscreen().add_to(folium_map)
    folium.plugins.MeasureControl().add_to(folium_map)
    return folium_map