コード例 #1
0
        col_int = divmod(nval, col_range)
        ci = int(col_int[0])
        r = col_int[1] / col_range
        if (r > 0.0 and ci < ncol):
            c0 = cb2_ordrd_rgb[ci]
            c1 = cb2_ordrd_rgb[ci + 1]
            col = (int((1.0 - r) * c0[0] + r * c1[0]),
                   int((1.0 - r) * c0[1] + r * c1[1]),
                   int((1.0 - r) * c0[2] + r * c1[2]))
            c_string = '#{:02x}{:02x}{:02x}'.format(col[0], col[1], col[2])

        if (val > 0):
            fm.Circle((center_y, center_x),
                      radius=15000,
                      color=c_string,
                      fill_color=c_string,
                      fill=True,
                      weight=0,
                      fill_opacity=0.25 + (nval * 0.5),
                      popup='Maximum count: {}'.format(val)).add_to(m)

#m.save('spatio-temporal.html')

k = 12
cluster_id_col_name = 'Cluster ID(k={})'.format(k)

kmeans = KMeans(n_clusters=k, random_state=42)
clus = kmeans.fit(time_series)

time_series[cluster_id_col_name] = clus.labels_

centroid = pd.DataFrame(data=clus.cluster_centers_,
コード例 #2
0
                        zoom_start=10)
# Marker for the Gateway of India
folium.Marker(location=[18.9220, 72.8347],
              popup='Gateway Of India',
              icon=folium.Icon(color='red')).add_to(map_mumbai)
# Marker for the Mumbai international airport.
folium.CircleMarker(location=[19.0896, 72.8656],
                    radius=50,
                    popup='Mumbai international airport',
                    color='#0000ff',
                    fill=True,
                    fill_color='#0000ff').add_to(map_mumbai)
# Marker for the Dharavi slum in Mumbai.
folium.Circle(location=[19.0380, 72.8538],
              radius=1000,
              popup='Dharavi slum',
              color='#ff0000',
              fill=False).add_to(map_mumbai)

map_mumbai
"""As you zoom-in and out of the map, the radius of the circular marker created using the `folium.Circle()` function increases and decreases whereas the radius of the circular marker created using the `folium.CircleMarker()` remains the same because the latter circular marker occupies the fixed number of pixels on the map.


So, that's it for this class. In the next class, we will create cartograms and add the markers for the meteorite landing sites. Here's one of the examples:

<img src='https://student-datasets-bucket.s3.ap-south-1.amazonaws.com/images/lesson-22/sample_met_lands_cartogram.png' width=900>

You repeat the same activities covered in this class by creating a cartogram for New Delhi or any other city you like. You can get the coordinates of your desired place through Google. 

If you are interested, you can read more about the `folium` module by clicking on the link provided in the **Activities** section under the title **Folium Documentation**.
コード例 #3
0
ファイル: views.py プロジェクト: SoloshenkoVeronika/Master
def multi2(request):
    print("______________Multi2_____________________________________")
    installations = Installation.objects.order_by('id')
    flag_model4 = 1
    error = ''
    list_numner_vessels = []
    print("!!!number_ERRV=", number_ERRV)
    for i in range(number_ERRV):
        list_numner_vessels.append(number_ERRV)

    print("list_numner_vessels=", list_numner_vessels)

    if request.method == 'POST':
        pp = request.POST.get("pp", "")
        wa = request.POST.get("wa", "")
        ww = request.POST.get("ww", "")
        wr = request.POST.get("wr", "")
        age = request.POST.getlist("age")
        # risk1 = 0.1
        # risk21 = 0.1
        # risk22 = 0.3
        # risk31 = 0.1
        # risk32 = 0.2
        # risk33 = 0.3
        # risk4 = 0.5
        #
        # risk_list = []
        # risk2 = 1 - (1-float(risk21))*(1-float(risk22))
        # risk3 = 1 - (1-float(risk31))*(1-float(risk32))*(1-float(risk33))
        # risk_sum = 1-(1-float(risk1))*(1-float(risk2))*(1-float(risk3))*(1-float(risk4))
        # risk_list.append(risk_sum)
        # risk_list.append(4)
        # full_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "recources")
        # filename = "Probability0.txt"
        # FileFullPath = os.path.join(full_path, filename)
        # with open(FileFullPath, 'w') as f:
        #     for i in risk_list:
        #         f.write(str(i)+"\n")
        #
        # print("risk_list=",risk_list)
        #
        # model_risk(wr,wt)
        # #model_risk(wr,wt)
        print("pp=", pp, " ", wa, " ", ww, " ", wr, " ", age, " ")
        context = {
            #'installations':installations,
            'title': "About"
        }

        test_list = [int(i) for i in age]
        errv_ages = tuple(test_list)

        crush_prob_res = crush_prob(pp, errv_ages)
        model2(ins_fix_list_g, flag_model4)
        print(
            "________________))))))))))))))))+++++++++++++++_____________(((((((((((((()))))))0"
        )
        model3(ins_fix_list_g, flag_model4)
        model4(ins_fix_list_g, flag_model4)
        model5(ins_fix_list_g, wa, ww, wr)
        #creation of map comes here + business logic
        m = folium.Map([62.354457, 2.377184], zoom_start=6)

        #Load Data
        data = pd.read_csv('main\\recources\\Data_Map.txt')
        lat = data['LAT']
        lon = data['LON']
        elevation = data['ELEV']
        name = data['NAME']

        #Function to change colors
        def color_change(elev):
            if (elev == 1):
                return ('blue')
            elif (elev == 2):
                return ('yellow')
            elif (elev == 3):
                return ('red')
            elif (elev == 100):
                return ('purple')

        #Function to change colors
        def radius_change(elev):
            if (elev == 3):
                return 62050
            elif (elev == 5):
                return 124100
            elif (elev == 6):
                return 155125

                #Function to change colors
        def radius_size(elev):
            if (elev == 1):
                return 2
            elif (elev == 2):
                return 1
            elif (elev == 3 or elev == 100):
                return 3

        data2 = pd.read_csv("main\\recources\\Data_Map_ERRV.txt")
        lat2 = data2['LAT']
        lon2 = data2['LON']
        elevation2 = data2['ELEV']

        for lat2, lon2, elevation2 in zip(lat2, lon2, elevation2):
            folium.Circle(location=[lat2, lon2],
                          radius=radius_change(elevation2),
                          popup=str(elevation2) + " m",
                          fill_color='red',
                          fill_opacity=0.05).add_to(m)

        #Plot Markers
        for lat, lon, elevation, name in zip(lat, lon, elevation, name):
            folium.CircleMarker(location=[lat, lon],
                                radius=radius_size(elevation),
                                popup=str(name),
                                fill_color=color_change(elevation),
                                color=color_change(elevation),
                                fill_opacity=0.9).add_to(m)

        m = m._repr_html_()  #updated

        context = {
            'installations': installations,
            'error': error,
            'my_map': m,
            # 'errvs': errvs,
            'title': "Multi-objective model"
        }

        return render(request, 'main/multi.html', context)
    else:
        context = {
            'numner_vessels': list_numner_vessels,
            'title': "Multi-objective model"
        }
        return render(request, 'main/multi2.html', context)
コード例 #4
0
colors = ColorVector(hour, numColors, "YlOrRd")

###############################################################################
#                               5. Make Map                                   #
###############################################################################
# create base map
m = folium.Map(location=[np.mean(lats), np.mean(lngs)],
               tiles='Stamen Toner',
               zoom_start=10)

# loop through properties to add map layers
for i in range(len(lats)):
    folium.Circle(location=[lats[i], lngs[i]],
                  popup=("""<b>{}</b><br>Description: {}""".format(
                      date[i], description[i])),
                  radius=15,
                  color=colors[i],
                  fill=True,
                  fill_opacity=.30).add_to(m)

# save map as html file
m.save('view-1.html')

###############################################################################
#                               6. Heat Map                                   #
###############################################################################
# Make list of list
heat_data = [[lats[ii], lngs[ii]] for ii in range(len(lats))]

# Create base map
m = folium.Map(location=[np.mean(lats), np.mean(lngs)],
コード例 #5
0
                       tiles='cartodbpositron',
                       min_zoom=5,
                       max_zoom=7,
                       control_scale=True)

for i in range(0, len(map_states)):
    state = map_states['State/UnionTerritory'][i]
    cases = map_states['Confirmed'][i]
    deaths = map_states['Deaths'][i]
    cured = map_states['Cured'][i]

    location = Location_dict[state]

    folium.Circle([location[0],location[1]],radius = float(cases * 0.8),color = '#10B4AB',fill_color = 'cyan',
                  fill = True,
                  tooltip = "<h5 style = 'text-align:center;font-weight:bold'>"+state+"</h5>"\
                  + "<div style = 'text-align:center;'>" + "<b>"+'Confirmed : '+"</b>"+ str(cases)+"</div>"\
                  + "<div style = 'text-align:center;'>" + "<b>"+'Recovered : '+"</b>"+ str(cured)+"</div>"\
                  + "<div style = 'text-align:center;'>" + "<b>"+'Deaths : '+"</b>"+ str(deaths)+"</div>").add_to(india_map)

india_map.save('indiamap.html')
india_map
"""We can deduce that the worst-struck states of India are the ones with densely packed urban areas, like Mumbai in Maharashtra, Chennai in Tamil Nadu and New Delhi. Let's see how the total national confirmed cases are distributed.

