Exemplo n.º 1
0
 def addMarkers(self):
     """
     Renders markers on class map based on html generated from inter and intra marker functions.
     """
     df1 = pd.DataFrame(self.markerList1)
     df2 = pd.DataFrame(self.markerList2)
     df3 = pd.concat([df1, df2])
     generate = df3.groupby(['lat', 'long']).size().reset_index()
     for index, row in generate.iterrows():
         temp = df3[(df3['lat'] == row['lat'])
                    & (df3['long'] == row['long'])]
         html = ''
         logo = None
         ipix = min(800, sum(temp['ipix']))
         for index, row in temp.iterrows():
             html = html + row['html1'] + row['html2']
             if row['logo'] != None and logo == None:
                 logo = row['logo']
         location = [row['lat'], row['long']]
         iframe = folium.IFrame(html=html,
                                width=self.popupWidth['marker'],
                                height=ipix)
         popup = folium.Popup(iframe, max_width=2650)
         if logo != None:
             icon = CustomIcon(logo,
                               icon_size=(40, 40),
                               popup_anchor=(0, -20))
             m1 = folium.Marker(location=location, popup=popup, icon=icon)
         else:
             m1 = folium.Marker(location=location, popup=popup)
         self.m.add_child(m1)
Exemplo n.º 2
0
 def add_point(self, payload):
     if ((abs(payload.lat - self.last_pt[0]) < BUFFER)
             and (abs(payload.lon - self.last_pt[1]) < BUFFER)):
         point = (payload.lat, payload.lon)
         self.last_pt = point
         callout = payload.getCallout()
         self.fleet.processPayload(payload)
         #redraw map
         my_map = folium.Map(location=[self.center[0], self.center[1]],
                             zoom_start=ZOOM_FACTOR)
         #add markers
         for entity in self.fleet.getEntities():
             # add all markers but the last one
             for i in range(len(entity.points)):
                 pt = entity.points[i]
                 ts = entity.timestamps[i]
                 if (i >= len(entity.points) - 1):
                     marker = folium.Marker(
                         location=[pt[0], pt[1]],
                         icon=CustomIcon('bus.png',
                                         icon_size=(50, 50),
                                         popup_anchor=(0, -10)),
                         popup=folium.Popup(
                             ts,
                             max_width=80,
                             min_width=80,
                             min_height=200,
                             max_height=200))  #.add_to(my_map)
                     my_map.add_child(marker)
             #add lines
             folium.PolyLine(entity.points).add_to(my_map)
         # display map
         my_map.save('index.html')
         if RELOAD: pyautogui.press('f5')  # press the F1 key
Exemplo n.º 3
0
def generate_html_map(destination: str, dict_isochrones: {},
                      array_lon_lat_users: [(float, float)],
                      array_popup_users: [str], array_lon_lat_bars: [
                          (float, float)
                      ], array_popup_bars: [str]) -> str:
    """
    Generates a Folium map
    :return: HTML map as a string
    """
    my_map = folium.Map(
        location=[48.869719, 2.337960],  # Centered on Paris by default
        tiles='https://mts1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',
        API_key=GOOGLEMAPS_TOKEN,
        attr='Google Maps',
        max_zoom=18,
        zoom_start=12)

    # Folium does not support Polygons with holes,
    # so I need to convert it to GeoJSON first to plot it
    for duration, poi_isochrone in dict_isochrones.items():
        polygon = bounding_box_fr.difference(poi_isochrone)
        polygon_geojson = geopandas.GeoSeries([polygon]).__geo_interface__
        folium.features.Choropleth(polygon_geojson,
                                   fill_opacity=0.10,
                                   fill_color='green',
                                   line_weight=0).add_to(my_map)

    # Adding the markers of the locations of the users
    assert len(array_lon_lat_users) == len(array_popup_users)
    for i in range(len(array_lon_lat_users)):
        folium.Marker([array_lon_lat_users[i][1], array_lon_lat_users[i][0]],
                      popup=array_popup_users[i]).add_to(my_map)

    emoji_beer_png = "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/" \
                     "320/facebook/65/clinking-beer-mugs_1f37b.png"

    # Adding the markers of the locations of the bars
    assert len(array_lon_lat_bars) == len(array_popup_bars)
    for i in range(len(array_lon_lat_bars)):
        folium.Marker([array_lon_lat_bars[i][1], array_lon_lat_bars[i][0]],
                      popup=array_popup_bars[i] + "🍻",
                      icon=CustomIcon(emoji_beer_png,
                                      icon_size=(40, 40),
                                      icon_anchor=(20, 20))).add_to(my_map)
    # alternative way: save to a .html file
    my_map.save(destination)
    # Documentation on how to embed a map here: https://github.com/python-visualization/folium/issues/781
    #html_string = my_map.get_root().render()
    return 0
Exemplo n.º 4
0
def getIcon(network=None, theme=None, size=32, returnLnk=False):
    import folium
    from folium.features import CustomIcon
    icon = None
    base = 'https://claudiodonofrio.github.io/res/icons/'    
    if network == 'icos':
        icoLnk = base+'icos_ico.png'
        icon = CustomIcon(icoLnk, icon_size=(size,size))        
        if theme=='AS':
            icoLnk = base+'atc_ico.png'
            icon = CustomIcon(icoLnk, icon_size=(size,size))
        if theme=='ES':
            icoLnk = base+'etc_ico.png'
            icon = CustomIcon(icoLnk, icon_size=(size,size))
        if theme=='OS':
            icoLnk = base+'otc_ico.png'
            icon = CustomIcon(icoLnk, icon_size=(size,size))
    if network == 'neon':
        icoLnk = base+'neon_ico.png'
        icon = CustomIcon(icoLnk, icon_size=(size,size))
    if network == 'ameriflux':
        icoLnk = base+'ameriflux_ico.png'
        icon = CustomIcon(icoLnk, icon_size=(size,size))
    if network == 'asiaflux':
        icoLnk = base+'asiaflux_ico.png'
        icon = CustomIcon(icoLnk, icon_size=(size,size))
    if network == 'lter':
        icoLnk = base+'deims_ico.png'
        icon = CustomIcon(icoLnk, icon_size=(size,size))
    if network == 'fluxnet':
        icoLnk = base+'fluxnet_ico.png'
        icon = CustomIcon(icoLnk, icon_size=(size,size))
    
    if icon is None:        
        icon=folium.Icon(color='blue',icon='info-sign')
    if returnLnk:
        lnk = "<img src='" + icoLnk + "' height='16' width='16'>"
        return lnk
    return icon
