예제 #1
0
def color(r):
    if 1 <= r < 5:
        return 'green'
    elif 5 <= r < 10:
        return 'orange'
    elif 10 <= r < 15:
        return 'red'
    else:
        return 'blue'


html = """<div style = "font-size:large;font-color:yellow;font-weight:bolder,font-family:Monospace">Name: {}<br/>Rank: {}<br/>Location: {}, {}, {}</div>"""

map = folium.Map(location=[27.7, 85.3], zoom_start=80, tiles="OpenStreetMap")

fg = folium.FeatureGroup(name="My Map")

for lt, ln, name, rn, p, st, cou in zip(lat, lon, name, rn, p, st, cou):
    iframe = folium.IFrame(html=html.format(str(name), str(rn), str(p),
                                            str(st), str(cou)),
                           width=300,
                           height=200)
    fg.add_child(
        folium.Marker(location=[lt, ln],
                      popup=folium.Popup(iframe),
                      icon=folium.Icon(color=color(rn))))

map.add_child(fg)

map.save("Map1.html")
예제 #2
0
파일: app.py 프로젝트: CiSigep/webmap
<div>Height: %s m</div>
"""


def color_picker(elevation):
    if elevation < 1000:
        return "lightblue"
    elif 1000 <= elevation < 3000:
        return "orange"
    else:
        return "red"


# Add volcano data to the map
for lt, ln, nm, el in zip(lat, lon, name, elev):
    iframe = folium.IFrame(html=html % (nm, str(el)), width=200, height=100)
    fgv.add_child(
        folium.CircleMarker(location=[lt, ln],
                            popup=folium.Popup(iframe),
                            fill_color=color_picker(el),
                            fill=True,
                            fill_opacity=0.8,
                            color="black"))

# Population map data
fgp = folium.FeatureGroup(name="Population")
geo_data = open("world.json", "r", encoding="utf-8-sig")
fgp.add_child(
    folium.GeoJson(
        data=geo_data.read(),
        style_function=lambda x: {
예제 #3
0
html = """<h4> City Information </h4>
Height: %s m
"""

map = folium.Map(location=[38.58, -99.09],
                 zoom_start=4,
                 tiles="Stamen Terrain")

fgc = folium.FeatureGroup(name="Cities")

for lt, ln, de in zip(lat, lon, det):

    #Cities I have been too function
    iframe = folium.IFrame(
        html=html % str(de), width=1000, height=1000
    )  #image will be here // Now a circle but expect to have png images//
    fgc.add_child(
        folium.CircleMarker(location=[lt, ln],
                            popup=str(de) + " time(s) in that city?",
                            color=color_producer(de),
                            radius=20,
                            fill=True))

#Population of every country in the world
fgp = folium.FeatureGroup(name="Population")

fgp.add_child(
    folium.GeoJson(
        data=open('world.json', 'r',
                  encoding='utf-8-sig').read(),  #adds segmentation lines
예제 #4
0
def make_html(raw_path,
              telemetrystatus_file,
              pic_path,
              dictionary,
              htmlpath,
              df,
              pdelta=20):
    """MAKE TELEMETRY.HTML
    raw_path: the path of store raw files
    telemetry_status: the path and filename of the telemetry status
    pic_path: the path that use to store pictures
    dictionary: the path and filename of dictionary(use to store the modules data)
    pdelta: the timedelta of picture file time with emolt data time
    
    """
    df_tele_status = rf.read_telemetrystatus(path_name=telemetrystatus_file)

    #### START BUILDING THE LEAFLET WEBPAGE, READ A FEW INPUT FILES, CREATE FOLIUM.MAP
    including = list(set(df['vessel_n']))  #vessel number eg. 'Vessel_18'
    map_1 = folium.Map(
        location=[41.572, -69.9072],
        width='88%',
        height='75%',
        left="3%",
        top="2%",
        control_scale=True,
        detect_retina=True,
        zoom_start=8,
        tiles=
        'https://server.arcgisonline.com/ArcGIS/rest/services/Ocean_Basemap/MapServer/tile/{z}/{y}/{x}',
        attr=
        'Tiles &copy; Esri &mdash; Sources: GEBCO, NOAA, CHS, OSU, UNH, CSUMB, National Geographic, DeLorme, NAVTEQ, and Esri',
    )
    #    map_1.add_tile_layer( name='Esri_OceanBasemap',
    #                     tiles='https://server.arcgisonline.com/ArcGIS/rest/services/Ocean_Basemap/MapServer/tile/{z}/{y}/{x}',
    #                          attr= 'Tiles &copy; Esri &mdash; Sources: GEBCO, NOAA, CHS, OSU, UNH, CSUMB, National Geographic, DeLorme, NAVTEQ, and Esri',
    #                          )
    #    map_1.add_tile_layer(                   name='NatGeo_World_Map',
    #                   tiles='http://server.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}',
    #                   attr= 'Tiles &copy; Esri &mdash; National Geographic, Esri, DeLorme, NAVTEQ, UNEP-WCMC, USGS, NASA, ESA, METI, NRCAN, GEBCO, NOAA, iPC',)
    colors = [
        'red', 'blue', 'gray', 'darkred', 'lightred', 'orange', 'beige',
        'green', 'darkgreen', 'lightgreen', 'darkblue', 'lightblue', 'purple',
        'darkpurple', 'pink', 'cadetblue', 'lightgray', 'black'
    ]

    for x in range(int(len(df_tele_status) / len(colors)) + 2):
        colors = colors + colors
        lat_box = []
        lon_box = []
        route = 0
        lat = 0
        lon = 0
        popup = 0
        html = ''
        lastfix = 1
        randomlat = 1
        randomlon = 0
        mc = MarkerCluster()
    # CREATE ICONS ON THE MAP
    for i in range(
            0, len(including)
    ):  # LOOP THROUGH VESSELS note: I am skipping vessel_1 since that was just at the dock test
        print(i, route, popup, lastfix)
        if i != route and popup != 0 and lastfix == 0 and html != '':  #since lastfix was set to 1 before loop, the following lines never get issued??????
            iframe = folium.IFrame(html=html, width=700, height=350)
            popup = folium.Popup(iframe, max_width=900)
            folium.Marker([lat + randomlat, lon + randomlon],
                          popup=popup,
                          icon=folium.Icon(color=colors[route],
                                           icon='ok-sign')).add_to(map_1)
        lastfix = 1
        for line in range(len(df)):  # LOOP THROUGH EACH LINE OF EMOLT.DAT
            if df.iloc[line]['vessel_n'] == including[i]:
                #                id_idn1=including[i]
                datet = df.iloc[line]['time']
                if float(str(df.iloc[line]['depth'])) > 10:
                    html = ''
                    meandepth = df.iloc[line]['depth']
                    rangedepth = df.iloc[line]['rangedepth']
                    len_day = df.iloc[line]['timerange']
                    mean_temp = df.iloc[line]['temp']
                    sdevia_temp = df.iloc[line]['stdtemp']
                    lat = df.iloc[line]['lat']  #get the latitude
                    lon = df.iloc[line]['lon']  #get the longitude
                    vessel_number = including[i].split('_')[1]
                    for ves in range(len(df_tele_status)):
                        if str(df_tele_status['Vessel#'].iloc[ves]) == str(
                                vessel_number):
                            vessel_name = df_tele_status['Boat'].iloc[ves]
                    pic_ym = datet.strftime('%Y%m')
                    picturepath = os.path.join(pic_path, vessel_name, pic_ym)
                    try:
                        dic = get_moudules_value(filepathname=dictionary,
                                                 vessel_name=vessel_name,
                                                 dtime=datet)
                        doppio_t, gomofs_t, FVCOM_t, clim_t = dic[
                            'Doppio'], dic['GoMOLFs'], dic['FVCOM'], dic[
                                'CrmClim']
                    except:
                        doppio_t, gomofs_t, FVCOM_t, clim_t = np.nan, np.nan, np.nan, np.nan

                    #set the value that need display, for example temperature of modules, observed and so on.
                    content = datet.strftime(
                        '%d-%b-%Y  %H:%M'
                    ) + '<br>Observed temperature: ' + str(
                        round(c2f(float(mean_temp))[0],
                              1)).rjust(4) + '&nbsp;F&nbsp;(' + str(
                                  round(mean_temp, 1)).rjust(4) + '&nbsp;C)'
                    if not (math.isnan(doppio_t) and math.isnan(gomofs_t)
                            and math.isnan(FVCOM_t) and math.isnan(clim_t)):
                        content += '<br>Modelled temperatures:'
                    if not math.isnan(doppio_t):
                        content += '<br>&nbsp;&nbsp;DOPPIO:&nbsp;' + str(
                            round(c2f(float(doppio_t))[0],
                                  1)).rjust(4) + '&nbsp;F&nbsp;(' + str(
                                      round(doppio_t, 1)).rjust(4) + '&nbsp;C)'
                    if not math.isnan(gomofs_t):
                        content += '<br>&nbsp;&nbsp;GoMOFS:&nbsp;' + str(
                            round(c2f(float(gomofs_t))[0],
                                  1)).rjust(4) + '&nbsp;F&nbsp;(' + str(
                                      round(gomofs_t, 1)).rjust(4) + '&nbsp;C)'
                    if not math.isnan(FVCOM_t):
                        content += '<br>&nbsp;&nbsp;FVCOM :&nbsp;' + str(
                            round(c2f(float(FVCOM_t))[0],
                                  1)).rjust(4) + '&nbsp;F&nbsp;(' + str(
                                      round(FVCOM_t, 1)).rjust(4) + '&nbsp;C)'
                    if not math.isnan(clim_t):
                        content += '<br>&nbsp;&nbsp;Climatology: ' + str(
                            round(c2f(clim_t)[0],
                                  1)).rjust(4) + '&nbsp;F&nbsp;(' + str(
                                      round(clim_t,
                                            1)).rjust(4) + '&nbsp;C)<br>'
                    content+='<br>Sdevia_temp: '+str(round(c2f(float(sdevia_temp))[0],1))+'&nbsp;F&nbsp;('+str(round(sdevia_temp,1)).rjust(4)+'&nbsp;C)'+\
                    '<br>Observed depth: '+str(round(meandepth/1.8288,1)).rjust(10)+'&nbsp;Fth'+\
                            '<br>Rangedepth: '+str(round(float(rangedepth)/1.8288,1))+'&nbsp;Fth'+\
                            '<br>Haul_duration: '+str(round(len_day,1))+'&nbsp;hours'
                    for aqu_file in glob.glob(
                            os.path.join(picturepath, "*.png")):
                        fpath, fname = os.path.split(aqu_file)
                        filename_time = fname.split('.')[0].split('_')[2:4]
                        dt_fnt = datetime.datetime.strptime(
                            filename_time[0] + filename_time[1],
                            '%Y%m%d%H%M%S')
                        if abs(dt_fnt -
                               datet) <= datetime.timedelta(minutes=pdelta):
                            link = '"' + 'http://studentdrifters.org' + (
                                '/' +
                                os.path.join('/lei/all_pic', fname)).replace(
                                    '//', '/') + '"'
                            icon = 'star'
                            if html == '':
                                html='''
                                    <p>
                                    <meta name="viewport" content="width=device-width">
                                    <body>
                                    <font size="5">
                                    <code>
                                    '''+content+\
                                    '<br>Click <a href='+link+'>here</a> to view the detailed graph.'+\
                                    '<br><font size="4">C:&nbsp;Celsius&nbsp;&nbsp;F:&nbsp;Fahrenheit''''
                                    </code>
                                    </body>
                                    </p>
                                    '''

                    if html == '':
                        html = '''
                            <p>
                            <meta name="viewport" content="width=device-width">
                            <body>
                            <font size="5">
                            <code>
                            ''' + content + '<br><font size="4">C: Celsius  F: Fahrenheit  Fth:Fathoms' '''
                            </code>
                            </body>
                            </p>
                            '''
                        icon = 'ok-sign'
                    lon_box.append(lon)
                    lat_box.append(lat)
                    iframe = folium.IFrame(html=html, width=700, height=350)
                    #                    popup = folium.Popup(iframe, max_width=1500)
                    #                    iframe = folium.IFrame(html=html)
                    popup = folium.Popup(iframe, max_width=45000)
                    randomlat = random.randint(-3000, 3000) / 100000.
                    randomlon = random.randint(-2500, 2000) / 100000.
                    mk = folium.Marker([lat + randomlat, lon + randomlon],
                                       popup=popup,
                                       icon=folium.Icon(icon=icon,
                                                        color=colors[i]))
                    #                    mk=folium.Marker([lat+randomlat,lon+randomlon],popup=popup,icon=folium.Icon(icon=icon,color=colors[i]))
                    mc.add_child(mk)
                    map_1.add_child(mc)
                    lastfix = 0
        route = i
    folium.LayerControl().add_to(map_1)
    map_1.save(os.path.join(htmlpath, 'telemetry_version2.html'))
    with open(os.path.join(htmlpath, 'telemetry_version2.html'), 'a') as file:
        file.write('''        <body>
            <div id="header"><br>
                <h1>&nbsp;&nbsp;&nbsp;&nbsp&nbsp;Realtime bottom temperatures from fishing vessels in the past month</h1>  
                <ul>
                <dir><dir>
                <li>Checkmark icons denotes latest reports color-coded by vessel.
                <li>Numbered icons denote multiple reports in that area color-coded by density of reports.
                <li>Starred icons denote actual reports posted within 10 miles of actual position.
                <li>Starred icons denote actual reports there have detailed graph, ok-sign icon denote there have not detailed graph.
                <li>Layer symbol in upper right denotes other basemap options.
                </dir></dir>
                </ul>
            </div>   
        </body>''')
    file.close()
예제 #5
0
def show_objects_on_map(input_df,
                        tpu_data,
                        obj_size=1000,
                        marker_size=2,
                        zoom=10,
                        obj_as_marker=False,
                        display_districts=True,
                        display_tpu=True,
                        translit=False):
    """
    This function builds a map with markers of objects on it.
    If location contains many objects - it groups it with the
    summary of the location. (Total objects  and  number   of
    objects from all avalible class)  Description is added as 
    HTML-tagged text. Can be converted from Cyrillic. See opt 
    Be advised: can be slow on large datasets.
    
    Param 'translit' transliterate Cyrillic symbols.
    
    :param pd.df: input_df           - Full or slice
    :param   int: marker_size        - [Dafault=2]    (Optional)
    :param   int: zoom               - [Dafault=10]   (Optional)
    :param  Bool: obj_as_marker      - [Dafault=False](Optional)
    :param  Bool: display_districts  - [Dafault=True] (Optional)
    :param  Bool: display_tpu        - [Dafault=True] (Optional)
    :param  Bool: translit           - [Dafault=False](Optional)
    :returns Folium.map: moscow_map  
    """
    def style_function(feature):
        feature = feature['properties']['NAME']
        obj_count = tpu_obj_count.get(feature, None)
        if isinstance(obj_count, type(None)):
            obj_count = find_area(feature)
        return {
            'fillOpacity': 0.5,
            'color': '#A9A7A7',
            'weight': 2,
            'fillColor':
            '#ffffff' if obj_count is None else colorscale(obj_count)
        }

    # Map initialization
    global tpu_obj_count
    tpu_obj_count = input_df['object_district'].value_counts()

    input_df = input_df.head(obj_size)
    geolocator = Nominatim(user_agent="demo")
    address = 'Moscow, Russia'
    location = geolocator.geocode(address)
    latitude = location.latitude
    longitude = location.longitude
    moscow_map = folium.Map(location=[latitude, longitude],
                            tiles='Stamen Toner',
                            zoom_start=zoom)

    # Add map types
    folium.TileLayer('cartodbpositron').add_to(moscow_map)
    folium.TileLayer('OpenStreetMap').add_to(moscow_map)

    # Display area boundaries
    if display_districts == True:
        municipality = json.loads(
            requests.get('http://gis-lab.info/data/mos-adm/mo.geojson').text)
        color_max = tpu_obj_count.max()
        color_min = tpu_obj_count.min()
        global colorscale
        colorscale = branca.colormap.linear.YlGnBu_09.scale(
            color_min, color_max)
        layer_name = 'Area boundaries'
        area_bound = folium.FeatureGroup(name=layer_name, show=True)
        folium.GeoJson(municipality,
                       style_function=style_function).add_to(area_bound)
        moscow_map.add_child(area_bound)

    # Generating Marker with HTML description for unique location
    layer_name = 'Trade places'
    shop_obj = folium.FeatureGroup(name=layer_name, show=True)
    for address_name in input_df.object_address.unique():
        info = {}
        obj_counter = 0
        tmp_obj_df = input_df[input_df.object_address == address_name]
        info['lat'], info['lng'] = tmp_obj_df.iloc[0].object_latitude,\
                                 tmp_obj_df.iloc[0].object_longitude
        # Creating Dictionary with location metadata divided into classes
        for curr_obj_size in tmp_obj_df.object_size.unique():
            curr_obj_data = []
            for name, descr in zip(tmp_obj_df[tmp_obj_df.object_size==\
                                                    curr_obj_size].object_name,
                               tmp_obj_df[tmp_obj_df.object_size==\
                                                    curr_obj_size].object_type):
                curr_obj_data.append(f'{name} - <i>{descr}</i>')
            obj_counter += len(curr_obj_data)
            info[curr_obj_size] = curr_obj_data
        # Generating HTML-tagged description using dictionary with metadata
        size_names = {1: 'Small', 2: 'Medium', 3: 'Large'}
        description = f'<p><b>Objects total: {str(obj_counter)}</b><br>'
        description += f'<p>Closest TPU: {tmp_obj_df.tpu_name.iloc[0]}'
        description += f' in {round(tmp_obj_df.distance_to_tpu.iloc[0],0)} m.<br>'
        description += f'<p>Nearest station: {tmp_obj_df.tpu_near_station.iloc[0]}<br><hr>'
        for curr_obj_size in np.sort(tmp_obj_df.object_size.unique())[::-1]:
            if curr_obj_size in info:
                description += f'<b>{size_names[curr_obj_size]} objects total: '
                description += str(len(info[curr_obj_size])) + '</b><ul>'
                for obj_info in info[curr_obj_size]:
                    description += (f'<li>{obj_info}')
                description += '</ul><hr><br>'
        if translit == True:
            description = transliterate(description)
        iframe = folium.IFrame(html=description, width=600, height=300)
        popup_description = folium.Popup(iframe, max_width=2650)
        # Choosing color accoring to top class of objects in the location
        colors = ['#006699', '#339900', '#cc6600']
        icon_shapes = [
            'marker', 'circle-dot', 'rectangle', 'rectangle-dot', 'doughnut',
            'circle'
        ]
        obj_icons = [
            'shopping-basket', 'shopping-cart', 'shopping-bag', 'building',
            'institution'
        ]
        for i in range(0, 3):
            if i + 1 in info.keys():
                marker_color = colors[i]
                icon_color = colors[i]
                marker_icon = obj_icons[i]
                icon_shape = icon_shapes[i]
        if 1 < obj_counter <= 10:
            marker_icon = obj_icons[3]
        if obj_counter > 10:
            marker_icon = obj_icons[4]
        # Marker generation
        if obj_as_marker == False:
            folium.CircleMarker(
                  [info['lat'], info['lng']],
                  radius= (marker_size + np.log(obj_counter))*2,
                  popup=popup_description,
                  tooltip=transliterate(f'{address_name} - ' +\
                                    f'{obj_counter} мест(а)')[14:],
                  color=marker_color,
                  fill=True,
                  fill_color=marker_color,
                  parse_html=True).add_to(shop_obj)
        else:
            folium.Marker(location=[info['lat'],
                                    info['lng']],
                          popup=popup_description,
                          tooltip=transliterate(f'{address_name} - ' +\
                                            f'{obj_counter} мест(а)')[14:],
                          icon=BI(icon=marker_icon,
                          icon_shape='marker',
                          border_width=2,
                          border_color='#ffffff',
                          text_color='#ffffff',
                          background_color=marker_color
                          )).add_to(shop_obj)

    moscow_map.add_child(shop_obj)

    # Display tpu data on map
    if display_tpu == True:
        layer_name = 'Transport hubs'
        tpu_obj = folium.FeatureGroup(name=layer_name, show=True)
        tpu_lat = tpu_data.tpu_latitude.apply(lambda x: x['center'])
        tpu_lon = tpu_data.tpu_longitude.apply(lambda x: x['center'])

        for lat, lng, tpu_name, tpu_stat, year, transfer, slots in zip(
                tpu_lat, tpu_lon, tpu_data.TPUName, tpu_data.Status,
                tpu_data.YearOfComissioning, tpu_data.AvailableTransfer,
                tpu_data.CarCapacity):

            description = f'<p><b>TPU name: {tpu_name}<br>'
            description += f' ({tpu_stat})</b><br><hr>'
            description += f'<p>Year of comissioning: {year}'
            description += f'<p>Availible transfer:<br><ul>'
            for option in transfer.split(';'):
                description += f'<li>{option.lower()}'
            description += f'</ul><p>Availible parking slots: {slots}'
            if translit == True:
                description = transliterate(description)
            iframe = folium.IFrame(html=description, width=600, height=300)
            popup_description = folium.Popup(iframe, max_width=2650)
            folium.Marker(location=[float(lat), float(lng)],
                          popup=popup_description,
                          tooltip=transliterate(tpu_name),
                          icon=folium.Icon(color="red",
                                           icon='train',
                                           prefix='fa')).add_to(tpu_obj)
        moscow_map.add_child(tpu_obj)

    # Add colorbar and LayerControl
    if display_districts == True:
        colorscale.add_to(moscow_map)
    folium.LayerControl().add_to(moscow_map)

    return moscow_map
예제 #6
0

def offset_location_lon(lon):
    ln = float(lon) + (random.randint(-5, 5) / 300)
    return ln


"""Create Icons for appropriate Feature Group based on year """
for lt, ln, dt, arm, nm, rc, tl, flee, bc, mod in zip(lat, lon, year, armed,
                                                      name, race, threat_level,
                                                      fleeing, body_camera,
                                                      manner_of_death):
    if lt != 'Latitude' and ln != 'Longitude':
        if '2020' in dt:
            iframe = folium.IFrame(html=html %
                                   (nm, nm, dt, rc, arm, tl, flee, bc, mod),
                                   width=200,
                                   height=100)
            fg20.add_child(
                folium.CircleMarker(location=[
                    offset_location_lat(lt),
                    offset_location_lon(ln)
                ],
                                    popup=folium.Popup(iframe),
                                    radius=5,
                                    fill_color=fill_color_selector(rc),
                                    fill_opacity=.8,
                                    color=color_icon(arm),
                                    opacity=1).add_to(cluster))
        if '2019' in dt:
            iframe = folium.IFrame(html=html %
                                   (nm, nm, dt, rc, arm, tl, flee, bc, mod),
예제 #7
0
def get_colour(integer):
    if integer < 1000:
        return "green"
    elif integer < 3000:
        return "orange"
    else:
        return "red"


data = pandas.read_csv("Volcanoes.txt")
latitudes = list(data.LAT)
longitudes = list(data.LON)
names = list(data.NAME)
elevations = list(data.ELEV)

html = """
<h4><a href="https://www.google.com/search?q=%%22%s%%22" target="_blank">%s</a></h4>
Height: %f m
"""

map = folium.Map(location=[39.7392, -104.9903], zoom_start=5, tiles="Stamen Terrain")
fg = folium.FeatureGroup(name="Volcanoes")
for lat, lon, name, elevation in zip(latitudes, longitudes, names, elevations):
    iFrame = folium.IFrame(html % (name, name, elevation), width=200, height=100)
    fg.add_child(folium.CircleMarker(location=[lat, lon], popup=folium.Popup(iFrame),  color=get_colour(elevation),
                                     fill=True, fill_opacity=0.5, fill_color=get_colour(elevation)))
map.add_child(fg)

map.save("volcanoe_map_heightgradient.html")
예제 #8
0
def save_map():

    A = pd.read_csv('D:\workspace\web\project\ev_project_web\static\data\ev\A.csv')
    B = pd.read_csv('D:\workspace\web\project\ev_project_web\static\data\ev\B.csv')
    C = pd.read_csv('D:\workspace\web\project\ev_project_web\static\data\ev\C.csv')
    D = pd.read_csv('D:\workspace\web\project\ev_project_web\static\data\ev\D.csv')
    E = pd.read_csv('D:\workspace\web\project\ev_project_web\static\data\ev\E.csv')
    F = pd.read_csv('D:\workspace\web\project\ev_project_web\static\data\ev\F.csv')

    a_place = ['한경면', '한림읍', '애월읍']
    b_place = ['추자면', '연동', '이도2동', '오라2동', '해안동', '아라1동',
                          '건입동', '노형동', '영평동', '삼양2동', '오라1동', '도남동',
                          '일도2동', '용강동', '외도1동', '봉개동', '아라2동', '아라동',
                          '도두1동', '이도1동', '화북1동', '용담2동', '오등동', '도련2동',
                          '용담1동', '삼도2도']
    c_place = ['조천읍', '구좌읍']
    d_place = ['대정읍', '안덕면', '하예동', '중문동', '대천동', '상예동',
                          '색달동']
    e_place = ['하효동', '남원읍', '강정동', '서홍동', '법환동', '동홍동',
                          '토평동', '서귀동', '보목동', '서호동', '회수동', '상효동']
    f_place = ['성산읍', '표선면']
    date = int(request.form['month'] + request.form['date']) 
    day = int(request.form['day'])
    times = int(request.form['times'])
    city = request.form['city']
    gu = request.form['gu']
    
    
    for i in a_place:
        if i == gu:
            test = A.drop_duplicates('cid')
            test['week'] = date
            test['day'] = day
            test['time'] = times
            aa = test.drop(['use', 'sid', 'gu'], axis = 1)
            pred = model_ev_dt_a.predict(aa)
            apred = pd.DataFrame({'dt': pred})
            test['DT'] = list(apred['dt'])
            test = test.sort_values(by=['gu', 'sid'], ascending=True)
            test = test.drop(['Unnamed: 0', 'cid', 'week', 'use'], axis=1)
            break

    for i in b_place:
        if i == gu:
            test = B.drop_duplicates('cid')
            test['week'] = date
            test['day'] = day
            test['time'] = times
            bb = test.drop(['use', 'sid', 'gu'], axis = 1)
            pred = model_ev_dt_b.predict(bb)
            bpred = pd.DataFrame({'dt': pred})
            test['DT'] = list(bpred['dt'])
            test = test.sort_values(by=['gu', 'sid'], ascending=True)
            test = test.drop(['Unnamed: 0', 'cid', 'week', 'use'], axis=1)
            break
    for i in c_place:
        if i == gu:
            test = C.drop_duplicates('cid')
            test['week'] = date
            test['day'] = day
            test['time'] = times
            cc = test.drop(['use', 'sid', 'gu'], axis = 1)
            pred = model_ev_dt_c.predict(cc)
            cpred = pd.DataFrame({'dt': pred})
            test['DT'] = list(cpred['dt'])
            test = test.sort_values(by=['gu', 'sid'], ascending=True)
            test = test.drop(['Unnamed: 0', 'cid', 'week', 'use'], axis=1)
            break
    for i in d_place:
        if i == gu:
            test = D.drop_duplicates('cid')
            test['week'] = date
            test['day'] = day
            test['time'] = times
            dd = test.drop(['use', 'sid', 'gu'], axis = 1)
            pred = model_ev_dt_d.predict(dd)
            dpred = pd.DataFrame({'dt': pred})
            test['DT'] = list(dpred['dt'])
            test = test.sort_values(by=['gu', 'sid'], ascending=True)
            test = test.drop(['Unnamed: 0', 'cid', 'week', 'use'], axis=1)
            break
    for i in e_place:
        if i == gu:
            test = E.drop_duplicates('cid')
            test['week'] = date
            test['day'] = day
            test['time'] = times
            ee = test.drop(['use', 'sid', 'gu'], axis = 1)
            pred = model_ev_dt_e.predict(ee)
            epred = pd.DataFrame({'dt': pred})
            test['DT'] = list(epred['dt'])
            test = test.sort_values(by=['gu', 'sid'], ascending=True)
            test = test.drop(['Unnamed: 0', 'cid', 'week', 'use'], axis=1)
    for i in f_place:
        if i == gu:
            test = F.drop_duplicates('cid')
            test['week'] = date
            test['day'] = day
            test['time'] = times
            ff = test.drop(['use', 'sid', 'gu'], axis = 1)
            pred = model_ev_dt_f.predict(ff)
            fpred = pd.DataFrame({'dt': pred})
            test['DT'] = list(fpred['dt'])
            test = test.sort_values(by=['gu', 'sid'], ascending=True)
            test = test.drop(['Unnamed: 0', 'cid', 'week', 'use'], axis=1)
            break
    top5 = []
    t_len = len(test)
    test.reset_index(inplace=True)
    for i in range(t_len): 
        if test['gu'][i] == gu :
            if i == 0 :
                top5.append(test['sid'][i])
            elif test['gu'][i-1] != test['gu'][i]:
                top5.append(test['sid'][i])

    if len(top5) <=5:
        for k in range(t_len):
            if test['gu'][k]!=gu :
                if k == 0:
                    top5.append(test['sid'][k])
                elif test['gu'][k-1] != test['gu'][k]:
                    top5.append(test['sid'][k])
    top5 = top5[0:5]

    df = pd.read_csv('D:\workspace\web\project\ev_project_web\static\data\충전소추천c_add\제주도_통계_수정.csv', sep=',', encoding = 'euc-kr', usecols = ['sid','week','time','use'])
    for i in range(0,len(df)):
        if df['use'][i] > 2 :
            df['use'][i] = 2
    df['카운트'] = 1
    df = df.groupby(by=['sid','week','time']).sum()
    df['확률'] = round((df['use']/df['카운트']/2),2)

    a = top5
    day_check = test['day']

    df_add = pd.read_csv('D:\workspace\web\project\ev_project_web\static\data\충전소추천c_add\c_name.csv', sep=',',usecols = ['c_name','sid','c_add'])
    df_add=pd.DataFrame(df_add)

    name = []
    sid = []
    add = []

    for i in range(len(df_add)):
        if i == 0 :
            name.append(df_add['c_name'][i])
            sid.append(df_add['sid'][i])
            add.append(df_add['c_add'][i])
        elif df_add['sid'][i-1] != df_add['sid'][i]:
            name.append(df_add['c_name'][i])
            sid.append(df_add['sid'][i])
            add.append(df_add['c_add'][i])
    charger_dict = {"name": name, "sid": sid, "c_add": add}
    charger_recommend = pd.DataFrame(charger_dict)
    dic = {"sid": a}
    input_charger = pd.DataFrame(dic)
    charger_chk = pd.merge(input_charger,charger_recommend,on='sid')

    charger_chk['위도'] = 0.000
    charger_chk['경도'] = 0.000

    b=[]
    for c in range(len(charger_chk)):
        b.append(charger_chk['name'][c])
    day = ['월요일','화요일','수요일','목요일','금요일','토요일','일요일']

    for i in range(len(df)):
        for j in range(len(a)):
            df_cid=df.loc[a[j]]
            for k in range(7):
                plt.cla()
                df_week=df_cid.loc[k]
                df_time=df_week
                df_time


                plt.rcParams['figure.figsize'] = [6,3.4]
                plt.rcParams["font.family"] = 'Malgun Gothic'

                plt.plot(df_time.index, (df_time.확률*100), marker='s', color='green', markersize = 5)

                plt.rc('xtick', labelsize = 10)
                plt.rc('ytick', labelsize = 10)
                plt.xticks(np.arange(0, 24, 1), labels=['0','1', '2', '3', '4', '5', '6', '7', '8', '9', '10','11','12','13','14','15','16','17','18','19','20','21','22','23','24'])
                plt.yticks(np.arange(0, 100,10), ('10', '20', '30', '40', '50', '60', '70', '80', '90', '100'))
                plt.title('%s - 이용자 통계(%s)'%(b[j],day[k]), fontsize=15)
                plt.ylabel('PERCENT(%)', fontsize=10)
                plt.xlabel('TIME', fontsize=10)
                plt.grid(True)
                plt.savefig('static/image/fig%.d-%.d.png'%(j,k))
                
                
                
        break

    for i in range(len(charger_chk)):
        location = charger_chk['c_add'][i]

        URL = 'https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyCNgb2Qc2tOS8zo4xr7odc9WigwW9h6noM' \
        '&sensor=false&language=ko&address={}'.format(location)

        response = requests.get(URL)
        data = response.json()

        lat = data['results'][0]['geometry']['location']['lat']
        lng = data['results'][0]['geometry']['location']['lng']
        
        u_address = []
        u = data['results'][0]
        u_address=u['formatted_address']
        
        lat =[]
        lng =[]
        k=data['results'][0]
        k_1=k['geometry']['location']
        k_1
        lat = k_1['lat'] #위도
        lng = k_1['lng'] #경도
        charger_chk['위도'][i] = lat
        charger_chk['경도'][i] = lng

        a_위도 = 0.00
    a_경도 = 0.00
    #전체 줌 위치
    for k in range(len(charger_chk)):
        a_위도 += charger_chk['위도'][k]
        a_경도 += charger_chk['경도'][k]

    a_위도 = a_위도/len(charger_chk)
    a_경도 = a_경도/len(charger_chk)

    imgs = '<img src="static/image/box.png">'

    m = folium.Map(
        location=[a_위도,a_경도],
        zoom_start=13,

    )
    
    All = folium.plugins.MarkerCluster(control=False, name='Top5')
    m.add_child(All)
    


    #실제 주소 받고 마커 체크
    for i in range(len(charger_chk)):
        pic_1 = base64.b64encode(open('static/image/%s.png'%(charger_chk['sid'][i]),'rb').read()).decode()
        pic_2 = base64.b64encode(open('static/image/fig%d-%d.png'%(i, day_check[i]),'rb').read()).decode()
        image_tag = '''<img src="data:image/jpeg;base64,{0}"><br><img src="data:image/jpeg;base64,{1}" style="width:430px; height:230px"><br>'''.format(pic_1, pic_2)
        iframe = folium.IFrame(image_tag, width=450, height=520)
        popup = folium.Popup(iframe, max_width=600)
        if i == 0:
            name2 = folium.plugins.FeatureGroupSubGroup(All, '<div><div style="float: left; "><img src="static/image/list_icon_green.ico" style ="width:40px; height:40px;">  </div><h4 style="font-weight: bold; font-family:Lato">%s</h4><h5 style=" font-family:Lato">%s</h5></div>'%(charger_chk['name'][i],charger_chk['c_add'][i]))
            m.add_child(name2)
            
            icon=folium.Icon(color='green', icon='car', icon_color="white", prefix='fa')
            folium.Marker(
            location=[charger_chk['위도'][i],charger_chk['경도'][i]],
            popup=popup,tooltip='%s'%(charger_chk['name'][i]),
            icon=icon
            ).add_to(m)
            
            folium.Marker(location=[charger_chk['위도'][i],charger_chk['경도'][i]], icon=DivIcon(
        icon_size=(120,24),
        icon_anchor=(3,5),
        
        html='<div style="position:relative;text-align:center; width:200px;"><img src="static/image/box.png"><div style="position: absolute; bottom: 18px; left: 10px; text-align:center; font-size:12pt; font-weight:bold; font-family:Lato">%s</div></div>'%(charger_chk['name'][i]),
        )).add_to(m)
            

        else :
            name2 = folium.plugins.FeatureGroupSubGroup(All, '<div><div style="float: left;"><img src="static/image/list_icon_blue.ico" style ="width:40px; height:40px;"></div>  <h4 style="font-weight: bold; font-family:Lato">%s</h4><h5 style=" font-family:Lato">%s</h5></div>'%(charger_chk['name'][i],charger_chk['c_add'][i]))
            m.add_child(name2)
            icon=folium.Icon(color='blue', icon='car', icon_color="white", prefix='fa')
            folium.Marker(
            location=[charger_chk['위도'][i],charger_chk['경도'][i]],
            popup=popup,tooltip='%s'%(charger_chk['name'][i]),
            icon=icon
            ).add_to(m)

            folium.Marker(location=[charger_chk['위도'][i],charger_chk['경도'][i]], icon=DivIcon(
        icon_size=(120,24),
        icon_anchor=(3,5),
        html='<div style="position:relative;text-align:center; width:200px;"><img src="static/image/box.png"><div style="position: absolute; bottom: 18px; left: 10px; text-align:center; font-size:12pt; font-weight: bold; font-family:Lato">%s</div></div>'%(charger_chk['name'][i]),
        )).add_to(m)
            

    folium.LayerControl(position='topleft', collapsed=False).add_to(m)       
    #m._repr_html_()
    m.save('templates/map.html')
    return render_template('map.html')
예제 #9
0
    icon=DivIcon(
        icon_size=(500, 500),
        icon_anchor=(0, 0),
        html=
        '<div style="font-size: 13pt"><b>Contact:</b><br>Adresa: b-dul C.D. Loga, nr. 1<br>Telefon: (0256) 408.300<br>'
        'Fax: (0256) 490.635<br>Email: [email protected]</div>')
).add_to(m)

for i in range(1, len(df["Adresa"])):
    location = loc.geocode(df["Adresa"][i] + " " + "Timisoara")

    try:
        location = loc.geocode(df["Adresa"][i] + " " + "Timisoara")
        html = '<b>Beneficiar: ' + "</b> " + df["Beneficiar"][
            i] + "<br>" + '<b>Descriere: ' + "</b>" + df["Descriere"][i]
        iframe = folium.IFrame(html)
        popup = folium.Popup(iframe, min_width=300, max_width=300)
        marker = folium.Marker(
            location=[location.latitude, location.longitude],
            popup=popup,
            icon=folium.Icon(color='purple')).add_to(m)
    except AttributeError:
        print(df["Adresa"][i])

m.save('index.html')

url = 'index.html'
window = tk.Tk()
window.title("Interfata grafica")
window.geometry("250x100")
window.configure(bg='pink')
예제 #10
0
def mapping_df(df, target, target_value='1.0', heat=False):
    """
    Recibe un Dataframe con Coordenadas y lo grafica
    en un mapa. retorna un html para usar con Iframe.

    Prueba es el tipo de prueba, Serologia o PCR
    an: Booleano para verificar si corresponde a animales
    """
    # df = table_target(full_ser, target)

    #Mapa:

    # folium_hmap = folium.Figure(width=500, height=500) No se necesita en st
    m = folium.Map(
        location=[8.3344713, -75.6666238],
        width='100%',
        height='100%',
        zoom_start=8,  #Por defecto es 10
        tiles=
        "CartoDB positron"  #stamentoner#CartoDB positron #dark_matter #OpenSteetMap ,Stamen Toner(Terrain, Watercolor)
    )  #.add_to(folium_hmap)
    data = df
    if heat:
        data['weight'] = data[target_value] / data['total']
        HeatMap(data[['lat', 'lon', 'weight']].dropna(), radius=40,
                blur=25).add_to(m)
    else:
        for i in range(0, len(data)):
            html = f"""
                    <head>
                        <link rel="stylesheet" href="https://codepen.io/chriddyp/pen/dZVMbK.css">
                    <head>
                    <h6> {data.iloc[i]['MUNICIPIO']}</h6>
                    <p> {target.split(' ')[-1]}: </p>
                    <p>{target_value}: {data.iloc[i][target_value]}</p>
                    <p> Total: {data.iloc[i]['total']}</p>
                    """
            iframe = folium.IFrame(html=html, width=130, height=160)
            popup = folium.Popup(iframe, max_width=2650)
            folium.Circle(location=[data.iloc[i]['lat'], data.iloc[i]['lon']],
                          popup=popup,
                          radius=float(data.iloc[i]['total']) * 500,
                          color='lightgray',
                          fill=True,
                          fill_color='lightgray').add_to(m)
            # for i in range(0,len(data)): #redundante
            html2 = f"""
                    <head>
                        <link rel="stylesheet" href="https://codepen.io/chriddyp/pen/dZVMbK.css">
                    <head>
                    <h6> {data.iloc[i]['MUNICIPIO']}</h6>
                    <p> {target.split(' ')[-1]}: </p>
                    <p>{target_value}: {data.iloc[i][target_value]}</p>
                    <p> Total: {data.iloc[i]['total']}</p>
                    """
            iframe2 = folium.IFrame(html=html2, width=130, height=160)
            popup2 = folium.Popup(iframe2, max_width=2650)
            folium.Circle(location=[data.iloc[i]['lat'], data.iloc[i]['lon']],
                          popup=popup2,
                          radius=float(data.iloc[i][target_value]) * 500,
                          color='crimson',
                          fill=True,
                          fill_color='crimson').add_to(m)
    return m
예제 #11
0
        data=data2.read(),
        style_function=lambda x: {
            'fillColor':
            'grey' if x['properties']['POP2005'] < 10000000 else 'blue'
            if 10000000 <= x['properties']['POP2005'] < 20000000 else 'purple'
        }))

# user location
fg1.add_child(
    folium.Marker(g.latlng,
                  popup='My Location',
                  icon=folium.Icon(color='black')))

# all volcanoes in all countries
for lt, ln, nm, hz in zip(lat, lon, name, hazard):
    iframe = folium.IFrame(html=html % (nm, nm), width=180, height=50)
    fg2.add_child(
        folium.CircleMarker([lt, ln],
                            radius=6,
                            popup=folium.Popup(iframe),
                            fill_color=colordefiner(hz),
                            color='black',
                            fill_opacity=1))

# Feature group added
map1.add_child(fg)
map1.add_child(fg1)
map1.add_child(fg2)

# control layer added
# needs to be at the bottom of feature group as it depends on it
예제 #12
0
파일: main.py 프로젝트: cateban/gymy
def main():
    if request.method == 'POST':
        try:
            filtro_usuario = request.form.get('dropdown')
            input_user = request.form['input_usuario']
            #inicializo GeoCage para localizar input del usuario
            tokengeo = token('geocagetoken.txt')
            #tokengeo = token(PATH+'/geocagetoken.txt') -> For pythonanywhere
            geocoder = OpenCageGeocode(tokengeo)
            results = geocoder.geocode(input_user)
            kmeters = 2
            fcoordinates = []
            coordinates = []
            coordinates.append(results[0]['geometry']['lat'])
            coordinates.append(results[0]['geometry']['lng'])
            country = results[0]['components']['country']
            city = results[0]['components']['city']
            localidad = country + ', ' + city
            fcoordinates.append(coordinates)
            fcoordinates.append(kmeters)
            fcoordinates.append(localidad)
            fcoordinates.append(input_user)

            #se separa la string
            latlong = fcoordinates[0]
            radio = fcoordinates[1]
            localidad = fcoordinates[2]
            direccion_solicitud = fcoordinates[3]

            gymy_modelo = gymy.copy()

            if filtro_usuario != 'Todas las categorías':
                gymy_modelo['filtro'] = gymy_modelo.category.apply(
                    filtro, form_user_input=filtro_usuario)
            else:
                gymy_modelo['filtro'] = True

            gymy_modelo = gymy_modelo[gymy_modelo.filtro == True]

            gymy_modelo['distance'] = gymy_modelo.latlong.apply(
                lambda x, y=latlong: distance.distance(x, y).km)
            display_df = gymy_modelo[gymy_modelo.distance < radio]
            display_df.reset_index(inplace=True)
            n_gyms = len(display_df)

            if n_gyms > 0:
                #creating map object
                tooltip = 'Dirección elegida: {} \n {}'.format(
                    direccion_solicitud, localidad)
                mapa = folium.Map(latlong,
                                  zoom_start=15,
                                  width='100%',
                                  height='70%')
                folium.Marker(latlong, tooltip=tooltip,
                              icon=folium.Icon()).add_to(mapa)
                for i in range(len(display_df)):
                    htmlpopup = """
                            <font face = Verdana size = "1"> <label ><b>{}</b></label> <br> </font>
                            <p>
                            <font face= Verdana size = "1"><label><b> Teléfono:</b> {}</label> <br>
                            <label><b>Dirección:</b> {}</label> <br>
                            <label><b>Web:</b> {}</label> <br>
                            <label><b>Categorías: </b>{}</label>
                            </font>
                                </p>
                            """.format(display_df.names[i],
                                       display_df.phone[i],
                                       display_df.address[i],
                                       display_df.web[i],
                                       display_df.category[i])

                    icongym = folium.features.CustomIcon(
                        '/Users/EstebanCardona/Documents/gymy/static/gymyicon.png',
                        icon_size=(40, 40))
                    iframe = folium.IFrame(html=htmlpopup,
                                           width=225,
                                           height=125)
                    popup = folium.Popup(iframe)

                    folium.Marker([display_df.lat[i], display_df.long[i]],
                                  popup=popup,
                                  tooltip=display_df.names[i],
                                  icon=icongym).add_to(mapa)
                mapa.save('templates/{}{}.html'.format(direccion_solicitud,
                                                       filtro_usuario))
                #mapa.save(PATH+'/templates/{}.html'.format(direccion_solicitud))  -> For pythonanywhere

                devuelta = 'Existen {} GYMYs de {} cerca de {}'.format(
                    n_gyms, filtro_usuario, direccion_solicitud)

                #agrega el jinja de block al html de folium
                with open(
                        'templates/{}{}.html'.format(direccion_solicitud,
                                                     filtro_usuario),
                        'a') as f:
                    #with open(PATH+'/templates/{}.html'.format(direccion_solicitud), 'a') as f: -> For pythonanywhere
                    f.write('\n{% block content %} {% endblock %}')

                return render_template('index.html',
                                       gyms_template=devuelta,
                                       mapatrue='{}{}.html'.format(
                                           direccion_solicitud,
                                           filtro_usuario),
                                       dropdown=filtro_usuario)

            else:
                devuelta = 'No hay Gymys cerca'
                return render_template('index.html',
                                       gyms_template=devuelta,
                                       mapatrue='nomapa.html',
                                       dropdown='Todas las categorías')

        except:
            devuelta = 'Dirección Inválida. Prueba con otra'
            return render_template('index.html',
                                   gyms_template=devuelta,
                                   mapatrue='nomapa.html',
                                   dropdown='Todas las categorías')

    else:
        return render_template('index.html',
                               gyms_template='',
                               mapatrue='nomapa.html',
                               dropdown='Todas las categorías')
예제 #13
0
"""