# Data Analysis
"""

state_report['per cent Confirmed'] = (state_report['Confirmed'] * 100 /
                                      state_report.sum()['Confirmed'])
pie = state_report.drop(
    index=state_report.index[state_report['State/UnionTerritory'] ==
                             'Cases being reassigned to states'])
コード例 #6
0
def most_least_populous(conn, c):
    # the query returns a list of the population of each neighbourhood
    # in a descending order
    c.execute(''' SELECT 
                p.Neighbourhood_Name, Latitude, Longitude,
                CANADIAN_CITIZEN+NON_CANADIAN_CITIZEN+NO_RESPONSE as total_pop
                FROM population p, coordinates c
                WHERE p.Neighbourhood_Name = c.Neighbourhood_Name and total_pop > 0 and c.Latitude <> 0.0 and c.Longitude <> 0
                ORDER BY total_pop DESC''')
    areas = c.fetchall()
    areas = list(areas)

    # get the value of N from the user
    while True:
        try:
            int_N = int(input("Enter number of locations: "))
            if int_N > len(areas):
                print("Out of bounds. Please try again")
                continue
        except Exception as e:
            print("Invalid input. Please try again")
            continue
        break

    # call the first_n_with_ties function to find the N MOST
    # populated neighbourhoods considering ties
    most_populous = areas[:first_n_with_ties(areas, (
        lambda l1, l2: l1[3] == l2[3]), int_N)]

    # reversing the areas list stores the neighbourhoods with their
    # populations in an ascending order
    areas_rev = areas.copy()

    # call the first_n_with_ties function to find the N LEAST
    # populated neighbourhoods considering ties
    areas_rev.reverse()
    least_populous = areas_rev[:first_n_with_ties(areas_rev, (
        lambda l1, l2: l1[3] == l2[3]), int_N)]

    # scale is to scale the populations for the circle markers
    scale = 0
    for i in range(len(most_populous)):
        scale = scale + most_populous[i][3]
    for i in range(len(least_populous)):
        scale = scale + least_populous[i][3]

    # define the area of the map to be shown
    m = folium.Map(location=[53.5444, -113.323], zoom_start=11)

    # map the most populous areas
    for index in range(len(most_populous)):
        folium.Circle(location=[areas[index][1], areas[index][2]],
                      popup=areas[index][0] + "<br>" + str(areas[index][3]),
                      radius=(areas[index][3] / scale) * 5000,
                      color='crimson',
                      fill=True,
                      fill_color='crimson').add_to(m)

    # map the least populous areas
    for index in range(len(least_populous)):
        folium.Circle(location=[areas_rev[index][1], areas_rev[index][2]],
                      popup=areas_rev[index][0] + "<br>" +
                      str(areas_rev[index][3]),
                      radius=(areas_rev[index][3] / scale) * 5000,
                      color='crimson',
                      fill=True,
                      fill_color='crimson').add_to(m)

    # save the mapped areas in a .html file
    m.save(get_filename("Q2", ".html"))
    conn.commit()
    return
コード例 #7
0
def plot_final_state(mdl,current_df,geojson):
        
    # Initiate map
    m = folium.Map(location=[62, 20], zoom_start=5)
    
    # Define styling rules for counties
    def style_function(feature):
        d = feature['properties']['name']    
        
        if current_df.at[d,"RateFinal"] < 0.5:
            if current_df.at[d,"FinalSurplusCapacity"] > 3:
                color = '#7AA826' #green
            else: 
                color = '#FFCA2D' #yellow
        elif 0.5 <= current_df.at[d,"RateFinal"] < 0.9:
            color='#FFCA2D' #yellow
        elif 0.9 <= current_df.at[d,"RateFinal"] <= 1:
            color='#EA830E' #orange   
        elif 1 < current_df.at[d,"RateFinal"]:
            color='#BF2C2A'  #red 
            
        return {'fillOpacity': 0.4,'weight': 0.5,
                'color': 'black','fillColor': color}
    
    # Import geojson data and apply styling rule
    geo = folium.GeoJson(
        geojson,
        name='geojson',
        style_function=style_function
    ).add_to(m)
    
    # Add a clickable circle to each county
    for idx, row in current_df.iterrows():    
    
        # Define styling rules
        if row.RateFinal < 0.5:
            if row.FinalSurplusCapacity > 3:
                color = '#7AA826' #green
            else: 
                color = '#FFCA2D' #yellow
        elif 0.5 <= row.RateFinal < 0.9:
            color='#FFCA2D' #yellow
        elif 0.9 <= row.RateFinal <= 1:
            color='#EA830E' #orange    
        elif 1 < row.RateFinal:
            color='#BF2C2A'  #red  
            
        # Draw circle
        folium.Circle(
            radius= 7000 + row.Final*200,
            location=[row.Lat, row.Long],
            popup=folium.Popup('<b>'+row.Region+'</b><br><br>From '+str(row.IVA)+' to '+str(row.Final)+\
                               ' IVA<br>Organic growth: '+str(row.OrganicGrowth)+\
                               '<br>Allocation: '+str(row.Allocation)+\
                               '<br>Capacity: '+str(row.Capacity),
                               max_width=450,min_width=150),
            color=color,
            fill=True,
            fill_color=color,
            tooltip="Klicka här!",
        ).add_to(m)
      
    # Add arrows and lines
    for (period, d1, d2, nb, il) in mdl.edges: 
        
        # Find arrow coordinates
        coordinates = [[current_df.at[d1,"Lat"], current_df.at[d1,"Long"]], 
                       [current_df.at[d2,"Lat"], current_df.at[d2,"Long"]]]
        
        # Define tooltop
        if nb == 1:
            tooltip = str(nb)+" patient from "+d1+" to "+d2
        elif nb > 1:
            tooltip = str(nb)+" patients from "+d1+" to "+d2
        
        # Draw line
        pl = folium.PolyLine(coordinates, color="black", weight=3,tooltip=tooltip)
        m.add_child(pl)    
        
        # Draw arrows
        arrows = get_arrows(locations=coordinates, color="black", size=3, n_arrows=1)
        for arrow in arrows:
            arrow.add_to(m)
    from branca.element import Template, MacroElement

    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'>Color code explanation</div>
    <div class='legend-scale'>
      <ul class='legend-labels'>
        <li><span style='background:#BF2C2A;opacity:0.7;'></span>Over 100% of capacity</li>
        <li><span style='background:#EA830E;opacity:0.7;'></span>Between 90% and 100% of capacity</li>
        <li><span style='background:#FFCA2D;opacity:0.7;'></span>Between 50% and 90% of capacity</li>
        <li><span style='background:#7AA826;opacity:0.7;'></span>Less than 50% of capacity</li>

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

    </body>
    </html>

    <style type='text/css'>
      .maplegend .legend-title {
        text-align: left;
        margin-bottom: 5px;
        font-weight: bold;
        font-size: 90%;
        }
      .maplegend .legend-scale ul {
        margin: 0;
        margin-bottom: 5px;
        padding: 0;
        float: left;
        list-style: none;
        }
      .maplegend .legend-scale ul li {
        font-size: 80%;
        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: 80%;
        color: #777;
        clear: both;
        }
      .maplegend a {
        color: #777;
        }
    </style>
    {% endmacro %}"""

    macro = MacroElement()
    macro._template = Template(template)
    m.get_root().add_child(macro)
    
    return m