Exemplo n.º 5
0
    def __init__(self, coord):
        # Create a map using the Map() function and the coordinates for Charlottesville
        #self.map = folium.Map(location=[38.055148, -78.569812], zoom_start=12)
        if LOAD_DRIVER: self.driver = webdriver.Chrome()
        self.dirpath = os.path.dirname(os.path.abspath(__file__))

        # draw initial map
        self.center = coord
        #self.centers.append([coord[0],coord[1]])
        my_map = folium.Map(location=[coord[0], coord[1]],
                            zoom_start=ZOOM_FACTOR)
        self.last_pt = coord
        my_map.save('index.html')
        if LOAD_DRIVER:
            self.driver.get("file:///" + self.dirpath + "/index.html")

        icon_image = 'bus.png'
        self.icon = CustomIcon('bus.png',
                               icon_size=(50, 50),
                               popup_anchor=(0, -10))
        self.fleet = Fleet()
Exemplo n.º 6
0
    def show_map(coords: list,
                 web_engine_view: QWebEngineView,
                 pop_up: str = None,
                 university=None,
                 kindergarden=None,
                 schools=None,
                 highschools=None,
                 transport=None,
                 charging=None,
                 bicycle=None,
                 groceries=None,
                 services=None,
                 sports=None):
        icon_size = (45, 45)
        small_icon = (40, 40)
        max_width = 400
        bytes_io = BytesIO()
        map_builder = Map(location=coords,
                          tiles="CartoDB positron",
                          zoom_start=16)
        map_icon = CustomIcon(up(up(__file__)) + "/images/marker.png",
                              icon_size=icon_size)

        if kindergarden:
            kindergarden_cluster = MarkerCluster(
                name='barnehage', show=False).add_to(map_builder)
            for pois in kindergarden:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/kindergarden.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(kindergarden_cluster)

        if schools:
            schools_cluster = MarkerCluster(name="barneskole",
                                            show=False).add_to(map_builder)
            for pois in schools:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/schools.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(schools_cluster)

        if highschools:
            highschools_cluster = MarkerCluster(name='vidregåendeskole',
                                                show=False).add_to(map_builder)
            for pois in highschools:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/highschools.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(highschools_cluster)

        if university:
            university_cluster = MarkerCluster(name='hogskole_universitet',
                                               show=False).add_to(map_builder)
            for pois in university:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/university.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(university_cluster)

        if transport:
            transport_cluster = MarkerCluster(name='holdeplass',
                                              show=False).add_to(map_builder)
            for pois in transport:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/transport.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(transport_cluster)

        if charging:
            charging_cluster = MarkerCluster(name='ladeplass',
                                             show=False).add_to(map_builder)
            for pois in charging:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/charging.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(charging_cluster)

        if bicycle:
            bicyle_cluster = MarkerCluster(name='bysykler',
                                           show=False).add_to(map_builder)
            for pois in bicycle:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/bicycle.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(bicyle_cluster)

        shops_cluster = MarkerCluster(name="butikker",
                                      show=False).add_to(map_builder)

        if groceries:
            for pois in groceries:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/groceries.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(shops_cluster)

        if services:
            for pois in services:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/services.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(shops_cluster)

        if sports:
            sports_cluster = MarkerCluster(name='sportsaktiviteter',
                                           show=False).add_to(map_builder)
            for pois in sports:
                pois_icon = CustomIcon(up(up(__file__)) + "/images/sports.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(sports_cluster)

        if pop_up:
            Marker(coords,
                   icon=map_icon,
                   popup=Popup(pop_up,
                               max_width=max_width)).add_to(map_builder)
        else:
            Marker(coords, icon=map_icon).add_to(map_builder)

        TileLayer('CartoDB dark_matter').add_to(map_builder)

        TileLayer('OpenStreetMap').add_to(map_builder)

        TileLayer(
            'https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png',
            attr=
            '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> '
            'contributors, Tiles style by <a href="https://www.hotosm.org/" '
            'target="_blank">Humanitarian OpenStreetMap Team</a> hosted by '
            '<a href="https://openstreetmap.fr/" target="_blank">OpenStreetMap '
            'France</a>',
            name='openstreetmap_hot').add_to(map_builder)

        TileLayer('Stamen Toner').add_to(map_builder)

        TileLayer(
            'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/'
            'tile/{z}/{y}/{x}',
            attr='Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, '
            'USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, '
            'UPR-EGP, and the GIS User Community',
            name='esri_worldimagery').add_to(map_builder)

        TileLayer(
            'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/'
            'tile/{z}/{y}/{x}',
            attr='Tiles &copy; Esri &mdash; Source: Esri, DeLorme, '
            'NAVTEQ, USGS, Intermap, iPC, NRCAN, Esri Japan, METI, '
            'Esri China (Hong Kong), Esri (Thailand), TomTom, 2012',
            name='esri_worldstreetmap').add_to(map_builder)

        TileLayer(
            'https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/'
            'tile/{z}/{y}/{x}',
            attr='Tiles &copy; Esri &mdash; Esri, DeLorme, NAVTEQ, '
            'TomTom, Intermap, iPC, USGS, FAO, NPS, NRCAN, GeoBase, '
            'Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri '
            'China (Hong Kong), and the GIS User Community',
            name='esri_worldtopomap').add_to(map_builder)

        TileLayer(
            'https://tileserver.memomaps.de/tilegen/{z}/{x}/{y}.png',
            attr='Map <a href="https://memomaps.de/">memomaps.de</a> '
            '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, '
            'map data &copy; <a href="https://www.openstreetmap.org/copyright">'
            'OpenStreetMap</a> contributors',
            name='openvkarte').add_to(map_builder)

        TileLayer(
            'https://{s}.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png',
            attr=
            '<a href="https://github.com/cyclosm/cyclosm-cartocss-style/releases" '
            'title="CyclOSM - Open Bicycle render">CyclOSM</a> | Map data: &copy; '
            '<a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> '
            'contributors',
            name='cyclosm').add_to(map_builder)

        TileLayer(
            'http://tile.mtbmap.cz/mtbmap_tiles/{z}/{x}/{y}.png',
            attr=
            '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> '
            'contributors &amp; USGS',
            name='mtbmap').add_to(map_builder)

        railway_feature = FeatureGroup('jernbane_tbane', show=False)
        TileLayer(
            'https://{s}.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png',
            attr=
            'Map data: &copy; <a href="https://www.openstreetmap.org/copyright'
            '">OpenStreetMap</a> contributors | Map style: &copy; <a href='
            '"https://www.OpenRailwayMap.org">OpenRailwayMap</a> (<a href='
            '"https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)',
            name='openrailwaymap').add_to(railway_feature)
        railway_feature.add_to(map_builder)

        safecast_feature = FeatureGroup('miljø', show=False)
        TileLayer(
            'https://s3.amazonaws.com/te512.safecast.org/{z}/{x}/{y}.png',
            attr=
            'Map data: &copy; <a href="https://www.openstreetmap.org/copyright">'
            'OpenStreetMap</a> contributors | Map style: &copy; '
            '<a href="https://blog.safecast.org/about/">SafeCast</a> '
            '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)',
            name='safecast').add_to(safecast_feature)
        safecast_feature.add_to(map_builder)

        trails_feature = FeatureGroup('turstil', show=False)
        TileLayer(
            'https://tile.waymarkedtrails.org/hiking/{z}/{x}/{y}.png',
            attr=
            'Map data: &copy; <a href="https://www.openstreetmap.org/copyright">'
            'OpenStreetMap</a> contributors | Map style: &copy; '
            '<a href="https://waymarkedtrails.org">waymarkedtrails.org</a> '
            '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)',
            name='waymarkedtrails_hiking').add_to(trails_feature)
        trails_feature.add_to(map_builder)

        cycling_feature = FeatureGroup('sykkelsti', show=False)
        TileLayer(
            'https://tile.waymarkedtrails.org/cycling/{z}/{x}/{y}.png',
            attr=
            'Map data: &copy; <a href="https://www.openstreetmap.org/copyright">'
            'OpenStreetMap</a> contributors | Map style: &copy; '
            '<a href="https://waymarkedtrails.org">waymarkedtrails.org</a> '
            '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)',
            name='waymarkedtrails_cycling').add_to(cycling_feature)
        cycling_feature.add_to(map_builder)

        slopes_feature = FeatureGroup('bakker_helning', show=False)
        TileLayer(
            'https://tile.waymarkedtrails.org/slopes/{z}/{x}/{y}.png',
            attr=
            'Map data: &copy; <a href="https://www.openstreetmap.org/copyright">'
            'OpenStreetMap</a> contributors | Map style: &copy; '
            '<a href="https://waymarkedtrails.org">waymarkedtrails.org</a> '
            '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)',
            name='waymarkedtrails_slopes').add_to(slopes_feature)
        slopes_feature.add_to(map_builder)

        LayerControl().add_to(map_builder)
        map_builder.save(bytes_io, close_file=False)
        web_engine_view.setHtml(bytes_io.getvalue().decode())
        web_engine_view.show()
Exemplo n.º 7
0
Arquivo: map.py Projeto: zhuqiuhui/GPS
folium.CircleMarker([36.9846766666667, 111.820881666667],
                    radius=30,
                    popup='Stay points example',
                    color='#3186cc',
                    fill_color='#3186cc').add_to(map_osm)
# 标记方式六(可以以任意多边形来标记)
folium.RegularPolygonMarker(
    [36.9842, 111.8207],
    popup='point_4',
    fill_color='#132b5e',
    number_of_sides=4,  # 表示正几边形,如3表示正三角形
    radius=10).add_to(map_osm)

# 可以在完整的一段轨迹中添加“自行车”、“TAXI”、“步行”、“公交车”图标
icon = CustomIcon('pic/bike.jpg',
                  icon_size=(38, 40),
                  icon_anchor=(22, 94),
                  popup_anchor=(-3, -76))
marker = folium.Marker(location=[36.9841, 111.8215], icon=icon, popup='bike')
map_osm.add_child(marker)

# draw line(在两个经纬诚度之间连线)
kw = dict(opacity=1.0, weight=2)
line1 = folium.PolyLine(locations=[(36.9841, 111.8194), (36.9841, 111.8205)],
                        color='red',
                        **kw)
map_osm.add_child(line1)

# draw trajectory1(轨迹画出)
point_lat = [36.9860, 36.9861, 36.9860, 36.9858, 36.9857, 36.9856, 36.9855]
point_lon = [
    111.8217, 111.8213, 111.8211, 111.8212, 111.8213, 111.8212, 111.8212
Exemplo n.º 8
0
            (shop['lat'], shop['lon']),
            radius=5,
            color=shop['color'],
            opacity=0.6,
            fill_color=shop['color'],
            fill_opacity=0.4,
            tooltip=note,
        ).add_to(m)
    msg = "コンビニ別に色分けしました"

if page == 'CustomIcon':
    for _, shop in df_shops.iterrows():
        note = "<b>{}</b><br>{}".format(shop['名称'], shop['住所'])
        folium.Marker(
            (shop['lat'], shop['lon']),
            icon=CustomIcon(shop['icon'], icon_size=(20, 20)),
            tooltip=note,
        ).add_to(m)
    msg = "アイコンもカスタマイズできますよ"

elif page == 'geojson':
    with open('410004saga.geojson') as f:
        saga = json.load(f)
    folium.GeoJson(
        saga,
        name="GST_NAME",
    ).add_to(m)
    msg = "geojsonも扱えます"

# 地図表示 Folium map in Streamlit
folium_static(m)
Exemplo n.º 9
0
def load_map(area, datafile, generate_ids, return_html=True):
    """
    Create a map for a bouldering zone that shows the GEOJSON data, names and
    links to video playlists of its sectors as well as the parking areas. All
    this data should be provided via a JSON file
    """
    generate_ids.reset_seed()
    area_data = {}
    with open(datafile, encoding='utf-8') as data:
        area_data = json.load(data)

    area_map = folium.Map(
        location=[area_data['latitude'], area_data['longitude']],
        zoom_start=area_data['zoom'])
    area_map._id = generate_ids.next_id()  # reassign id
    for child in area_map._children.values():
        child._id = generate_ids.next_id()
    tile_layer = folium.TileLayer(
        tiles=
        'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
        name='Satellite',
        attr=
        'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
    )
    tile_layer._id = generate_ids.next_id()  # reassign id
    tile_layer.add_to(area_map)

    # Add fullscreen button to map
    fs = Fullscreen()
    fs._id = generate_ids.next_id()
    fs.add_to(area_map)

    sectors = area_data['sectors']
    # Create a Folium feature group for this layer, since we will be displaying multiple layers
    sector_lyr = folium.FeatureGroup(name='Zone Markers')
    sector_lyr._id = generate_ids.next_id()  # reassign id

    for sector in sectors:
        if not sector['sector_data'] or not sector['link']:
            continue
        sector_map = folium.GeoJson(
            os.path.dirname(os.path.abspath(datafile)) + sector['sector_data'],
            name=sector['name'],
            tooltip=sector['name'],
            style_function=lambda x: {
                'color': x['properties']['stroke'],
                'weight': x['properties']['stroke-width'],
                'opacity': SECTOR_OPACITY,
                'fillColor': x['properties']['stroke'],
            })
        sector_map._id = generate_ids.next_id()  # reassign id
        sector_html = utils.js_helpers.generate_sector_html(
            sector['name'], sector['link'])
        sector_popup = folium.Popup(sector_html,
                                    max_width=POPUP_WIDTH,
                                    min_width=POPUP_WIDTH)
        sector_popup._id = generate_ids.next_id()  # reassign id
        for child in sector_popup._children.values():
            child._id = generate_ids.next_id()

        sector_map.add_child(sector_popup)

        sector_lyr.add_child(sector_map)

    # Parking areas
    for parking in area_data['parkings']:
        parking_icon = CustomIcon('static/images/icons/parking.png',
                                  icon_size=(ICON_SIZE, ICON_SIZE))
        parking_icon._id = generate_ids.next_id()  # reassign id
        parking_marker = folium.Marker(
            location=[
                parking['parking_latitude'], parking['parking_longitude']
            ],
            popup=utils.js_helpers.generate_parking_html(
                [parking['parking_latitude'], parking['parking_longitude']]),
            tooltip='Parking',
            icon=parking_icon)
        parking_marker._id = generate_ids.next_id()  # reassign id
        for child in parking_marker._children.values():
            child._id = generate_ids.next_id()

        sector_lyr.add_child(parking_marker)

    # Approximation
    if area_data.get('approximation', None) is not None:
        import gpxpy
        import gpxpy.gpx

        approximation_geojson = {
            'type': 'Feature',
            'properties': {
                'stroke': '#1f1a95',
                'stroke-opacity': 1,
                'stroke-width': 2
            },
            'geometry': {
                'type': 'LineString',
                'coordinates': []
            }
        }

        gpx_path = 'data/zones/' + area + '/' + area_data.get('approximation')
        with open(gpx_path, 'r') as gpx_file:
            gpx = gpxpy.parse(gpx_file)
            for track in gpx.tracks:
                for segment in track.segments:
                    for point in segment.points:
                        approximation_geojson['geometry'][
                            'coordinates'].append(
                                [point.longitude, point.latitude])

        zone_approximation = folium.GeoJson(
            approximation_geojson,
            name='Approximation',
            tooltip=APPROX_PLACEHOLDER,
            style_function=lambda x: {
                'color': x['properties']['stroke'],
                'weight': x['properties']['stroke-width'],
                'opacity': SECTOR_OPACITY,
                'fillColor': x['properties']['stroke'],
            })
        zone_approximation._id = generate_ids.next_id()  # reassign id

        zone_approx_html = utils.js_helpers.generate_file_download_html(
            area, area_data.get('approximation'), 'Track')

        track_popup = folium.Popup(zone_approx_html,
                                   max_width=POPUP_WIDTH,
                                   min_width=POPUP_WIDTH)
        track_popup._id = generate_ids.next_id()  # reassign id

        for child in track_popup._children.values():
            child._id = generate_ids.next_id()

        zone_approximation.add_child(track_popup)

        sector_lyr.add_child(zone_approximation)

    # Sectors
    zoomed_out_lyr = folium.FeatureGroup(name='Sector Markers')
    zoomed_out_lyr._id = generate_ids.next_id()  # reassign id
    zoomed_out_icon = CustomIcon('static/images/marker/marker.png',
                                 icon_size=(MARKER_SIZE, MARKER_SIZE))
    zoomed_out_icon._id = generate_ids.next_id()  # reassign id
    sectors_marker = folium.Marker(
        location=[area_data['latitude'], area_data['longitude']],
        tooltip=area_data['name'],
        icon=zoomed_out_icon)
    sectors_marker._id = generate_ids.next_id()  # reassign id
    zoomed_out_lyr.add_child(sectors_marker)

    area_map.add_child(zoomed_out_lyr)
    area_map.add_child(sector_lyr)

    layer_control = folium.LayerControl()
    layer_control._id = generate_ids.next_id()  # reassign id
    layer_control.add_to(area_map)

    # Since folium does not support all the functionalities we need
    # we obtain them by injecting JavaScript code in the map html
    map_html = area_map.get_root().render()
    map_html = utils.js_helpers.make_layer_that_hides(map_html,
                                                      area_map.get_name(),
                                                      sector_lyr.get_name(),
                                                      DEFAULT_AREA_ZOOM)
    map_html = utils.js_helpers.make_layer_that_hides(
        map_html, area_map.get_name(), zoomed_out_lyr.get_name(),
        DEFAULT_AREA_ZOOM, False, True)
    # Zoom into area when clicking
    map_html = utils.js_helpers.zoom_on_click(map_html, area_map.get_name(),
                                              sectors_marker.get_name(),
                                              DEFAULT_AREA_ZOOM + 1)

    map_html = utils.js_helpers.enable_links_from_iframe(map_html)
    map_html = utils.js_helpers.replace_maps_placeholder(map_html)
    map_html = utils.js_helpers.replace_approx_placeholders_for_translations(
        map_html, APPROX_PLACEHOLDER)
    # Avoid zooming in when clicking on a sector area
    map_html = utils.js_helpers.remove_geojson_zoom_on_click(map_html)
    # replace the ids of all the html tags
    map_html = utils.js_helpers.replace_tag_ids(map_html, ['html'],
                                                generate_ids)
    return map_html if return_html else area_map
Exemplo n.º 10
0
def load_general_map(datafiles, generate_ids, return_html=True):
    """
    Create a map that contains all the zones provided by the list of datafiles
    i.e. all areas combined in one map. This map only shows the markers that 
    indicate an existing area.
    """
    generate_ids.reset_seed()
    area_map = folium.Map(location=[-23.0390625, -18.299051014581817],
                          zoom_start=2)
    area_map._id = generate_ids.next_id()  # reassign id
    for child in area_map._children.values():
        child._id = generate_ids.next_id()

    tile_layer = folium.TileLayer(
        tiles=
        'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
        name='Satellite',
        attr=
        'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
    )
    tile_layer._id = generate_ids.next_id()  # reassign id
    tile_layer.add_to(area_map)

    # Add fullscreen button to map
    fs = Fullscreen()
    fs._id = generate_ids.next_id()
    fs.add_to(area_map)

    # layers = []
    sectors_markers = []
    placeholders = []

    # Sectors layer
    zoomed_out_lyr = folium.FeatureGroup(name='Sector Markers')
    zoomed_out_lyr._id = generate_ids.next_id()  # reassign id
    areas_cluster = MarkerCluster()
    areas_cluster._id = generate_ids.next_id()  # reassign id

    for areadatafile in datafiles:
        area_data = {}
        with open(areadatafile, encoding='utf-8') as data:
            area_data = json.load(data)

        # sectors = area_data['sectors']
        # # Create a Folium feature group for this layer, since we will be displaying multiple layers
        # sector_lyr = folium.FeatureGroup(name='sectors_layer')
        # for sector in sectors:
        #     sector_map = folium.GeoJson(
        #         os.path.dirname(os.path.abspath(areadatafile)) +
        #         sector['sector_data'],
        #         name=sector['name'],
        #         tooltip=sector['name'],
        #         style_function=lambda x: {
        #             'color': x['properties']['stroke'],
        #             'weight': x['properties']['stroke-width'],
        #             'opacity': SECTOR_OPACITY,
        #             'fillColor': x['properties']['stroke'],
        #         }
        #     )
        #     sector_html = helpers.generate_sector_html(
        #         sector['name'], sector['link'])
        #     sector_map.add_child(folium.Popup(
        #         sector_html, max_width=POPUP_WIDTH, min_width=POPUP_WIDTH))

        #     sector_lyr.add_child(sector_map)

        # Parking
        # for parking in area_data['parkings']:
        #     parking_marker = folium.Marker(
        #         location=[parking['parking_latitude'],
        #                   parking['parking_longitude']],
        #         popup=helpers.generate_parking_html([parking['parking_latitude'],
        #                                              parking['parking_longitude']]),
        #         tooltip='Parking',
        #         icon=folium.Icon(color='red', icon='info-sign')
        #     )

        #     sector_lyr.add_child(parking_marker)

        zoomed_out_icon = CustomIcon('static/images/marker/marker.png',
                                     icon_size=(MARKER_SIZE, MARKER_SIZE))
        zoomed_out_icon._id = generate_ids.next_id()  # reassign id
        html_redirect, _ = os.path.splitext(
            os.path.basename(os.path.normpath(areadatafile)))
        area_name = os.path.splitext(os.path.basename(areadatafile))[0]
        placeholder = area_name + PLACEHOLDER
        popup_html = folium.Html(utils.js_helpers.generate_area_popup_html(
            area_data['name'], area_name, html_redirect, placeholder),
                                 script=True)
        popup_html._id = generate_ids.next_id()  # reassign id
        zone_popup = folium.Popup(
            popup_html,
            max_width=max(len(area_data['name']), len(BETA_VIDEOS_TEXT)) * 10)
        zone_popup._id = generate_ids.next_id()  # reassign id
        placeholders.append(placeholder)

        sectors_marker = folium.Marker(
            location=[area_data['latitude'], area_data['longitude']],
            tooltip=area_data['name'],
            icon=zoomed_out_icon,
            popup=zone_popup,
        )
        sectors_marker._id = generate_ids.next_id()  # reassign id
        sectors_markers += [sectors_marker]
        # Group areas' markers when zoomed out
        areas_cluster.add_child(sectors_marker)
        zoomed_out_lyr.add_child(areas_cluster)

        area_map.add_child(zoomed_out_lyr)
        # area_map.add_child(sector_lyr)
        # layers += [(sector_lyr, zoomed_out_lyr)]

    layer_control = folium.LayerControl()
    layer_control._id = generate_ids.next_id()  # reassign id
    layer_control.add_to(area_map)

    # Since folium does not support all the functionalities we need
    # we obtain them by injecting or editing JavaScript code in the map html
    map_html = area_map.get_root().render()
    # for sector_lyr, zoomed_out_lyr in layers:
    #     # Hide or show layers depending on the zoom level
    #     map_html = helpers.make_layer_that_hides(
    #         map_html, area_map.get_name(), sector_lyr.get_name(), DEFAULT_AREA_ZOOM, False, False)
    #     map_html = helpers.make_layer_that_hides(
    #         map_html, area_map.get_name(), zoomed_out_lyr.get_name(), DEFAULT_AREA_ZOOM, True, True)
    #     # Zoom into area when clicking
    #     for marker in sectors_markers:
    #         map_html = helpers.zoom_on_click(
    #             map_html, area_map.get_name(), marker.get_name(), DEFAULT_AREA_ZOOM+1)
    map_html = utils.js_helpers.replace_custom_placeholders(
        map_html, placeholders)
    map_html = utils.js_helpers.replace_tag_ids(map_html, ['html'],
                                                generate_ids)
    return map_html if return_html else area_map
Exemplo n.º 11
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
Exemplo n.º 12
0
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
Exemplo n.º 13
0
url1 = ('logo2.JPG')
url2 = ('C.JPG')
url3 = ('caption2.JPG')

icon_image1 = ('1.jpg')
icon_image2 = ('2.jpg')
icon_image3 = ('3.jpg')
icon_image4 = ('4.jpg')
icon_image5 = ('5.jpg')
icon_image6 = ('6.jpg')
icon_image7 = ('7.jpg')

icon1 = CustomIcon(
    icon_image1,
    icon_size=(90, 70),  #size of image
    icon_anchor=(5, -18)  #right / left image
)

icon2 = CustomIcon(icon_image2, icon_size=(90, 70), icon_anchor=(5, -16))

icon3 = CustomIcon(icon_image3, icon_size=(90, 70), icon_anchor=(5, -15))

icon4 = CustomIcon(icon_image4, icon_size=(90, 70), icon_anchor=(5, -13))

icon5 = CustomIcon(icon_image5, icon_size=(90, 70), icon_anchor=(5, -8))

icon6 = CustomIcon(icon_image6, icon_size=(90, 70), icon_anchor=(6, -13))

icon7 = CustomIcon(icon_image7, icon_size=(90, 70), icon_anchor=(7, 5))
Exemplo n.º 14
0
        bar.update(1)

# Print Total users and online users
print('\nFound %i users of wich %i are online..' % (int(c), int(on)))

# Create World Map
print('\nGenerating Map...')
folium_map = folium.Map(location=[51.862890, 4.535700],
                        zoom_start=8,
                        tiles="OpenStreetMap")  # Define Map

for gebr in loc:
    try:
        gebr = gebr.split(':')
        icon = CustomIcon(
            'https://kite.wildix.com/' + org + '/' + gebr[2] + '/api/avatar' %
            (),
            icon_size=(45, 45))  # Use Kite User's profile picture on map
        marker = folium.Marker(location=[gebr[3], gebr[4]],
                               popup='<b>%s (%s)</b><br><br>%s' %
                               (gebr[0], gebr[2], gebr[1]),
                               tooltip=gebr[0],
                               fill=True,
                               icon=icon).add_to(folium_map)  # Set marker
    except Exception:
        pass  # If error, skip this users on map

folium_map.save("./user_map.html")  # Save map in current folder
webbrowser.open_new_tab(
    'file://' + os.path.realpath('user_map.html'))  # Open map when generated

# Finished, Exiting...
Exemplo n.º 15
0
def geovizTrafficMatrix(MatrixOrList,
                        GCL=pd.DataFrame(),
                        savefile='Map.html',
                        Src=list(range(1000)),
                        Dst=list(range(1000))):

    #Initilize variables and edit some strings in geo info file to make it look nicer
    plt.ioff()
    targetfile = 'asnum2.csv'
    LoA = MatrixOrList
    pd.set_option('display.max_colwidth', -1)

    ASNums = pd.read_csv(targetfile)
    ASNums['organization'] = ASNums['organization'].str.replace("'", "")

    if len(GCL) > 0:
        GCL['organization'] = GCL['organization'].str.replace("'", "")

    tempdf = pd.DataFrame()
    SelfList = []
    ASUnique = []
    DupList = []
    removelist = []

    m = folium.Map(location=[29.7176, -95.4188],
                   tiles='OpenStreetMap',
                   zoom_start=5)

    #Seperate into the One Location,Bidirection or Unidirectional Lists

    mc = 0

    for x in range(0, len(LoA)):

        if LoA[x - mc].get('asSrc') == LoA[x - mc].get('asDst'):
            if LoA[x - mc] not in SelfList:
                SelfList.append(LoA[x - mc])
                del LoA[x - mc]
                mc = mc + 1

    for x in range(0, len(LoA)):

        if LoA[x].get('asSrc') not in DupList:
            DupList.append(LoA[x].get('asSrc'))
            d = {"asNum": int(LoA[x].get('asSrc'))}
            if d not in ASUnique:
                ASUnique.append(d)

        if LoA[x].get('asDst') not in DupList:
            DupList.append(LoA[x].get('asDst'))
            d = {"asNum": int(LoA[x].get('asDst'))}
            if LoA[x].get('asDst') not in ASUnique:
                ASUnique.append(d)

    for x in SelfList:
        for y in range(0, len(ASUnique)):
            if int(x.get('asSrc')) == ASUnique[y]['asNum']:
                removelist.append(y)

    removelist = set(removelist)
    removelist = sorted(removelist, reverse=True)

    for x in removelist:
        del ASUnique[x]

#Make Markers for all non self-talkers

    for x in ASUnique:

        tempdf = pd.DataFrame()

        if len(GCL) > 0:
            tempdf = GCL[(GCL.asNum == int(x.get('asNum')))].reset_index()

        if (len(tempdf) == 0):
            tempdf = ASNums[(ASNums.asNum == int(
                x.get('asNum')))].reset_index()

        if len(tempdf) > 0:
            temp = tempdf.loc[0]

            asnum = temp.asNum

            icon_image = 'http://engsrvdb00.utep.edu/amis/images/as_images/%s.png' % asnum

            x['latitude'] = temp.latitude
            x['longitude'] = temp.longitude
            x['Logo'] = '<img src="' + icon_image + '" height="50" width="50">'
            x['Organization'] = temp.organization

    if len(ASUnique) > 0:
        qq = pd.DataFrame(ASUnique)
        qq['asNum'] = qq['asNum'].astype(int)
        MarkerLat = qq['latitude'].unique()
        MarkerLong = qq['longitude'].unique()

        for lat in MarkerLat:
            for lng in MarkerLong:
                dff = pd.DataFrame()
                dff = qq[(qq['latitude'] == lat)
                         & (qq['longitude'] == lng)].reset_index(drop=True)

                if len(dff) == 1:
                    asnum = dff['asNum'][0]
                    icon_image = 'http://engsrvdb00.utep.edu/amis/images/as_images/%s.png' % asnum

                    html = dff.to_html(escape=False).replace(
                        '<td>', '<td align = "center">').replace(
                            '<thead>', '<thead align = "center">').replace(
                                'border="1"', 'border="5"').replace(
                                    '<tr style="text-align: right;">',
                                    '<tr style="text-align: center;">')

                    location = [lat, lng]
                    iframe = folium.IFrame(html=html, width=450, height=110)
                    popup = folium.Popup(iframe, max_width=2650)

                    try:
                        urllib.request.urlretrieve(icon_image)

                        icon = CustomIcon(
                            icon_image,
                            icon_size=(40, 40),
                            popup_anchor=(0, -20),
                        )

                        m1 = folium.Marker(location=location,
                                           popup=popup,
                                           icon=icon)

                    except urllib.error.HTTPError:
                        m1 = folium.Marker(location=location, popup=popup)
                    m.add_child(m1)

                if len(dff) > 1:

                    ipix = 75 * len(dff)
                    ipix = min(ipix, 600)

                    html = dff.to_html(escape=False).replace(
                        '<td>', '<td align = "center">').replace(
                            '<thead>', '<thead align = "center">').replace(
                                'border="1"', 'border="5"').replace(
                                    '<tr style="text-align: right;">',
                                    '<tr style="text-align: center;">')

                    location = [lat, lng]
                    iframe = folium.IFrame(html=html, width=450, height=ipix)
                    popup = folium.Popup(iframe, max_width=2650)

                    for p in range(0, len(dff)):
                        asnum = dff['asNum'][p]
                        icon_image = 'http://engsrvdb00.utep.edu/amis/images/as_images/%s.png' % asnum
                        try:
                            urllib.request.urlretrieve(icon_image)

                            icon = CustomIcon(
                                icon_image,
                                icon_size=(40, 40),
                                popup_anchor=(0, -20),
                            )

                            m1 = folium.Marker(location=location,
                                               popup=popup,
                                               icon=icon)
                            break

                        except urllib.error.HTTPError:
                            if p == len(dff) - 1:
                                m1 = folium.Marker(location=location,
                                                   popup=popup)

                    m.add_child(m1)

#Make Markers for all the Self-Talkers

    for x in SelfList:

        tempdf = pd.DataFrame()

        if int(x.get('bytes')) > 0:
            color = 'green'
        else:
            color = 'gray'

        if len(GCL) > 0:
            tempdf = GCL[(GCL.asNum == int(x.get('asSrc')))].reset_index()

        if (len(tempdf) == 0):
            tempdf = ASNums[(ASNums.asNum == int(
                x.get('asSrc')))].reset_index()

        if len(tempdf) > 0:
            temp = tempdf.loc[0]

            asnum = temp.asNum

            icon_image = 'http://engsrvdb00.utep.edu/amis/images/as_images/%s.png' % asnum

            x['latitude'] = temp.latitude
            x['longitude'] = temp.longitude
            #x['Logo'] = '<img src="' + icon_image + '" height="50" width="50">'
            x['Organization'] = temp.organization
            x['packets'] = int(x.get('packets'))
            x['bytes'] = int(x.get('bytes'))

    if len(SelfList) > 0:
        qq = pd.DataFrame(SelfList)
        qq['asSrc'] = qq['asSrc'].astype(int)
        qq['asDst'] = qq['asDst'].astype(int)
        MarkerLat = qq['latitude'].unique()
        MarkerLong = qq['longitude'].unique()

        for lat in MarkerLat:
            for lng in MarkerLong:
                dff = pd.DataFrame()
                dff = qq[(qq['latitude'] == lat)
                         & (qq['longitude'] == lng)].reset_index(drop=True)
                dff = dff.drop(['id'], axis=1)

                if len(dff) == 1:
                    asnum = dff['asSrc'][0]
                    icon_image = 'http://engsrvdb00.utep.edu/amis/images/as_images/%s.png' % asnum

                    html = dff.to_html(escape=False).replace(
                        '<td>', '<td align = "center">').replace(
                            '<thead>', '<thead align = "center">').replace(
                                'border="1"', 'border="5"').replace(
                                    '<tr style="text-align: right;">',
                                    '<tr style="text-align: center;">')
                    location = [lat, lng]
                    iframe = folium.IFrame(html=html, width=1000, height=110)
                    popup = folium.Popup(iframe, max_width=2650)

                    try:
                        urllib.request.urlretrieve(icon_image)

                        icon = CustomIcon(
                            icon_image,
                            icon_size=(40, 40),
                            popup_anchor=(0, -20),
                        )

                        m1 = folium.Marker(location=location,
                                           popup=popup,
                                           icon=icon)

                    except urllib.error.HTTPError:
                        m1 = folium.Marker(location=location, popup=popup)

                    m.add_child(m1)

                if len(dff) > 1:

                    ipix = 75 * len(dff) + 200
                    ipix = min(ipix, 600)

                    if 'App' in dff.columns:
                        h = MakeHist(dff)

                    if len(dff) > 3:
                        dff = dff.sort_values(
                            by=['bytes'],
                            ascending=False).reset_index(drop=True)
                        dff = dff.iloc[0:3]

                    html = dff.to_html(escape=False).replace(
                        '<td>', '<td align = "center">').replace(
                            '<thead>', '<thead align = "center">').replace(
                                'border="1"', 'border="5"').replace(
                                    '<tr style="text-align: right;">',
                                    '<tr style="text-align: center;">')
                    html = h + html
                    h = ''

                    location = [lat, lng]
                    iframe = folium.IFrame(html=html, width=1000, height=ipix)
                    popup = folium.Popup(iframe, max_width=2650)

                    for p in range(0, len(dff)):
                        asnum = dff['asSrc'][p]
                        icon_image = 'http://engsrvdb00.utep.edu/amis/images/as_images/%s.png' % asnum
                        try:
                            urllib.request.urlretrieve(icon_image)

                            icon = CustomIcon(
                                icon_image,
                                icon_size=(40, 40),
                                popup_anchor=(0, -20),
                            )

                            m1 = folium.Marker(location=location,
                                               popup=popup,
                                               icon=icon)
                            break

                        except urllib.error.HTTPError:
                            if p == len(dff) - 1:
                                m1 = folium.Marker(location=location,
                                                   popup=popup)

                    m.add_child(m1)

    for x in LoA:
        tempdf = pd.DataFrame()

        if len(GCL) > 0:
            tempdf = GCL[(GCL.asNum == int(x.get('asSrc')))].reset_index()

        if (len(tempdf) == 0):
            tempdf = ASNums[(ASNums.asNum == int(
                x.get('asSrc')))].reset_index()

        if len(tempdf) > 0:
            temp = tempdf.loc[0]

            asnum = temp.asNum

            icon_image = 'http://engsrvdb00.utep.edu/amis/images/as_images/%s.png' % asnum

            x['Srclatitude'] = temp.latitude
            x['Srclongitude'] = temp.longitude
            #x['SrcLogo'] = '<img src="' + icon_image + '" height="50" width="50">'
            x['SrcOrganization'] = temp.organization

        tempdf = pd.DataFrame()

        if len(GCL) > 0:
            tempdf = GCL[(GCL.asNum == int(x.get('asDst')))].reset_index()

        if (len(tempdf) == 0):
            tempdf = ASNums[(ASNums.asNum == int(
                x.get('asDst')))].reset_index()

        if len(tempdf) > 0:
            temp = tempdf.loc[0]

            asnum = temp.asNum

            icon_image = 'http://engsrvdb00.utep.edu/amis/images/as_images/%s.png' % asnum

            x['Dstlatitude'] = temp.latitude
            x['Dstlongitude'] = temp.longitude
            #x['DstLogo'] = '<img src="' + icon_image + '" height="50" width="50">'
            x['DstOrganization'] = temp.organization

    sod = 'var bigdict = {'

    if len(LoA) > 0:
        zz = pd.DataFrame(LoA)
        zz['asSrc'] = zz['asSrc'].astype(int)
        zz['asDst'] = zz['asDst'].astype(int)
        for i in range(len(zz) - 1, -1, -1):
            Srclat = zz['Srclatitude'][i]
            Srclong = zz['Srclongitude'][i]
            Dstlat = zz['Dstlatitude'][i]
            Dstlong = zz['Dstlongitude'][i]
            location = [Srclat, Srclong]
            location2 = [Dstlat, Dstlong]
            dff = pd.DataFrame()
            dff = zz[(((zz['Srclatitude'] == Srclat) &
                       (zz['Srclongitude'] == Srclong)) &
                      ((zz['Dstlatitude'] == Dstlat) &
                       (zz['Dstlongitude'] == Dstlong))) |
                     (((zz['Srclatitude'] == Dstlat) &
                       (zz['Srclongitude'] == Dstlong)) &
                      ((zz['Dstlatitude'] == Srclat) &
                       (zz['Dstlongitude'] == Srclong)))].reset_index(
                           drop=True)
            if len(dff) > 0:

                ipix = 75 * len(dff)
                ipix = max(ipix, 130)

                if int(dff['bytes'].max()) > 0:
                    color = 'green'
                    opacity = 1
                else:
                    color = 'grey'
                    opacity = 0.25

                dff = dff.drop(['id'], axis=1)

                if len(dff) > 1:
                    if 'App' in dff.columns:
                        ipix = ipix + 400
                        h = MakeHist(dff)

                if len(dff) > 3:
                    dff = dff.sort_values(
                        by=['bytes'], ascending=False).reset_index(drop=True)
                    dff = dff.iloc[0:3]

                html = dff.to_html(escape=False).replace(
                    '<td>', '<td align = "center">').replace(
                        '<thead>', '<thead align = "center">').replace(
                            'border="1"', 'border="5"').replace(
                                '<tr style="text-align: right;">',
                                '<tr style="text-align: center;">')
                html = h + html
                html = html.replace('\n', '')
                h = ''

                ipix = min(ipix, 600)
                iframe = folium.IFrame(html=html, width=1300, height=ipix)
                popup = folium.Popup(iframe, max_width=2650)
                sod = sod + "'" + str(Srclat) + ',' + str(Srclong) + ',' + str(
                    Dstlat) + ',' + str(
                        Dstlong) + "'" + ' : ' + "`" + html + "`" + ','

#Save map on server to be served to user

    if '.html' not in savefile:
        savefile = savefile + '.html'

    sod = sod[0:-1]
    sod = sod + '};'
    m.save(savefile)
    jscode = findMarkers(savefile, sod)
    with open(savefile, "a") as f:
        f.write(jscode)
        f.write("<title>Ra Map - %s</title>" % savefile[:-5])
    return sod
Exemplo n.º 16
0
    [38.3375, 31.4050],
    [38.3375, 31.4010],
]
folium.PolyLine(smooth_factor=50,
                locations=coordinates,
                color='green',
                tooltip='Şeker Pancarı Tarlası',
                weight=5).add_to(m)

url = 'https://img.icons8.com/color/48/000000/{}'.format  #Belli bir koordinata resim ekle
icon_image = url('')
shadow_image = url('beet.png')
icon = CustomIcon(icon_image,
                  icon_size=(38, 95),
                  icon_anchor=(22, 94),
                  shadow_image=shadow_image,
                  shadow_size=(50, 64),
                  shadow_anchor=(4, 62),
                  popup_anchor=(-3, -76))
marker = folium.Marker(location=[38.3390, 31.4026],
                       icon=icon,
                       popup='Şeker Pancarı Tarlası')
m.add_child(marker)
""""
url = ('https://raw.githubusercontent.com/SECOORA/static_assets/'  #Kuzey Yıldızı
       'master/maps/img/rose.png')
FloatImage(url, bottom=0, left=0).add_to(m)
"""

folium.raster_layers.TileLayer(  # Farklı tür harita desenleri
    tiles='http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',