コード例 #1
0
def index():
    """
    main page with map and all pins
    """
    m = folium.Map(location=[20, 0], zoom_start=3)
    points = db_pg.select_map_data()
    nicknames = db_pg.select_nicknames()

    # MarkerCluster(locations=points, popups=nicknames).add_to(m)
    for i in range(len(points)):
        tooltip_ = Tooltip(nicknames[i], permanent=True)
        if nicknames[i] is None:
            Marker(points[i]).add_to(m)
        else:
            Marker(points[i], tooltip=tooltip_).add_to(m)

    map_html = m._repr_html_()
    if request.method == 'POST':
        # TODO: add new point to map in a different color - red or so
        location = request.form['location']
        nickname = request.form['nickname']
        try:
            decoded_location = geolocator.geocode(location)
            db_pg.insert_into_data(location, decoded_location.latitude,
                                   decoded_location.longitude, nickname)
            # MarkerCluster(locations=[[decoded_location.latitude, decoded_location.longitude]]).add_to(m)
            # map_html = m._repr_html_()
            flash('location successfully added')
            print('new location: ', location, ', ', decoded_location.latitude,
                  ', ', decoded_location.longitude, ', ', datetime.utcnow())
        except AttributeError:
            flash('location not found, try again')
            print('location not found')
        return redirect(url_for('index'))
    return render_template('base.html', map_=map_html)
コード例 #2
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_()
コード例 #3
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
コード例 #4
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:
            locations = validate_locations(locations)
            for i, location in enumerate(locations):
                self.add_child(
                    Marker(location,
                           popup=popups and popups[i],
                           icon=icons and icons[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
コード例 #5
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
コード例 #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
ファイル: marker_cluster.py プロジェクト: tessellateX/wb_maps
    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):
        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
コード例 #9
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
コード例 #10
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
コード例 #11
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 %}
            """)
コード例 #12
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
コード例 #13
0
def test_marker_valid_location():
    m = Map()
    marker = Marker()
    marker.add_to(m)
    with pytest.raises(ValueError):
        m.render()
コード例 #14
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