コード例 #8
0
def folium_map_with_circles(your_name, country, map_width, map_height, left_margin, top_margin, map_tile, zoom, circle_color, minimap):
    last_col = conf_df.columns[-1]
    if country == 'India':
        india_map = folium.Map(location = [22.3511148, 78.6677428], 
                               width = map_width, height = map_height,
                               left = f"{left_margin}%", top = f"{top_margin}%",
                               tiles = map_tile, zoom_start = zoom)
        
        if minimap == True:
            add_minimap(india_map)
    
        add_title(india_map, country, your_name)    
        for i in india_df.index:
            folium.Circle(radius = float(india_df.loc[i, 'Confirmed']) / 1.25,
                          location = [india_df.loc[i, 'Latitude'], india_df.loc[i, 'Longitude']],
                          popup = "{}\n {}\n on {}".format(india_df.loc[i, 'State'], 
                                                          india_df.loc[i, 'Confirmed'], 
                                                          india_df.loc[i, 'Last_Updated_Time']),
                          
                          color = circle_color,
                          fill = True).add_to(india_map)
        return india_map

    elif country == 'US':
        us_map = folium.Map(location = [39.381266, -97.922211], 
                            width = map_width, height = map_height, 
                            left = f"{left_margin}%", top = f"{top_margin}%",
                            tiles = map_tile, zoom_start = zoom)
        if minimap == True:
            add_minimap(us_map)
        
        add_title(us_map, country, your_name)
        for i in grouped_us_conf_df.index:
            folium.Circle(location = [grouped_us_conf_df.loc[i, 'Lat'], grouped_us_conf_df.loc[i, 'Long_']], 
                          radius = int(grouped_us_conf_df.loc[i, last_col]), 
                          popup = "{}\n {}\n on {}".format(grouped_us_conf_df.loc[i, 'Combined_Key'],
                                                          grouped_us_conf_df.loc[i, last_col],
                                                          last_col),
                          color = circle_color,
                          fill = True).add_to(us_map)
        return us_map
    
    elif country == 'World':
        world_map = folium.Map(location = [0, 0], 
                            width = map_width, height = map_height, 
                            left = f"{left_margin}%", top = f"{top_margin}%",
                            tiles = map_tile, zoom_start = zoom)
        if minimap == True:
            add_minimap(world_map)
        
        add_title(world_map, country, your_name)
        for i in grouped_conf_df.index:
            folium.Circle(location = [grouped_conf_df.loc[i, 'Lat'], grouped_conf_df.loc[i, 'Long']], 
                          radius = int(grouped_conf_df.loc[i, last_col]) / 2, 
                          popup = "{}\n {}\n on {}".format(grouped_conf_df.loc[i, 'Country/Region'],
                                                          grouped_conf_df.loc[i, last_col], 
                                                          last_col),
                          color = circle_color, 
                          fill = True).add_to(world_map)
        return world_map
    else:
        print("\nWrong input! Enter either India, US or World.\n")
コード例 #9
0
ファイル: danish_predict.py プロジェクト: xuan583636/AIS-LSTM
print('----------------------------------------------------')
print('Average Distance (m): ', avg_dist, ' m')
print('Average Distance (km): ', avg_dist / 1000, ' km')
print('Average Distance (NM): ', avg_dist * 0.00053996, 'NM')
print('----------------------------------------------------')
print('End of danish_predict.py')
print('----------------------------------------------------')

# graph AOU

location_index = 50

center = [prediction[location_index, 0], prediction[location_index, 1]]