def colour_producer(elvation):
    if elvation <= 1500:
        return 'green'
    elif elvation <= 3000:
        return 'orange'
    else:
        return 'red'


volcanoes = folium.FeatureGroup(name="Volcanoes")

for lt, ln, el, nm in zip(lat, long, elev, name):
    iframe = folium.IFrame(html=html % (nm, nm, el), width=240, height=64)
    colour = colour_producer(el)
    volcanoes.add_child(
        folium.CircleMarker(location=[lt, ln],
                            radius=8,
                            popup=folium.Popup(iframe),
                            fill_color=colour,
                            color=colour,
                            fill_opacity=0.7))

population = folium.FeatureGroup(name="Population")

population.add_child(
    folium.GeoJson(
        data=open('population.json', 'r', encoding='utf-8-sig').read(),
        style_function=lambda x: {
예제 #14
0
파일: map.py 프로젝트: nowacki69/Python
    else:
        return 'white'


html = """<h4>Volcano Information:</h4>
Name: %s
<br>Height: %s m
<br>Type: %s
"""

map = folium.Map([40, -100], zoom_start=5, tiles="Mapbox Bright")
fgv = folium.FeatureGroup(name="Volcanoes")

for lt, ln, nam, el, typ in zip(lat, lon, name, elev, type):
    iframe = folium.IFrame(html=html % (nam, str(el), typ),
                           width=250,
                           height=120)
    # fgv.add_child(folium.Marker(location=[lt, ln], popup=folium.Popup(iframe),
    #                            icon=folium.Icon(color=color_producer(typ))))
    fgv.add_child(
        folium.CircleMarker(location=[lt, ln],
                            popup=folium.Popup(iframe),
                            fill_color=color_producer(typ),
                            color='grey',
                            fill_opacity=0.7))

fgp = folium.FeatureGroup(name="Population")
fgp.add_child(
    folium.GeoJson(
        data=open('world.json', 'r', encoding='utf-8-sig').read(),
        style_function=lambda x: {
예제 #15
0
def overlayGPX(gpxDataList, Colours, Labels, zoom):
    myMap = folium.Map(location=[50.443627, 16.869285], zoom_start=zoom)
    # add the layer control
    LC = folium.map.LayerControl(position='topleft',
                                 collapsed=True,
                                 autoZIndex=True)

    # deklaracja warstw
    L1 = folium.FeatureGroup()
    L2 = folium.FeatureGroup()
    L3 = folium.FeatureGroup()
    L4 = folium.FeatureGroup()
    L5 = folium.FeatureGroup()
    L6 = folium.FeatureGroup()
    L7 = folium.FeatureGroup()

    # tyt warstwy
    L1.layer_name = 'Szlaki komunikacyjne'
    L2.layer_name = 'Niekóre atrakcje obecne w roku 2020'
    L3.layer_name = 'Ważna działka w centrum miasta'
    L4.layer_name = 'Proponowany podział ważnej działki w centrum miasta'
    L5.layer_name = 'Propozycje uczestników SLL'
    L6.layer_name = 'Nowe atrakcje'
    L7.layer_name = 'Przegląd ankietyzacji kolarzy górskich'

    # dodawanie tytułu
    title_html = '''
			 <h3 align="center" style="font-size:17px"><b>Gmina Złoty Stok - przestrzenne rozmieszczenie elementów raportu</b></h3>
			 '''
    myMap.get_root().html.add_child(folium.Element(title_html))

    # dodawanie szlakow z plików GPX
    for gpxData, color, label in zip(gpxDataList, Colours, Labels):
        gpx_file = open(gpxData, 'r')
        Lon = []
        Lat = []
        for line in gpx_file:
            X = line.split('"')

            for i in X:
                try:
                    if float(i) < 20:
                        Lon.append(float(i))
                    elif float(i) > 20:
                        Lat.append(float(i))
                except:
                    pass
        points = []
        for i, j in zip(Lat[2:], Lon[2:]):
            points.append([i, j])
        if gpxData == 'zloty-stok-czerwona.gpx' or gpxData == 'zloty-stok-niebieska.gpx':
            (folium.vector_layers.PolyLine(points,
                                           width='200%',
                                           popup=label,
                                           tooltip=None,
                                           smooth_factor=2,
                                           color=color,
                                           dash_array='5')).add_to(L1)
        else:
            (folium.vector_layers.PolyLine(points,
                                           width='200%',
                                           popup=label,
                                           tooltip=None,
                                           smooth_factor=2,
                                           color=color)).add_to(L1)

    ################################################################
    ################################################################
    # OBRAZY ISTNIEJACYCH ATRAKCJI
    ################################################################
    # singletracki
    png = "single.png"
    encoded = base64.b64encode(open(png, 'rb').read())
    html = '''<h3>Sieć szlaków rowerowych Singletrack Glacensis</h3>
	<br><img src="data:image/png;base64,{}">
	<br><p></p>'''.format
    iframe = folium.IFrame(html(encoded.decode('UTF-8')),
                           width=420,
                           height=420)
    popup = folium.Popup(iframe, max_width=500)
    icon = folium.Icon(color="red", icon="ok")
    marker = folium.Marker(location=[50.441834, 16.865620],
                           popup=popup,
                           icon=icon)
    marker.add_to(L2)

    # wypożyczalnia rowerów elektrycznych
    png = 'ebike.png'
    encoded = base64.b64encode(open(png, 'rb').read())
    html = '''<h3>Wypożyczalnia rowerów elektrycznych <em>Segbi</em></h3>
	<br><img src="data:image/png;base64,{}">
	<br><p></p>'''.format
    iframe = folium.IFrame(html(encoded.decode('UTF-8')),
                           width=430,
                           height=340)
    popup = folium.Popup(iframe, max_width=500)
    icon = folium.Icon(color="red", icon="ok")
    marker = folium.Marker(location=[50.442673, 16.875021],
                           popup=popup,
                           icon=icon)
    marker.add_to(L2)

    # kaplica cmentarna
    png = 'cmentarz_2.png'
    encoded = base64.b64encode(open(png, 'rb').read())
    html = '''<h3>Późnogotycka Kaplica Cmentarna</h3>
	<br><img src="data:image/png;base64,{}">
	<br><p></p>'''.format
    iframe = folium.IFrame(html(encoded.decode('UTF-8')),
                           width=310,
                           height=520)
    popup = folium.Popup(iframe, max_width=310)
    icon = folium.Icon(color="red", icon="ok")
    marker = folium.Marker(location=[50.445561, 16.875297],
                           popup=popup,
                           icon=icon)
    marker.add_to(L2)

    # kamienica na rynku z portretami
    png = 'zloty1_kamienica_z_portretami.png'
    encoded = base64.b64encode(open(png, 'rb').read())
    html = '''<h3><em>Rynek</em> i jedna z wielu<br/>zabytkowych kamienic</h3>
	<br><img src="data:image/png;base64,{}">
	<br><p></p>'''.format
    iframe = folium.IFrame(html(encoded.decode('UTF-8')),
                           width=420,
                           height=420)
    popup = folium.Popup(iframe, max_width=420)
    icon = folium.Icon(color="red", icon="fa-university", prefix='fa')
    marker = folium.Marker(location=[50.442969, 16.874835],
                           popup=popup,
                           icon=icon)
    marker.add_to(L2)

    # 'wyrobisko'/skala za kopalnią
    png = 'skala.png'
    encoded = base64.b64encode(open(png, 'rb').read())
    html = '''<h3>Widok na potężne wyrobisko i tyrolkę</h3>
	<br><img src="data:image/png;base64,{}">
	<br><p></p>'''.format
    iframe = folium.IFrame(html(encoded.decode('UTF-8')),
                           width=420,
                           height=400)
    popup = folium.Popup(iframe, max_width=420)
    icon = folium.Icon(color="red", icon="ok")
    marker = folium.Marker(location=[50.436968, 16.872321],
                           popup=popup,
                           icon=icon)
    marker.add_to(L2)

    # meleks zdjecie z gazety
    png = 'melex.png'
    encoded = base64.b64encode(open(png, 'rb').read())
    html = '''<h3>Punkt Informacji Turystycznej i możliwość zwiedzania miasta melexem</h3>
	<br><img src="data:image/png;base64,{}">
	<br><p></p>'''.format
    iframe = folium.IFrame(html(encoded.decode('UTF-8')),
                           width=420,
                           height=400)
    popup = folium.Popup(iframe, max_width=420)
    icon = folium.Icon(color="red", icon="ok")
    marker = folium.Marker(location=[50.442837, 16.874020],
                           popup=popup,
                           icon=icon)
    marker.add_to(L2)

    # park techniki
    png = 'park_techniki_2.png'
    encoded = base64.b64encode(open(png, 'rb').read())
    html = '''<h3>Średniowieczny Park Techniki</h3>
	<br><img src="data:image/png;base64,{}">
	<br><p></p>'''.format
    iframe = folium.IFrame(html(encoded.decode('UTF-8')),
                           width=420,
                           height=460)
    popup = folium.Popup(iframe, max_width=420)
    icon = folium.Icon(color="red", icon="ok")
    marker = folium.Marker(location=[50.444541, 16.879349],
                           popup=popup,
                           icon=icon)
    marker.add_to(L2)

    ################################################################
    ################################################################
    # NASZE POMYSŁY
    ################################################################

    # wiata gastronomiczna na rynku lub obok singla
    png = 'wiata.png'
    encoded = base64.b64encode(open(png, 'rb').read())
    html = '''<h3>Przykładowe wykonanie i poglądowe umiejscowienie wiaty gastronomicznej</h3>
	<br><img src="data:image/png;base64,{}">
	<br><p></p>'''.format
    iframe = folium.IFrame(html(encoded.decode('UTF-8')),
                           width=420,
                           height=400)
    popup = folium.Popup(iframe, max_width=420)
    icon = folium.Icon(color="green", icon="home")
    marker = folium.Marker(location=[50.440978, 16.874471],
                           popup=popup,
                           icon=icon)
    marker.add_to(L5)

    # napisy promocyjne z hashtagiem przy wjazdach do miasta
    png = 'zdjecie_napisu.png'
    encoded = base64.b64encode(open(png, 'rb').read())
    html = '''<h3>Napisy powiązane z akcją promocyjną</h3>
	<br><img src="data:image/png;base64,{}">
	<br><p></p>'''.format
    iframe = folium.IFrame(html(encoded.decode('UTF-8')),
                           width=410,
                           height=400)
    popup = folium.Popup(iframe, max_width=420)
    icon = folium.Icon(color="green", icon="fa-hashtag", prefix='fa')
    marker = folium.Marker(location=[50.447121, 16.864869],
                           popup=popup,
                           icon=icon)
    marker.add_to(L5)

    # atrakcyjne dzialki
    png = 'pole.png'
    encoded = base64.b64encode(open(png, 'rb').read())
    html = '''<h3>Korzystny dla miasta podział działki</h3>
	<br><img src="data:image/png;base64,{}">
	<br><p></p>'''.format
    iframe = folium.IFrame(html(encoded.decode('UTF-8')),
                           width=420,
                           height=485)
    popup = folium.Popup(iframe, max_width=420)
    icon = folium.Icon(color="green", icon="fa-pie-chart", prefix='fa')
    marker = folium.Marker(location=[50.445954, 16.873068],
                           popup=popup,
                           icon=icon)
    marker.add_to(L5)

    ###############################################################
    # PODZIAŁ DZIAŁEK
    ###############################################################

    # Wyznaczanie (pogladowe) dzialki
    oryginal_field = folium.vector_layers.Polygon(
        [[50.446811, 16.873717], [50.445823, 16.873545],
         [50.445416, 16.873196], [50.445481, 16.873051]],
        popup="Działka w aktualnej postaci",
        fill_color='blue')
    biedronka_field = folium.vector_layers.Polygon(
        [[50.445922, 16.871966], [50.446862, 16.873631], [
            50.446811, 16.873717
        ], [50.446227, 16.873619], [50.445643, 16.872632]],
        popup="Działka supermarketu po zamianie",
        fill_color='green')
    golden_field = folium.vector_layers.Polygon(
        [[50.445823, 16.873545], [50.445416, 16.873196],
         [50.445643, 16.872637], [50.446215, 16.873622]],
        popup="Działka miasta po zamianie",
        fill_color='red')
    oryginal_field.add_to(L3)
    biedronka_field.add_to(L4)
    golden_field.add_to(L4)

    ################################################################
    ################################################################

    ################################################################
    ################################################################
    # POWSTAJACE ATRAKCJE
    ################################################################

    # sciezka laczaca kopalnie z rynkiem
    png = 'trasa.png'
    encoded = base64.b64encode(open(png, 'rb').read())
    html = '''<h3>Atrakcyjna ścieżka kopalnia-rynek</h3>
	<br><img src="data:image/png;base64,{}">
	<br><p></p>'''.format
    iframe = folium.IFrame(html(encoded.decode('UTF-8')),
                           width=420,
                           height=400)
    popup = folium.Popup(iframe, max_width=420)
    icon = folium.Icon(color="darkgreen", icon="fa-child", prefix='fa')
    marker = folium.Marker(location=[50.440397, 16.875159],
                           popup=popup,
                           icon=icon)
    marker.add_to(L6)

    # wieża widokowa na kościele ewangelickim
    png = "wieza.png"
    encoded = base64.b64encode(open(png, 'rb').read())
    html = '''<h3>Platforma widokowa na szczycie wieży kościelnej</h3>
	<br><img src="data:image/png;base64,{}">
	<br><p></p>'''.format
    iframe = folium.IFrame(html(encoded.decode('UTF-8')),
                           width=320,
                           height=520)
    popup = folium.Popup(iframe, max_width=320)
    icon = folium.Icon(color="darkgreen", icon="fa-child", prefix='fa')
    marker = folium.Marker(location=[50.442686, 16.873486],
                           popup=popup,
                           icon=icon)
    marker.add_to(L6)

    ################################################################
    ################################################################
    # ANALIZA ANKIETY
    ################################################################

    # wieża widokowa na kościele ewangelickim
    png = image_edition_1("pie_chart")
    encoded = base64.b64encode(open(png, 'rb').read())
    html = '''<br><img src="data:image/png;base64,{}">
	<br><p></p>'''.format
    iframe = folium.IFrame(html(encoded.decode('UTF-8')),
                           width=820,
                           height=620)
    popup = folium.Popup(iframe, max_width=820)
    icon = folium.Icon(color="cadetblue", icon="fa-line-chart", prefix='fa')
    marker = folium.Marker(location=[50.435845, 16.861167],
                           popup=popup,
                           icon=icon)
    marker.add_to(L7)

    # dodawanie warstw do mapy
    L1.add_to(myMap)
    L2.add_to(myMap)
    L3.add_to(myMap)
    L4.add_to(myMap)
    L5.add_to(myMap)
    L6.add_to(myMap)
    L7.add_to(myMap)
    LC.add_to(myMap)

    template = """
	{% macro html(this, kwargs) %}

	<!doctype html>
	<html lang="en">
	<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>jQuery UI Draggable - Default functionality</title>
	<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

	<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
	<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

	<script>
	$( function() {
	$( "#maplegend" ).draggable({
					start: function (event, ui) {
						$(this).css({
							right: "auto",
							top: "auto",
							bottom: "auto"
						});
					}
				});
	});

	</script>
	</head>
	<body>


	<div id='maplegend' class='maplegend' 
	style='position: absolute; z-index:9999; border:2px solid grey; background-color:rgba(255, 255, 255, 0.8);
	 border-radius:6px; padding: 10px; font-size:14px; right: 20px; bottom: 20px;'>
	 
	<div class='legend-title'>Legenda znaczników</div>
	<div class='legend-scale'>
	<ul class='legend-labels'>
	<li><span style='background:#d33d29;opacity:1;'></span>Atrakcje obecne w roku 2020</li>
	<li><span style='background:#6da824;opacity:1;'></span>Propozycje uczestników SLL</li>
	<li><span style='background:#6f7f23;opacity:1;'></span>Powstające atrakcje</li>
	<li><span style='background:#FF5050;opacity:1;'></span>Ścieżka prowadząca od kopalni do rynku</li>
	<li><span style='background:#349ceb;opacity:1;'></span>(i inne odcienie niebieskiego) Ważne szlaki komunikacyjne</li>
	<li><span style='background:#5f9ea0;opacity:1;'></span>Wyniki ankietyzacji kolarzy</li>

	</ul>
	</div>
	</div>

	</body>
	</html>

	<style type='text/css'>
	.maplegend .legend-title {
	text-align: left;
	margin-bottom: 5px;
	font-weight: bold;
	font-size: 80%;
	}
	.maplegend .legend-scale ul {
	margin: 0;
	margin-bottom: 5px;
	padding: 0;
	float: left;
	list-style: none;
	}
	.maplegend .legend-scale ul li {
	font-size: 70%;
	list-style: none;
	margin-left: 0;
	line-height: 18px;
	margin-bottom: 2px;
	}
	.maplegend ul.legend-labels li span {
	display: block;
	float: left;
	height: 16px;
	width: 30px;
	margin-right: 5px;
	margin-left: 0;
	border: 1px solid #999;
	}
	.maplegend .legend-source {
	font-size: 70%;
	color: #777;
	clear: both;
	}
	.maplegend a {
	color: #777;
	}
	</style>
	{% endmacro %}"""

    macro = MacroElement()
    macro._template = Template(template)

    myMap.get_root().add_child(macro)

    folium.plugins.Fullscreen(position='topright',
                              title='wypełnij ekran',
                              title_cancel='wyłącz tryb pełnego ekranu',
                              force_separate_button=True).add_to(myMap)
    return (myMap)
예제 #16
0
파일: map1.py 프로젝트: Anish-Malla/Mapping
df_volcanoes = pd.read_csv("volcanoes.csv")
lat_volcanoes = list(df_volcanoes["LAT"])
lon_volcanoes = list(df_volcanoes["LON"])
elevation_volcanoes = list(df_volcanoes['ELEV'])
name_volacnoes = list(df_volcanoes["NAME"])

html = """
<h4>Volcano info:</h4>
Name: %s <br>
Elevation = %s m
"""

fgv = folium.FeatureGroup(name="Volcanoes")

for lat, lon, elev, name in zip(lat_volcanoes,lon_volcanoes, elevation_volcanoes, name_volacnoes):
    iframe = folium.IFrame(html=html % (str(name), str(elev)), width=200, height=100)
    fgv.add_child(folium.CircleMarker(location=[lat, lon], popup=folium.Popup(iframe), fill_color=deciding_color(elev),
    radius=6, color="white", fill_opacity=0.8))

fgp = folium.FeatureGroup(name="Population")

fgp.add_child(folium.GeoJson(data=open("world.json", "r", encoding="utf-8-sig").read(),
style_function=lambda x:{"fillColor":"yellow" if x["properties"]["POP2005"] < 10_000_000 else "orange" if 10_000_000 <=
x["properties"]["POP2005"] < 20_000_000 else "red"}))

map.add_child(fgv)
map.add_child(fgp)
map.add_child(folium.LayerControl())

map.save("Map1.html")
예제 #17
0
    date = data['date']


    geolocator = Nominatim()
    location = geolocator.geocode(result+ " ,Mauritius")
    print((location.latitude, location.longitude))
    long = location.longitude
    lat = location.latitude


    html="""
        <p>
        Disease alert:"""+disease+""" at """+date +"""
        </p>
    """
    iframe = folium.IFrame(html=html, width=300, height=100)
    popup = folium.Popup(iframe, max_width=1000)

    folium.Marker([lat, long], popup=popup).add_to(m)

m.save("map.html")

# Place map -- using googlemaps API
"""


gmap = gmplot.GoogleMapPlotter(-20, 57, 10)
gmap.marker(lat, long, "FF0000")

gmap.draw("my_map2.html")"""
예제 #18
0
def generate_map(df_listings_filtered):
    folium_map = \
        folium.Map(location=[52.516266, 13.377775],
                   zoom_start=13,
                   tiles='OpenStreetMap',
                   )

    for index, row in df_listings_filtered.iterrows():
        title = row["title"]
        price = row["price"]
        livingSpace = row["livingSpace"]
        latitude = row["latitude"]
        longitude = row["longitude"]
        street = row["street"]
        quarter = row["quarter"]
        numberOfRooms = int(row["numberOfRooms"])
        balcony = row["balcony"]
        garden = row["garden"]
        monthlyRate = row["monthlyRate"]
        builtInKitchen = row["builtInKitchen"]
        home_url = row["home_url"]

        html = f'''
        <b>Title</b>: {title}<br>
        <b>Price</b>: {price} <br>
        <b>LivingSpace</b>: {livingSpace} <br>
        <b>Street</b>: {street} <br>
        <b>Quarter</b>: {quarter} <br>
        <b>NumberOfRooms</b>: {numberOfRooms} <br>
        <b>Balcony</b>: {balcony} <br>
        <b>Garden</b>: {garden} <br>
        <b>MonthlyRate</b>: {monthlyRate} <br>
        <b>BuiltInKitchen</b>: {builtInKitchen} <br>
        <b>home_url</b>: <a href="{home_url}">{home_url}</a> <br>
        '''

        iframe = folium.IFrame(html, width=450, height=250)

        popup = folium.Popup(iframe, max_width=450)

        if numberOfRooms == 1:
            color = "#cc3139"  # Red
        elif numberOfRooms == 2:
            color = "#39cc31"  # Green
        elif numberOfRooms >= 3:
            color = "#3139cc"  # Blue
        else:
            color = "#cc3139"

        folium.CircleMarker(location=[latitude, longitude],
                            radius=3,
                            popup=popup,
                            color=color,
                            fill=True).add_to(folium_map)

    now = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
    legend = f'Urutu Find a Home. Last update: {now}'

    title_html = '''
                 <h3 align="center" style="font-size:16px"><b>{}</b></h3>
                 '''.format(legend)

    folium_map.get_root().html.add_child(folium.Element(title_html))

    folium_map.save("index.html")
예제 #19
0
hheight = list(volcano_data["ELEV"])

map = folium.Map(location=[lat[0], lon[0]],
                 zoom_start=6,
                 tiles="Stamen Terrain")
features = folium.FeatureGroup("Mapq_feat")

html = """
Volcano name:<br>
<a href="https://www.google.com/search?q=%%22%s%%22" target="_blank">%s</a><br>
Height: %s m
"""

for lt, ln, nm, h in zip(lat, lon, name, hheight):
    iframe = folium.IFrame(html=html % ("Volcano " + nm, nm, h),
                           width=100,
                           height=200,
                           ratio=60)
    #features.add_child(folium.Marker(location = [lt,ln], popup= folium.Popup(iframe), icon= folium.Icon(color=marker_color(h))))
    features.add_child(
        folium.CircleMarker(location=[lt, ln],
                            radius=5,
                            popup=folium.Popup(iframe),
                            tooltip='Volcano',
                            fill_color=marker_color(h),
                            color='grey',
                            fill_opacity=0.7))

features.add_child(
    folium.GeoJson(data=open('world.json', 'r', encoding='utf-8-sig').read(),
                   style_function=lambda x: {
                       'fillColor':
예제 #20
0
파일: map.py 프로젝트: BlueSaNGG/HTML_MAP
#add_child  加入object
fgv = folium.FeatureGroup(name="Volcanoes")  #特征层,在该层addchild


def color_producer(height):
    if height < 1000:
        return "green"
    elif height < 3000:
        return "orange"
    else:
        return "red"


for lt, ln, el, name in zip(lat, lon, elev,
                            name):  #同时遍历两个列表——zip   i进入lat, j进入lon
    iframe = folium.IFrame(html=html % (name, name, el), width=177, height=77)
    fgv.add_child(
        folium.CircleMarker(location=[lt, ln],
                            popup=folium.Popup(iframe),
                            tooltip="Click to get more information",
                            radius=6,
                            fill=True,
                            fill_opacity=0.7,
                            color=color_producer(el)))
#如果火山不放在featuregroup层里,则添加几次就有几个层

fgp = folium.FeatureGroup(
    name="Population")  #需要传入str类型  popup=folium.Popup(str(el),parse_html=True)
#加入polygamy层
#得到一个GeoJson object
fgp.add_child(
예제 #21
0
import folium
import pandas

data = pandas.read_csv("Volcanoes.txt")
lat = list(data["LAT"])
lon = list(data["LON"])
elev = list(data["ELEV"])
name = list(data["NAME"])

html = """
Volcano name:<br>
<a href="https://www.google.com/search?q=%%22%s%%22" target="_blank">%s</a><br>
Height: %s m
"""

map = folium.Map(location=[38.58, -99.09], zoom_start=5, tiles="Stamen Terrain")
fg = folium.FeatureGroup(name="My Map")

for lt, ln, el, name in zip(lat, lon, elev, name):
    iframe = folium.IFrame(html=html % (name, name, el), width=200, height=100)
    fg.add_child(folium.Marker(location=[lt, ln], popup=folium.Popup(iframe), icon=folium.Icon(color="red")))

map.add_child(fg)
map.save("Map1.html")
예제 #22
0
        return "green"


html = """<h4>Volcano information:</h4>
<b>Name:</b> %s
<br>
<b>Height:</b> %s m
"""

map = folium.Map(location=[38.58, -99.09], zoom_start=6, tiles="Mapbox Bright")

fg_volcanoes = folium.FeatureGroup(name="American volcanoes map")
fg_population = folium.FeatureGroup(name="World population map")

for lt, ln, nm, ev in zip(lat, lon, name, elev):
    iframe = folium.IFrame(html=html % (nm, ev), width=200, height=100)

    fg_volcanoes.add_child(
        folium.CircleMarker(location=[lt, ln],
                            radius=10,
                            popup=folium.Popup(iframe),
                            fill_color=marker_color(ev),
                            color="black",
                            fill_opacity=0.7))

fg_population.add_child(
    folium.GeoJson(
        data=(open("world.json", "r", encoding="utf-8-sig").read()),
        style_function=lambda x: {
            "fillColor":
            "green" if x["properties"]["POP2005"] < 10000000 else "orange"
예제 #23
0
def plot_map_tpu(tpu_name, tpu_data, main_df, translit=False):
    """
    This function visualizes shopping facilities, which are in the reach 
    distance of transport hub specified in tpu_name 
    """
    geolocator = Nominatim(user_agent="demo")

    tpu_lat = float(tpu_data[tpu_data['TPUName'] ==
                             tpu_name].tpu_latitude.values[0]['center'])
    tpu_lng = float(tpu_data[tpu_data['TPUName'] ==
                             tpu_name].tpu_longitude.values[0]['center'])
    tpu_stat = tpu_data[tpu_data['TPUName'] == tpu_name].Status.values[0]
    tpu_year = tpu_data[tpu_data['TPUName'] ==
                        tpu_name].YearOfComissioning.values[0]
    tpu_transfer = tpu_data[tpu_data['TPUName'] ==
                            tpu_name].AvailableTransfer.values[0]
    tpu_slots = float(tpu_data[tpu_data['TPUName'] == tpu_name].CarCapacity)

    latitude = tpu_lat
    longitude = tpu_lng

    obj_icons = [
        'shopping-basket', 'shopping-cart', 'shopping-bag', 'building',
        'institution'
    ]
    #icon_colors = ['#009900', '#0099ff', '#660066', '#cc9900', '#669999']
    icon_colors = ['#3366CC', '#3366CC', '#3366CC', '#3366CC', '#3366CC']

    maps = folium.Map(location=[latitude, longitude],
                      tiles='cartodbpositron',
                      zoom_start=14.5)
    # Add map types
    folium.TileLayer('Stamen Toner').add_to(maps)
    folium.TileLayer('OpenStreetMap').add_to(maps)

    # Add transport hub
    description = f'<p><b>TPU name: {tpu_name}<br>'
    description += f' ({tpu_stat})</b><br><hr>'
    description += f'<p>Year of comissioning: {tpu_year}'
    description += f'<p>Availible transfer:<br><ul>'
    for option in tpu_transfer.split(';'):
        description += f'<li>{option.lower()}'
    description += f'</ul><p>Availible parking slots: {tpu_slots}'

    if translit == True:
        description = transliterate(description)
    iframe = folium.IFrame(html=description, width=600, height=300)
    popup_description = folium.Popup(iframe, max_width=2650)

    folium.Marker(location=[float(tpu_lat), float(tpu_lng)],
                  popup=popup_description,
                  tooltip=transliterate(tpu_name),
                  icon=folium.Icon(color='red', icon='train',
                                   prefix='fa')).add_to(maps)

    # Add trade places
    input_df = main_df[(main_df['tpu_name'] == tpu_name) & (
        main_df['object_real_reach_distance'] >= main_df['distance_to_tpu'])]

    for address_name in input_df.object_address.unique():
        info = {}
        obj_counter = 0
        tmp_obj_df = input_df[input_df.object_address == address_name]
        info['lat'], info['lng'] = tmp_obj_df.iloc[0].object_latitude,\
                                 tmp_obj_df.iloc[0].object_longitude
        for curr_obj_size in tmp_obj_df.object_size.unique():
            curr_obj_data = []

            for name, descr in zip(tmp_obj_df[tmp_obj_df.object_size==\
                                                    curr_obj_size].object_name,
                               tmp_obj_df[tmp_obj_df.object_size==\
                                                    curr_obj_size].object_type):
                curr_obj_data.append(name + ' - <i>' + descr + '<i>')
            obj_counter += len(curr_obj_data)
            info[curr_obj_size] = curr_obj_data

        size_names = {1: 'Small', 2: 'Medium', 3: 'Large'}
        description = f'<p><b>Objects total: {str(obj_counter)}</b><br>'
        description += f'<p>Closest TPU: {tmp_obj_df.tpu_name.iloc[0]}'
        description += f' in {round(tmp_obj_df.distance_to_tpu.iloc[0],0)} m.<br>'
        description += f'<p>Nearest station: {tmp_obj_df.tpu_near_station.iloc[0]}<br><hr>'
        for curr_obj_size in np.sort(tmp_obj_df.object_size.unique())[::-1]:
            if curr_obj_size in info:
                description += f'<b>{size_names[curr_obj_size]} objects total: '
                description += str(len(info[curr_obj_size])) + '</b><ul>'
                for obj_info in info[curr_obj_size]:
                    description += (f'<li>{obj_info}')
                description += '</ul><hr><br>'
        if translit == True:
            description = transliterate(description)
        iframe = folium.IFrame(html=description, width=600, height=300)
        popup_description = folium.Popup(iframe, max_width=2650)

        for i in range(0, 3):
            if i + 1 in info.keys():
                marker_color = icon_colors[i]
                marker_icon = obj_icons[i]

        if 1 < obj_counter <= 10:
            marker_icon = obj_icons[3]
            marker_color = icon_colors[3]
        if obj_counter > 10:
            marker_icon = obj_icons[4]
            marker_color = icon_colors[4]

        folium.Marker(location=[info['lat'], info['lng']],
                      popup=popup_description,
                      tooltip=transliterate(f'{address_name} - ' +\
                                            f'{obj_counter} мест(а)')[14:],
                      icon=BI(icon=marker_icon,
                              icon_shape='circle',
                              border_width=2,
                              border_color=marker_color,
                              text_color='#ffffff',
                              #iconSize = [28, 28],
                              #innerIconAnchor = [0, 5],
                              background_color=marker_color
                              )).add_to(maps)

    folium.LayerControl().add_to(maps)

    return maps
예제 #24
0
def color_picker(province):
    u_province = list(df['province'].unique())
    #print(u_province)
    if province == u_province[1]:
        return "blue"
    """elif province == u_province[2]:
        return "red"
    elif province == u_province[3]:
        return "green" """


my_map = folium.Map(location=[7.3041622, 126.0893406], zoom_start=10)
fg = folium.FeatureGroup(name="Coordinates")
for lt, ln, add, code, prov in zip(lat, lon, address, psgc_code, province):
    iframe = folium.IFrame(html=html % (str(code), str(add)),
                           width=200,
                           height=100)
    fg.add_child(
        folium.CircleMarker(location=[lt, ln],
                            radius=7,
                            popup=folium.Popup(iframe),
                            fill_color=color_picker(prov),
                            color='grey',
                            fill=True,
                            fill_opacity=0.8))

fgb = folium.FeatureGroup(name="Barangay")
for json_file in json_files:
    fgb.add_child(
        folium.GeoJson(data=open(
            path_to_json +
예제 #25
0
        return 'green'
    elif 1000 <= elev < 3000:
        return 'orange'
    else:
        return 'red'

map = folium.Map(location=values[0][:2],zoom_start=4,\
                 tiles='Stamen Terrain')

#This msg will be displayed if you hover over the marker.
tooltip = "Click!"

#Feature Group for Volcanoes data.
fgv = folium.FeatureGroup(name="Volcanoes")
for val in values:
    iframe = folium.IFrame(html=html % (val[-1], val[-1], str(val[-2])),\
             width=200, height=70)
    # fg.add_child(folium.Marker(location=val[:2],popup=folium.Popup(iframe),\
    #  icon=folium.Icon(color=color_func(val[-2])),tooltip=tooltip))
    fgv.add_child(folium.CircleMarker(location=val[:2],popup=folium.Popup(iframe),\
                radius=5, fill_color= color_func(val[-2]), color='grey',\
                fill_opacity =0.7,))

#Feature Group for Population data.
fgp = folium.FeatureGroup(name="Population")
fgp.add_child(folium.GeoJson(data=open('world.json','r',\
    encoding='utf-8-sig').read(),style_function=lambda x:{'fillColor':'green'\
            if x['properties']['POP2005']<10000000 else 'orange'\
            if 10000000 <= x['properties']['POP2005']<20000000 else 'red'}))

map.add_child(fgv)
map.add_child(fgp)
예제 #26
0
            x = (lat1 + lat2) / 2.0
            y = (lon1 + lon2) / 2.0
        else:
            (x, y, radius) = sec.make_circle(clusters[clusterId]['points'])
        distance = calculate_radius_in_meters(x, y, radius) * 2
        print('Cluster', clusterId, 'center', x, y, distance)

        points_ids = []
        for l in sorted(clusters[clusterId]['points']):
            for p in locations[l]:
                points_ids.append("ids=" + p[1])

        iframe = folium.IFrame(
            html=
            '''<a href="http://127.0.0.1:8080/searchIds/?{}">[Open in DB] </a>Cluster {} [{}] {}<br>'''
            .format("&".join(points_ids), str(clusterId), points_in_cluster,
                    clusters[clusterId]['color']),
            width=500,
            height=300)
        p = folium.Popup(iframe, max_width=2650)
        folium.features.Circle(
            radius=distance,
            location=[x, y],
            popup=p,
            color=clusters[clusterId]['color'],
            fill=True,
        ).add_to(circles_fg)

    location_list = []
    popups = []
    icons = []
예제 #27
0
파일: base.py 프로젝트: rajat2654/folmap
fg = folium.FeatureGroup(name="MYMAP")
fg1 = folium.FeatureGroup(name="MYMAP1")
dd = pandas.read_csv("Volcanoes.txt")
s1 = list(dd["LAT"])
s2 = list(dd["LON"])
el = list(dd["ELEV"])
name = list(dd["NAME"])

html = """<h4>Volcano info</h4>
Name = 
<a href="https://www.google.com/search?q=%s" target="_blank">%s</a><br>
Height = %s m
"""

for i in range(len(dd)):
    ifr = folium.IFrame(html=html % (name[i], name[i], str(el[i])), height=100, width=200)
    if el[i] < 1000:
        col = "green"
    elif el[i] < 2000:
        col = "blue"
    elif el[i]<3000:
        col = "orange"
    else:
        col = "red"
    fg.add_child(folium.Marker(location=[s1[i], s2[i]],
    popup=folium.Popup(ifr), icon=folium.Icon(color=col), tooltip= name[i]))

fg1.add_child(folium.GeoJson(data=open("world.json", "r", encoding="utf-8-sig").read(),
style_function = lambda x: {"fillColor":"red" if x["properties"]["POP2005"] < 1000000000 else "blue"}))

mapp.add_child(fg)
예제 #28
0
places = file1.readlines()
file1.close()

html = """
<a href="https://www.google.com/search?q=%s" target="_blank">%s</a>
"""

fg = folium.FeatureGroup(name="My places")
map = folium.Map(location=[52, 21], zoom_start=10)

coordinates = []
file2 = open("web_map\\data\\coordinates.txt", "r+")
for i in range(len(places)):
    coordinates.append(nom.geocode(places[i]))
    file2.write(
        str(coordinates[i].latitude) + "," + str(coordinates[i].longitude) +
        "\n")
    iframe = folium.IFrame(html=html % (places[i], places[i]),
                           width=75,
                           height=35)
    fg.add_child(
        folium.Marker(
            location=[coordinates[i].latitude, coordinates[i].longitude],
            zoom_start=4,
            color="red",
            popup=folium.Popup(iframe)))
file2.close()

map.add_child(fg)
map.save("web_map\\html\\moje_miejsca.html")
webbrowser.open("web_map\\html\\moje_miejsca.html")
예제 #29
0

def elev_c(e):
    if e < 1000:
        return 'green'
    elif 1000 <= e < 3000:
        return 'red'
    else:
        return 'blue'


html1 = """<h4>%</h4>"""

fgv = folium.FeatureGroup(name="Volcanoes")
for lt, ln, n, elev in zip(lat, lon, n, elev):
    iframe = folium.IFrame(html=html % (n, elev), width=200, height=100)
    fgv.add_child(
        folium.Circle(location=[lt, ln],
                      popup=folium.Popup(iframe),
                      color=elev_c(elev),
                      radius=1000))

for i in v.index:
    #name = v['Dominant Rock Type'][i]
    iframe = folium.IFrame(html=html %
                           (v['Volcano Name'][i], v['Elevation (m)'][i]),
                           width=200,
                           height=100)
    if (math.isnan(v['Latitude'][i])):
        pass
    else:
예제 #30
0
# Compute average for color production
volcano_elev_avg = round(mean(volcano_elev), 0)

# Configure html so that the popup windows include the volcano's name and height, including a link to search for specific volcanoes
html = """
Volcano name:<br>
<a href="https://www.google.com/search?q=%%22%s%%22" target="_blank">%s</a><br>
Height: %s m
"""

# Add markers to map for volcanoes
for lat, lon, elev, name in zip(volcano_lat, volcano_lon, volcano_elev,
                                volcano_name):
    iframe = folium.IFrame(html=html % (name + " volcano", name, elev),
                           width=200,
                           height=100)
    volcano_fg.add_child(
        folium.CircleMarker(location=[lat, lon],
                            radius=6,
                            fill=True,
                            popup=folium.Popup(iframe),
                            fill_color=color_producer(elev, volcano_elev_avg),
                            color='grey',
                            fill_opacity=0.7))

# Add data for population of countries, loaded from json file. Set fillColor by population
pop_fg.add_child(
    folium.GeoJson(
        data=open('world.json', 'r', encoding='utf-8-sig').read(),
        style_function=lambda x: {