m = folium.Map(location=center, tiles="Stamen Toner", zoom_start=12)
'''
# Real Location
folium.Circle(
    radius=20,
    location=[y_test[location_index, 0], y_test[location_index, 1]],
    popup='Real Location',
    color='crimson',
    fill=True,
    fill_color='#ffcccb'
).add_to(m)

# AOU
folium.Circle(
    location=[prediction[location_index, 0], prediction[location_index, 1]],
    radius=avg_dist,  # might want to take largest distance!
    popup='AOU Radius: ' + str(avg_dist) + ' meters',
コード例 #10
0
latitude_list = get_latitude_list(business_data)
longitude_list = get_longitude_list(business_data)
address_list = get_addresses(business_data)
alias_list = get_aliases(business_data)
unique_alias_list = get_unique_aliases(business_data)

vegan_places = ["vegan"]
coffee_places = ["coffee", "breakfast_brunch"]

folium.Marker([start_latitude, start_longitude],
              tooltip="You are here",
              icon=folium.Icon(color='red', icon='info-sign')).add_to(m)

folium.Circle(location=[start_latitude, start_longitude],
              radius=11000,
              popup="Radius of 11000m",
              color='#428bca',
              fill=True,
              fill_color='#428bca').add_to(m)

for i, e in enumerate(latitude_list):
    if alias_list[i] in vegan_places:
        color = "green"
    elif alias_list[i] in coffee_places:
        color = "black"
    else:
        color = "blue"
    folium.Marker([latitude_list[i], longitude_list[i]],
                  popup=address_list[i],
                  tooltip=tooltip,
                  icon=folium.Icon(color=color, icon='leaf')).add_to(m)
コード例 #11
0
ファイル: create-leaflet.py プロジェクト: mpickering/rg-map
        }""")


for image_vrt in images:
    print(image_vrt)
    key = os.path.splitext(os.path.splitext(os.path.basename(image_vrt))[0])[0]
    event = pickle.load(
        open(os.path.join(metadata_dir, '{}.pickle'.format(key)), 'rb'))
    print(key)

    center = GetCenterImage(image_vrt)
    popup = folium.map.Popup(html=make_event_link(event))
    folium.Circle(center,
                  radius=100,
                  popup=popup,
                  color=make_colour(event),
                  fill_color=make_colour(event),
                  fill=True,
                  onclick=flag_click(key)).add_to(m)

tiles_loc = "https://s3-eu-west-1.amazonaws.com/rg-maps/{z}/{x}/{y}.png"
tiles_loc_dev = "{z}/{x}/{y}.png"

img = folium.raster_layers.TileLayer(tiles=tiles_loc_dev,
                                     attr="RouteGadget",
                                     name="RouteGadget",
                                     tms=True,
                                     max_native_zoom=zoom_level,
                                     overlay=True,
                                     opacity=0.7)
コード例 #12
0
    message = unicode(message, 'utf-8')
    folium.Marker(coordinate,
                  icon=folium.Icon(color='red', icon='trash'),
                  popup=message).add_to(map_osm)
    print coordinate

for i in range(len(beitou)):
    coordinate2 = [beitou.ix[i, 'lat'], float(beitou.ix[i, 'lon'])]
    message = '%s,%s' % (beitou.ix[i, 'road'], beitou.ix[i, 'road_detail'])
    message = unicode(message, 'utf-8')
    folium.Marker(coordinate2,
                  icon=folium.Icon(color='blue', icon='home'),
                  popup=message).add_to(map_osm)
    print coordinate2

map_osm.save('map\\demo86.html')

dorm1 = [25.023406, 121.505235]
dorm2 = [25.021649, 121.499677]
folium.CircleMarker(dorm1,
                    radius=200,
                    popup='small dorm',
                    fill_color='#C0FFEE').add_to(map_osm)  #圓圈大小會隨著比例一直縮放
folium.Circle(
    dorm2,
    radius=200,
    popup='dorm',  #圓圈大小固定
    fill_color='#FFEEC0').add_to(map_osm)

map_osm.save('map\\demo86.html')
コード例 #13
0
ファイル: visualization.py プロジェクト: jnetosoares/PyMove
def plot_stops(
    move_data,
    radius=0,
    weight=3,
    id_=None,
    legend=True,
    n_rows=None,
    lat_origin=None,
    lon_origin=None,
    zoom_start=12,
    base_map=None,
    tile=TILES[0],
    save_as_html=False,
    color='black',
    filename='plot_stops.html',
):
    """
    Generate points on map that represents stops points with folium.

    Parameters
    ----------
    move_data : pymove.core.MoveDataFrameAbstract subclass.
        Input trajectory data.
    radius :  Double, optional(900 by default)
        The radius value is used to determine if a segment is a stop.
        If the value of the point in target_label is greater than
        radius, the segment is a stop, otherwise it'srs a move.
    weight: int or None
        Stroke width in pixels
    id_: int or None
        If int, plots trajectory of the user, else plot for all users
    legend: boolean, default True
        Whether to add a legend to the map
    n_rows : int, optional, default None.
        Represents number of data rows that are will plot.
    lat_origin : float, optional, default None.
        Represents the latitude which will be the center of the map.
        If not entered, the first data from the dataset is used.
    lon_origin : float, optional, default None.
        Represents the longitude which will be the center of the map.
        If not entered, the first data from the dataset is used.
    zoom_start : int, optional, default 12.
        Initial zoom level for the map
    base_map : folium.folium.Map, optional, default None.
        Represents the folium map. If not informed, a new map is generated
        using the function create_base_map(), with the lat_origin,
        lon_origin and zoom_start.
    tile : String, optional, default 'CartoDB positron'.
        Represents the map'srs tiles.
    save_as_html : bool, optional, default False.
        Represents if want save this visualization in a new file .html.
    color : String or List, optional, default 'black'.
        Represents line'srs color of visualization.
        Pass a list if plotting for many users. Else colors will be random
    filename : String, optional, default 'plot_stops.html'.
        Represents the file name of new file .html.

    Returns
    -------
    folium.folium.Map.
        Represents a folium map with visualization.

    Raises
    ------
    KeyError
        If no STOPs found
    IndexError
        If there is no user with the id passed

    """

    if base_map is None:
        base_map = create_base_map(
            move_data,
            lat_origin,
            lon_origin,
            tile=tile,
            default_zoom_start=zoom_start,
        )

    if SITUATION not in move_data:
        move_data.generate_move_and_stop_by_radius(radius=radius)

    mv_df = _filter_generated_feature(move_data, SITUATION, STOP)
    mv_df, items = _filter_and_generate_colors(mv_df, id_, n_rows, color)

    for _id, color in items:
        for stop in mv_df[mv_df[TRAJ_ID] == _id].iterrows():
            base_map.add_child(
                folium.Circle(
                    (stop[1][LATITUDE], stop[1][LONGITUDE]),
                    color=color,
                    weight=weight,
                    radius=40,
                    opacity=0.5,
                    popup=stop[1][DATETIME],
                    fill_color=color,
                    fill_opacity=0.5,
                ))

    if legend:
        add_map_legend(base_map, 'Color by user ID', items)

    if save_as_html:
        base_map.save(outfile=filename)
    else:
        return base_map
コード例 #14
0
ファイル: demo86.py プロジェクト: dsissac-liu/bdpy0618
import pandas as pd

sample_data = pd.read_csv('data\\data5_utf8.csv', sep=',')
print sample_data.columns, sample_data.shape
sample_data.columns = ['section', 'road', 'road_detail', 'lon', 'lat', 'extra']
print sample_data.head()

location1 = [25.052833, 121.544158]
zoom = 16
map_osm = folium.Map(location=location1, zoom_start=zoom)

for i in range(len(sample_data)):
    coordinate = [float(sample_data.ix[i, 'lat']), float(sample_data.ix[i, 'lon'])]
    message = '%s,%s' % (sample_data.ix[i, 'road'], sample_data.ix[i, 'road_detail'])
    message = unicode(message, 'utf-8')
    folium.Marker(coordinate,
                  icon=folium.Icon(color='blue', icon='info-sign'),
                  popup=message).add_to(map_osm)
    print coordinate

dorm1 = [25.051899, 121.552183]
dorm2 = [25.042374, 121.558899]
dorm3 = [25.051225, 121.564166]
folium.CircleMarker(dorm1, radius=200, popup='small dorm',
                    fill_color='#C0FFEE').add_to(map_osm)
folium.Circle(dorm2, radius=200, popup='dorm',
              fill_color='#FFEEC0').add_to(map_osm)
folium.Circle(dorm3, radius=20, popup='small dorm3',
                    fill_color='#C0FFFF').add_to(map_osm)

map_osm.save('map\\demo86.html')
コード例 #15
0
def get_map(log_user, brand, vt_flag, pc_flag, ml_flag, bl_flag, bl_min, bl_max):
    server = "10.110.3.56"
    user = "******"
    password = "******"
    database = "city_test"
    conn = pms.connect(server, user, password, database)

    log_user = '******'

    strSQL = "SELECT * FROM [legend].[compass].[d_user_init_city] where row_num=1 and user_name='" + log_user + "'"
    df_init_city = pd.read_sql(strSQL, conn)

    latitude = df_init_city.loc[0, 'latitude']
    longitude = df_init_city.loc[0, 'longitude']

    region_company_id = str(df_init_city.loc[0, 'region_company_id'])

    # 地图上悬浮显示经纬度
    san_map = folium.Map(
        location=[latitude, longitude],
        zoom_start=12,
        tiles='http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
        attr='&copy; <a href="http://ditu.amap.com/styles/macaron/">高德地图</a>'
    )

    # vechile track data
    if vt_flag > -1:
        if vt_flag == 2:
            strSQL = "select * from [legend].[compass].[d_vechile_location_city] where region_company_id = " + region_company_id
        else:
            strSQL = "select * from [legend].[compass].[d_vechile_location_city_weekday] where region_company_id = " + region_company_id + " and [weekday]=" + str(
                vt_flag)
        df_gps_range = pd.read_sql(strSQL, conn)

        max_color = max(df_gps_range['location_times'])

        all_boxes = []

        i = 0

        for i in range(len(df_gps_range)):
            upper_left = [df_gps_range.loc[i, 'longitude'] - 0.0075, df_gps_range.loc[i, 'latitude'] + 0.0075]
            upper_right = [df_gps_range.loc[i, 'longitude'] + 0.0075, df_gps_range.loc[i, 'latitude'] + 0.0075]
            lower_right = [df_gps_range.loc[i, 'longitude'] + 0.0075, df_gps_range.loc[i, 'latitude'] - 0.0075]
            lower_left = [df_gps_range.loc[i, 'longitude'] - 0.0075, df_gps_range.loc[i, 'latitude'] - 0.0075]

            # Define json coordinates for polygon
            coordinates = [
                upper_left,
                upper_right,
                lower_right,
                lower_left,
                upper_left
            ]

            geo_json = {"type": "FeatureCollection",
                        "properties": {
                            "lower_left": lower_left,
                            "upper_right": upper_right
                        },
                        "features": []}

            grid_feature = {
                "type": "Feature",
                "geometry": {
                    "type": "Polygon",
                    "coordinates": [coordinates],
                }
            }

            geo_json["features"].append(grid_feature)

            all_boxes.append(geo_json)

            grid = all_boxes

        j = 0

        for j, geo_json in enumerate(grid):
            color = plt.cm.Blues(1 / math.log((max_color + 1) / df_gps_range.loc[j, 'location_times']))
            color = mpl.colors.to_hex(color)

            gj = folium.GeoJson(geo_json,
                                style_function=lambda feature, color=color: {
                                    'fillColor': color,
                                    'color': "white",
                                    'weight': 1,
                                    'line': '5',
                                    'fillOpacity': 0.4,
                                })
            popup = folium.Popup("location heat {}".format(df_gps_range.loc[j, 'location_times']))
            gj.add_child(popup)

            san_map.add_child(gj)

    # block data
    if bl_flag == 1:
        strSQL = "select * from [legend].[compass].[d_block_by_region] where region_company_id = " + region_company_id
        strSQL = strSQL + " and [avg_unit_price] between " + str(bl_min) + " and " + str(bl_max)
        df_gps_range = pd.read_sql(strSQL, conn)

        max_color = max(df_gps_range['avg_unit_price'])

        all_boxes = []

        i = 0

        for i in range(len(df_gps_range)):
            upper_left = [df_gps_range.loc[i, 'longitude'] - 0.0005, df_gps_range.loc[i, 'latitude'] + 0.0005]
            upper_right = [df_gps_range.loc[i, 'longitude'] + 0.0005, df_gps_range.loc[i, 'latitude'] + 0.0005]
            lower_right = [df_gps_range.loc[i, 'longitude'] + 0.0005, df_gps_range.loc[i, 'latitude'] - 0.0005]
            lower_left = [df_gps_range.loc[i, 'longitude'] - 0.0005, df_gps_range.loc[i, 'latitude'] - 0.0005]

            # Define json coordinates for polygon
            coordinates = [
                upper_left,
                upper_right,
                lower_right,
                lower_left,
                upper_left
            ]

            geo_json = {"type": "FeatureCollection",
                        "properties": {
                            "lower_left": lower_left,
                            "upper_right": upper_right
                        },
                        "features": []}

            grid_feature = {
                "type": "Feature",
                "geometry": {
                    "type": "Polygon",
                    "coordinates": [coordinates],
                }
            }

            geo_json["features"].append(grid_feature)

            all_boxes.append(geo_json)

            grid = all_boxes

        j = 0

        for j, geo_json in enumerate(grid):
            color = plt.cm.Greys(1 / math.log((max_color + 1) / df_gps_range.loc[j, 'avg_unit_price']))
            color = mpl.colors.to_hex(color)

            gj = folium.GeoJson(geo_json,
                                style_function=lambda feature, color=color: {
                                    'fillColor': color,
                                    'color': "grey",
                                    'weight': 1,
                                    'line': '2',
                                    'fillOpacity': 0.4,
                                })
            popup = folium.Popup(
                "{}".format(str(df_gps_range.loc[j, 'name']) + " " + str(df_gps_range.loc[j, 'avg_unit_price'])))
            gj.add_child(popup)

            san_map.add_child(gj)

            # power charger data
    if pc_flag == 1:
        strSQL = "SELECT * FROM [legend].[compass].[d_power_cluster] where region_company_id = " + region_company_id
        df_pc = pd.read_sql(strSQL, conn)

        max_fp = df_pc['num'].max()
        color = plt.cm.Greens(0.2)
        color = mpl.colors.to_hex(color)

        df_pc_g = df_pc[df_pc['cluster'] > -1]
        df_pc_i = df_pc[df_pc['cluster'] == -1]

        for lat, lng, label in zip(df_pc_i.latitude, df_pc_i.longitude, str(df_pc_i.num)):
            folium.Circle(
                radius=2,
                location=[lat, lng],
                popup="power charger {}".format(label),
                color=color,
                fill=True,
                fill_color=color,
            ).add_to(san_map)

        for lat, lng, num, rad in zip(df_pc_g.latitude, df_pc_g.longitude, df_pc_g.num, df_pc_g.radius):
            color = plt.cm.Greens(num / max_fp)
            color = mpl.colors.to_hex(color)
            folium.Circle(
                radius=rad,
                location=[lat, lng],
                popup="power charger {}".format(num),
                color=color,
                fill=True,
                fill_color=color,
            ).add_to(san_map)
    # mall data
    if ml_flag == 1:
        strSQL = "SELECT * FROM [legend].[compass].[d_mall_cluster_region] where region_company_id = " + region_company_id
        df_pc = pd.read_sql(strSQL, conn)

        max_fp = df_pc['num'].max()
        color = plt.cm.Reds(0.4)
        color = mpl.colors.to_hex(color)

        df_pc_g = df_pc[df_pc['cluster'] > -1]
        df_pc_i = df_pc[df_pc['cluster'] == -1]

        for lat, lng, label in zip(df_pc_i.latitude, df_pc_i.longitude, str(df_pc_i.num)):
            folium.Circle(
                radius=2,
                location=[lat, lng],
                popup="mall {}".format(label),
                color=color,
                fill=True,
                fill_color=color,
            ).add_to(san_map)

        for lat, lng, num, rad in zip(df_pc_g.latitude, df_pc_g.longitude, df_pc_g.num, df_pc_g.radius):
            color = plt.cm.Reds(num / max_fp)
            color = mpl.colors.to_hex(color)
            folium.Circle(
                radius=rad,
                location=[lat, lng],
                popup="mall {}".format(num),
                color=color,
                fill=True,
                fill_color=color,
            ).add_to(san_map)

    strSQL = "SELECT * FROM [legend].[compass].[d_china_ssss_list_qc] where addr_type in ('门牌号','兴趣点') and brand in ('" + "','".join(
        brand) + "')"
    df_ssss = pd.read_sql(strSQL, conn)

    strSQL = "select * from [legend].[compass].[d_brand_category] where [brand_name] in ('" + "','".join(
        brand) + "') order by [brand_id]"
    df_icon = pd.read_sql(strSQL, conn)

    incidents = folium.map.FeatureGroup()

    # instantiate a mark cluster object for the incidents in the dataframe
    incidents = plugins.MarkerCluster().add_to(san_map)

    # loop through the dataframe and add each data point to the mark cluster
    for bnd in (brand):
        df_brand = df_ssss[df_ssss['brand'] == bnd]
        ico = df_icon[df_icon['brand_name'] == bnd].iloc[0, 0]

        for lat, lng, label, addr in zip(df_brand.latitude, df_brand.longitude, df_brand.store, df_brand.address):
            folium.Marker(
                location=[lat, lng],
                # icon=folium.features.CustomIcon(ico, icon_size=(25,25)),
                icon=folium.features.CustomIcon(
                    'https://image.bitautoimg.com/bt/car/default/images/logo/masterbrand/png/100/m_8_100.png',
                    icon_size=(20, 20)),
                popup=label + "\n\r |" + addr,
            ).add_to(incidents)

    h_file = "_".join(df_icon['brand_id_str'].tolist())
    h_file = df_init_city.loc[0, 'city_name'] + "_" + h_file + ".html"
    h_file = "test.html"
    san_map.save(h_file)
    wb.open(h_file)
コード例 #16
0
def circle_maker(x):
    folium.Circle(location=[x[0], x[1]],
                  radius=float(x[2]),
                  color="red",
                  popup='confirmed cases:{}'.format(x[2])).add_to(m)
コード例 #17
0
ファイル: nlp.py プロジェクト: hhimansh/GlobalTerrorism
City_State = pd.merge(data_city,
                      df1_filter,
                      how='left',
                      left_on='city',
                      right_on='city')
City_State = City_State.drop_duplicates(subset='city',
                                        keep='first',
                                        inplace=False)
count = City_State['value'].values
m = folium.Map(location=[28, 81], tiles="Mapbox Bright", zoom_start=4.5)
for i in range(0, 10):
    folium.Circle(
        location=[
            City_State.iloc[i]['latitude'], City_State.iloc[i]['longitude']
        ],
        #location=[20, 81],
        popup=City_State.iloc[i]['city'],
        radius=int(count[i]) * 300,
        color='crimson',
        fill=True,
        fill_color='crimson').add_to(m)
m

df1_filter = df1[df1['targtype1_txt'] == "Private Citizens & Property"]
df1_filter = df1[df1['country_txt'] == "United States"]
df1_filter = df1_filter[['city', 'latitude', 'longitude']]
df1_filter = df1_filter[df1_filter['city'] != 'Unknown']
data = df1_filter[['city', 'latitude', 'longitude']]
df1_filter = df1_filter.drop_duplicates(subset=None,
                                        keep='first',
                                        inplace=False)
data_city = pd.DataFrame({
コード例 #18
0
path_csv = "/home/maresoc870/Documents/Stopien_II/Semestr_2/AS/Code2/CRIMES/preprocess/processed_csvs/arrest_location2018.csv"
crimes_df = pd.read_csv(path_csv, nrows=10000)

path_csv = "/home/maresoc870/Documents/Stopien_II/Semestr_2/AS/Code2/CRIMES/preprocess/processed_csvs/Police_Stations_processed.csv"
police_df = pd.read_csv(path_csv)
#police_df.loc[police_df['DISTRICT'] == 'Headquarters','DISTRICT'] = '0' # Headquaters -> 0
#police_df['DISTRICT'] = police_df['DISTRICT'].astype(np.uint8) # 'DISTRICT' type -> uint8

map = folium.Map(location=(41.881832, -87.623177), zoom_start=12)

for i in range(len(crimes_df)):

    folium.Circle(radius=30,
                  location=(crimes_df.loc[i, 'Latitude'],
                            crimes_df.loc[i, 'Longitude']),
                  color='crimson',
                  fill=True).add_to(map)

for i in range(len(police_df)):

    folium.Circle(radius=400,
                  location=(police_df.loc[i, 'LATITUDE'],
                            police_df.loc[i, 'LONGITUDE']),
                  color='blue',
                  fill=True).add_to(map)

map.render()
map.save(
    "/home/maresoc870/Documents/Stopien_II/Semestr_2/AS/Code2/CRIMES/maps/map1.html"
)
コード例 #19
0
from folium.plugins import HeatMap

path_csv = "/home/maresoc870/Documents/Stopien_II/Semestr_2/AS/Code2/CRIMES/preprocess/processed_csvs/arrest_location2018.csv"
crimes_df = pd.read_csv(path_csv)

path_csv = "/home/maresoc870/Documents/Stopien_II/Semestr_2/AS/Code2/CRIMES/preprocess/processed_csvs/Police_Stations_processed.csv"
police_df = pd.read_csv(path_csv)

map = folium.Map(location=(41.881832, -87.623177), zoom_start=12)

crimes_df['count'] = 1
HeatMap(data=crimes_df[['Latitude', 'Longitude', 'Arrest'
                        ]].groupby(['Latitude', 'Longitude'
                                    ]).sum().reset_index().values.tolist(),
        radius=10).add_to(map)

for i in range(len(police_df)):
    folium.Circle(radius=400,
                  location=(police_df.loc[i, 'LATITUDE'],
                            police_df.loc[i, 'LONGITUDE']),
                  color='blue',
                  fill=True).add_to(map)

map.render()
map.save(
    "/home/maresoc870/Documents/Stopien_II/Semestr_2/AS/Code2/CRIMES/maps/map1.html"
)
webbrowser.open(
    "/home/maresoc870/Documents/Stopien_II/Semestr_2/AS/Code2/CRIMES/maps/map1.html"
)
コード例 #20
0
y_pred = pd.concat(
    [x_ids.reset_index(drop=True),
     y_pred.reset_index(drop=True)], axis=1)

dt = pd.read_csv("data/dt_us_pnt.csv", dtype={"ID": "int"})
dt = dt.loc[dt["ID"].isin(y_pred["id"])]
dt = dt.set_index("ID").join(y_pred.set_index("id"))
dt["cluster_id"] = [str(x) for x in dt["cluster_id"]]

# seaborn ----
sns.scatterplot(data=dt, x="lon", y="lat", hue="cluster_id")
plt.show()

# folium ----
# https://geopandas.org/gallery/plotting_with_folium.html

m = folium.Map(tiles="cartodbpositron")

for i in range(dt.shape[0]):
    # i = 0
    coordinates = (dt.reset_index(drop=True)["lat"].loc[[i]].to_list() +
                   dt.reset_index(drop=True)["lon"].loc[[i]].to_list())
    cluster_color = color_map(
        int(list(dt.reset_index().loc[[i]]["cluster_id"])[0]))
    m.add_child(folium.Circle(location=coordinates, color=cluster_color))

folium.LayerControl().add_to(m)
m.fit_bounds(m.get_bounds())
m.save(outfile="test.html")
m
コード例 #21
0
            lon=line.g_lon

        f = branca.element.Figure()
        m1=folium.Map([float(lat), float(lon)], zoom_start=10) #eventualmente aggiungere il livello di zoom in base al raggio può essere fyco

        iframe = branca.element.IFrame(
            html=html.format(ddrop['ID_event'].at[line.Index], ddrop['venue_name'].at[line.Index]), 
            width=400, height=240)
        popup1 = folium.Popup(iframe, show=True)


        m1.add_child(folium.Circle(
          location=[float(lat), float(lon)],
          popup=popup1,
          radius=int(ddrop.iloc[line.Index]['maxdist'])*1000,
          #radius=1,
          color='crimson',
          fill=False,
          #fill_color='crimson',

        ))
        #print (lat,"   ", lon)
        #trying to add some text
        #m1.add_child(folium.Marker(
            #location=[45.5,8.5],#[lat, lon],
            #icon=DivIcon(icon_size=(150,36), icon_anchor=(0,0),html='<div style="font-size: 24pt">Bacino d\'utenza</div>')
            #))

        #macro1 = MacroElement()
        #macro1._template = Template(template)
        #m1.get_root().add_child(macro1)
コード例 #22
0
              popup='<strong>LimeHouse</strong>',
              tooltip=tooltip_1).add_to(m),
folium.Marker([51.507538, -0.012823],
              popup='<strong>Blackwall DLR</strong>',
              tooltip=tooltip_1).add_to(m),
folium.Marker([51.515800, -0.014330],
              popup='<strong>Langdon Park</strong>',
              tooltip=tooltip_1).add_to(m),
folium.Marker(
    [51.507538, -0.012823],  #Requires correction
    popup='<strong>Poplar DLR</strong>',
    icon=folium.Icon(color='green', icon='bus'),
    tooltip=tooltip_1).add_to(m),

#Area under study
folium.Circle(location=[51.525211, -0.033503], radius=2500,
              popup=' FRI ').add_to(m)

# Generate map
m.save('map.html')

#Adding Legend

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>
コード例 #23
0
    data = (json.load(f))["features"]

with open("D:\\大學課程\\大二上\\社會科學程式設計\\Youbike專題\\json\\MRT.json", "r") as f:
    data1 = (json.load(f))["features"]

myMap = folium.Map(location=[25.03, 121.55],
                   zoom_start=12,
                   prefer_canvas=True,
                   tiles=mapbox,
                   attr="Mapbox attribution")

fg1 = folium.FeatureGroup(name="YouBike")
for i in range(len(data)):
    place = data[i]["geometry"]["coordinates"]
    place = [place[1], place[0]]
    fg1.add_child(folium.Circle(location=place, radius=2, weight=4))

fg2 = folium.FeatureGroup(name="MRT")
for i in range(len(data1)):
    place = data1[i]["geometry"]["coordinates"]
    place = [place[1], place[0]]
    line, name = data1[i]["properties"]["Line"], data1[i]["properties"]["Name"]

    if line == "BR":  # 文湖
        fg2.add_child(
            folium.Marker(location=place,
                          popup=folium.Popup(name),
                          icon=folium.Icon(color="gray",
                                           icon="subway",
                                           prefix="fa")))
    elif line == "G":  # 松山
コード例 #24
0
#hide colormap bar
for key in choropleth._children:
    if key.startswith('color_map'):
        del (choropleth._children[key])

choropleth.add_to(m)

#adding labels and circle markers
for index, row in regions.iterrows():
    location = list((row['lat'], row['lon']))
    popup = folium.Popup(f"<b>{row['nome']}</b> <br>{str(row['percentage'])}%",
                         show=True)
    folium.Circle(location=location,
                  radius=row['percentage'] * 9000,
                  weight=10,
                  color="#f26233",
                  fill=False,
                  popup=popup).add_to(m)

#creating the abroad marker
location_outside = list((-10.7437, -30.0758))
popup = folium.Popup("<b>Outros países</b> <br>9.5%", show=True)
folium.Circle(location=location_outside,
              radius=9.5 * 9000,
              weight=10,
              color="#f26233",
              fill=False,
              popup=popup).add_to(m)

folium.LayerControl().add_to(m)
コード例 #25
0
map_cctv = folium.Map(location=[35.22323, 128.60946], zoom_start=11, tiles='OpenStreetMap')

rfile = open("changwon.json", 'r', encoding='cp949').read()
jsonData = json.loads(rfile)
folium.GeoJson(jsonData, name='읍면동 구분').add_to(map_cctv)

# 4-3-5. 마우스 포지션(위도, 경도) 찾기 기능
# from folium.plugins import MousePosition
# MousePosition().add_to(map_cctv)

# 4-3-6. 측정도구 기능
# from folium.plugins import MeasureControl
# map_pplace.add_child(MeasureControl())
len(data[data['카메라대수'] == 4])

fg = folium.FeatureGroup(name="cctv 전체")  # 전체그룹 설정
g1 = plugins.FeatureGroupSubGroup(fg, '교통용 cctv')  # 서브그룹 틀 만들기
g2 = plugins.FeatureGroupSubGroup(fg, '비교통용 cctv')
map_cctv.add_child(fg)  # 서브 그룹 맵에 넣기
map_cctv.add_child(g1)
map_cctv.add_child(g2)
for i in range(0, len(data_traffic)):
    folium.Circle([data_traffic["위도"][i], data_traffic["경도"][i]], radius=50, color="#ffc039", fill=True).add_to(g1)
for j in range(0, len(data_non_traffic)):
    folium.Circle([data_non_traffic["위도"][j], data_non_traffic["경도"][j]], radius=50, color="#376091", fill=True).add_to(g2)

folium.LayerControl(collapsed=False).add_to(map_cctv)

map_cctv.save("map_cctv.html")
コード例 #26
0
        if i[2] not in rut_lista:
            lista_nueva.append(i)
            todos.append(i)
            rut_lista.append(i[2])
    for i in noEncontrados:
        if i not in no_encontrados:
            no_encontrados.append(i)
        if i not in todosNoEncontrados:
            todosNoEncontrados.append(i)
    multihogar = []
    contador = 0
    lapromedio = 0
    lopromedio = 0
    circulo = folium.Circle(
        radius=1000,
        location=[lapromedio, lopromedio],
        color='crimson',
        fill=False,
    )
    from Folium import plugins
    #plugins.Search(states, search_zoom=6, geom_type='Polygon').add_to(m)
    x = crearJson(lista_nueva)
    plugins.Search(x, search_zoom=20).add_to(archivos[mapa])
    for i in lista_nueva:
        if contador == 0:
            registro = folium.Map(location=[-34.9926116, -71.2527959],
                                  zoom_start=16)
            m = folium.Map(location=[-34.9926116, -71.2527959], zoom_start=13)

        contador = contador + 1
        latitud = i[0]
        longitud = i[1]
コード例 #27
0
ファイル: views.py プロジェクト: SoloshenkoVeronika/Master
def m_wstime(request):
    print("_________________Worst time____________________")
    error = ''
    installations = Installation.objects.order_by('id')
    if request.method == 'POST':
        flag_grid = 0
        type_errv = 0
        ins_fix_list = 0
        flag_model4 = 0
        grid = request.POST.get("grid", "")
        display_type = request.POST.get("display_type", None)
        ins_fix_flag = request.POST.get("ins_fix", None)

        if ins_fix_flag in ["F"]:
            ins_fix_list = request.POST.get("inst_list", "")
        if display_type in ["DB"]:
            type_errv = 1
        elif display_type == "GR":
            type_errv = 2
            if grid == '':
                flag_grid = 1

        if (type_errv == 2 and flag_grid == 1):
            error = 'Number is not valide'
            context = {
                'installations': installations,
                'error': error,
                'title': "Minimizing average time"
            }
        else:
            model1(grid, type_errv, ins_fix_list)
            model3(ins_fix_list, flag_model4)
            # errvs= ERRV.objects.filter(type_solution=203)
            installations = Installation.objects.order_by('id')
            m = folium.Map([62.354457, 2.377184], zoom_start=6)

            #Load Data
            data = pd.read_csv('main\\recources\\Data_Map.txt')
            lat = data['LAT']
            lon = data['LON']
            elevation = data['ELEV']
            name = data['NAME']

            #Function to change colors
            def color_change(elev):
                if (elev == 1):
                    return ('blue')
                elif (elev == 2):
                    return ('yellow')
                elif (elev == 3):
                    return ('red')
                elif (elev == 100):
                    return ('purple')

            #Function to change colors
            def radius_change(elev):
                if (elev == 3):
                    return 62050
                elif (elev == 5):
                    return 124100
                elif (elev == 6):
                    return 155125

                    #Function to change colors
            def radius_size(elev):
                if (elev == 1 or elev == 100):
                    return 2
                elif (elev == 2):
                    return 1
                elif (elev == 3):
                    return 3

            data2 = pd.read_csv("main\\recources\\Data_Map_ERRV.txt")
            lat2 = data2['LAT']
            lon2 = data2['LON']
            elevation2 = data2['ELEV']

            for lat2, lon2, elevation2 in zip(lat2, lon2, elevation2):
                folium.Circle(location=[lat2, lon2],
                              radius=radius_change(elevation2),
                              popup=str(elevation2) + " m",
                              fill_color='red',
                              fill_opacity=0.05).add_to(m)

            #Plot Markers
            for lat, lon, elevation, name in zip(lat, lon, elevation, name):
                folium.CircleMarker(location=[lat, lon],
                                    radius=radius_size(elevation),
                                    popup=str(name),
                                    fill_color=color_change(elevation),
                                    color=color_change(elevation),
                                    fill_opacity=0.9).add_to(m)

            m = m._repr_html_()  #updated

            context = {
                'installations': installations,
                # 'errvs':errvs,
                'my_map': m,
                'error': error,
                'title': "Worst-time minimization"
            }
        return render(request, 'main/wstime.html', context)

    else:
        context = {
            'installations': installations,
            'title': "Worst-time minimization"
        }
        return render(request, 'main/wstime.html', context)
コード例 #28
0
ファイル: application.py プロジェクト: lbaral/myApp
                       zoom_start=1.5,
                       max_zoom=5,
                       min_zoom=1.0)

for i in range(0, len(confirmed_df)):
    folium.Circle(
        location=[confirmed_df.iloc[i]['lat'], confirmed_df.iloc[i]['long']],
        fill=True,
        radius=(int(
            (np.log(confirmed_df.iloc[i, -1] + 1.00001))) + 0.2) * 50000,
        color='red',
        fill_color='indigo',
        tooltip=
        "<div style='margin: 0; background-color: black; color: white;'>" +
        "<h4 style='text-align:center;font-weight: bold'>" +
        confirmed_df.iloc[i]['country'] + "</h4>"
        "<hr style='margin:10px;color: white;'>" +
        "<ul style='color: white;;list-style-type:circle;align-item:left;padding-left:20px;padding-right:20px'>"
        + "<li>Confirmed: " + str(confirmed_df.iloc[i, -1]) + "</li>" +
        "<li>Deaths:   " + str(death_df.iloc[i, -1]) + "</li>" +
        "<li>Death Rate: " + str(
            np.round(
                death_df.iloc[i, -1] /
                (confirmed_df.iloc[i, -1] + 1.00001) * 100, 2)) + "</li>" +
        "</ul></div>",
    ).add_to(world_map)

world_map

location_map = world_map
location_map.save('abc.html')
コード例 #29
0
        np.random.uniform(low=80.607387, high=80.620474, size=N)
    ]
)
popups = [str(i) for i in range(N)]  # Popups texts are simple numbers.

# m = folium.Map([45, 3], zoom_start=4)
plugins.MarkerCluster(data, popups=popups, options={
                      "disableClusteringAtZoom": 14, "maxClusterRadius": 100, "zoomToBoundsOnClick": True, "spiderfyOnMaxZoom": False}).add_to(OFDs)

datalist = data.tolist()
for row in datalist:
    # use Circle instead of CircleMarker for radius in meters:
    folium.Circle(
        radius=75,
        location=row,
        popup='This is the sensing radius',
        color='#3186cc',
        fill=True,
        fill_color='#3186cc'
    ).add_to(Radii)


# test markers for vega/altair visualization:
folium.Marker(
    location=[6.942236, 80.615474],
    icon=folium.Icon(color='blue', icon='bar-chart',
                     prefix='fa'),
    popup=folium.Popup(max_width=500).add_child(
        folium.Vega(vis1, width=500, height=250))
).add_to(dat_grphs)

folium.Marker(
コード例 #30
0
ファイル: job2.2.py プロジェクト: kasiditau/transcode
    list_marks.append(km_st)
    POLYLINE.append(Polyline_doh)
list_marks[0]
list_marks[1]
len(POLYLINE[0])
#################### test the distance between each 100m marks #########################
for i in range(len(list_marks[1]) - 1):
    print(distance_km(list_marks[0][i], list_marks[0][i + 1]))

import folium
m = folium.Map(location=[13.727876, 100.540474], zoom_start=10)

for i in list_marks[1]:
    folium.Circle(
        location=i,
        radius=1,
    ).add_to(m)

Polyline_doh

for i in [Polyline_doh]:
    folium.PolyLine(i, color="green", weight=2.5, opacity=1).add_to(m)

m
m.save('E:\Transcode' + "/try3.html")

################################################################################3
# map the 100 marks with road number

###############################################
############################# DICTIONARY ################################################