Ejemplo n.º 1
0
def star_select() -> 'html':
    the_region = request.form["the_region_selected"]
    print(the_region)  # 检查用户输入
    dfs = disdata4.query("region=='{}'".format(the_region))
    df_summary = dfs.groupby("行业").agg(
        {"数量": "number"}).sort_values(by="数量", ascending=False)
    print(df_summary.head(5))  # 在后台检查描述性统计
    # 显示前100名富豪所在的国籍的地图
    latitude = 39.92
    longitude = 116.46

    from folium import plugins

    # let's start again with a clean copy of the map of San Francisco
    san_map = folium.Map(location=[latitude, longitude], zoom_start=4)

    # 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 lat, lng, label, in zip(d2.y, d2.x, N.中文姓名):
        folium.Marker(
            location=[lat, lng],
            icon=None,
            popup=label,
        ).add_to(incidents)

    # add incidents to map
    san_map.add_child(incidents)
Ejemplo n.º 2
0
def cafeinfo(request):
    
    popup=[]
    data_lat_log=[]
    a_path='C:/JMS/data'
    df=pd.read_csv(os.path.join(a_path,'cafe_info_1.csv'),encoding='utf-8')
    print(df)
    for data in df.values:
        popup.append(data[0])
        data_lat_log.append([data[8],data[9]])
    
    m=folium.Map([35.16370389566739, 129.15879330965538],zoom_start=11)
    plugins.MarkerCluster(data_lat_log, popups=popup).add_to(m)
    #folium.Marker([35.1803305,129.0516257],popups=popup).add_to(m)
    #m.save(os.path.join(TEMPLATE_DIR,'board/kotags/kocafe/cafe_map.html'))
    
    conn=MongoClient('127.0.0.1')
    db=conn.test1
    
    makeup=db.cafe_info_1
    finds=makeup.find({},{'_id':0})
    
    cafetags=db.cafetags
    cafe15=cafetags.find({},{'_id':0})
    
    return render(request,'board/kotags/kocafe/cafeinfo.html',{'finds':finds,'cafe15':cafe15})
Ejemplo n.º 3
0
def plot_point_clusters(points, filename="ODs_clusters.html"):
    lats = points.apply(lambda x: x[0])
    lons = points.apply(lambda x: x[1])

    lon_avg = np.average(lons)
    lat_avg = np.average(lats) + 0.03
    #map_tiles='OpenStreetMap'
    map_tiles = 'Stamen Terrain'
    #map_tiles='cartodbpositron'
    my_map = folium.Map(location=[lat_avg, lon_avg],
                        zoom_start=12,
                        tiles=map_tiles)
    #folium.LayerControl().add_to(my_map)

    # Build list of (lat, lon) values, ex: [('a', 'b'), ('a1', 'b1')]
    locations = list(zip(lats.values, lons.values))

    # Create a folium marker cluster
    custom_options = {
        'maxClusterRadius': 80 * 2,
        'chunkedLoading': 1,
        'spiderfyDistanceMultiplier': 1
    }
    #custom_options = {'maxClusterRadius':int(80*1.5)}
    custom_options = {'maxClusterRadius': int(80 * 1)}
    marker_cluster = plugins.MarkerCluster(locations=locations,
                                           options=custom_options)
    # Add marker cluster to map
    marker_cluster.add_to(my_map)

    my_map.save(filename)

    return my_map, marker_cluster
Ejemplo n.º 4
0
def plot_coordinates(dataframe, save_path=None):
    """
    Dynamic plot of 'lat' and 'lon' coordinates.

    Parameters
    ----------
    dataframe: pd.DataFrame
        Source dataframe with 'lat' and 'lon' columns
    save_path: str or None
        Where the map will be saved
    """
    # Folium's Map object
    m = folium.Map(location=[dataframe.lat.mean(),
                             dataframe.lon.mean()],
                   zoom_start=12)

    # Markers
    marker_cluster = plugins.MarkerCluster().add_to(m)

    # Iterate over df
    for i, obs in dataframe.iterrows():
        folium.Marker(location=[obs['lat'], obs['lon']]).add_to(marker_cluster)

    # Save map
    if save_path is not None:
        m.save(save_path)

    return m
Ejemplo n.º 5
0
def Map_plot(data_, address_):  #地圖詳細資訊
    d = data_.loc[all_data['縣市'] == address_]
    if d.shape[0] > 10000:  #超過一萬筆就隨機抽一萬筆資料
        d = d.sample(n=10000, random_state=1)
    m = folium.Map(d[['LAT', 'LONG']].mean().values.tolist())
    mc = plugins.MarkerCluster().add_to(m)
    for _, row in d.iterrows():
        trade_date = f"民國{str(row['交易年月日'])[:(len(str(row['交易年月日']))-4)].lstrip('0')}年" \
                     f"{str(row['交易年月日'])[-4:-2].lstrip('0')}月" \
                     f"{str(row['交易年月日'])[-2:].lstrip('0')}日"
        pop_info = f"<font size=\"3\"><u>{row['土地區段位置建物區段門牌']}</u></font><br>" \
                    f"<table>" \
                    f"<tr><th>交易日期</th><td>{trade_date}</td>" \
                    f"<tr><th>種類</th><td>{row['交易標的']}</td>" \
                    f"<tr><th>建物型態</th><td>{row['建物型態']}</td>" \
                    f"<tr><th>使用分區</th><td>{row['都市土地使用分區']}</td>" \
                    f"<tr><th>土地面積</th><td>{round(row['土地移轉總面積平方公尺'],2)}</td>" \
                    f"<tr><th>建物面積</th><td>{round(row['建物移轉總面積平方公尺'],2)}</td>" \
                    f"<tr><th>車位面積</th><td>{round(row['車位移轉總面積平方公尺'],2)}</td>" \
                    f"<tr><th>樓層</th><td>{row['總樓層數']}</td>" \
                    f"<tr><th>建物現況格局</th><td><b>房:</b>{row['建物現況格局-房']} <b>廳:</b>{row['建物現況格局-廳']} <b>衛:</b>{row['建物現況格局-衛']} <b>隔間:</b>{row['建物現況格局-隔間']}</td>" \
                    f"<tr><th>管理組織</th><td>{row['有無管理組織']}</td>" \
                    f"<tr><th>屋齡</th><td>{row['屋齡']}</td>" \
                    f"<tr><th>總價格</th><td>{row['總價元']}</td>" \
                    f"<tr><th>每平方公尺單價:</th><td>{int(row['單價元平方公尺'])}</td>" \
                    f"</table>"
        folium.Marker(row[['LAT', 'LONG']],
                      popup=folium.Popup(utf2asc(pop_info),
                                         max_width=800,
                                         min_width=200)).add_to(mc)
    sw = d[['LAT', 'LONG']].min().values.tolist()
    ne = d[['LAT', 'LONG']].max().values.tolist()
    m.fit_bounds([sw, ne])
    return m.get_root().render()
Ejemplo n.º 6
0
def Cluster_map_generation(Data_to_save, geoJsonData):
    m = folium.Map(
        location=[float(Data_to_save[100, 9]),
                  float(Data_to_save[100, 10])],
        zoom_start=15)

    folium.GeoJson(geoJsonData,
                   style_function=lambda x: {
                       'color': x['properties']['stroke'],
                       'weight': x['properties']['stroke-width'],
                       'opacity': 0.6,
                   }).add_to(m)

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

    # loop through the dataframe and add each data point to the mark cluster
    for i in range(0, len(Data_to_save)):
        folium.Marker(
            location=[float(Data_to_save[i, 9]),
                      float(Data_to_save[i, 10])],
            icon=None,
        ).add_to(incidents)

    # display map
    m.save('Result/Map_Cluster.html')
Ejemplo n.º 7
0
def cctv_map():
    popup=[]
    data_lat_log=[]
    df=pd.read_csv("e:/data/input/map/cctv.csv",encoding="utf-8")
    for data in df.values:
        if data[4]>0:
            popup.append(data[2])
            data_lat_log.append([data[3],data[4]])
    
    m=folium.Map([35.1803305,129.0516257], zoop_start=11)
    plugins.MarkerCluster(data_lat_log,popups=popup).add_to(m)
    m.save(os.path.join(TEMPLATE_DIR,'map/map01.html'))   
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
Ejemplo n.º 8
0
def make_map(features):
    #print('> Making map...')
    m = f.Map()
    a = {}
    z = 0.3 * len(d)
    y = int(z)
    for i in range(0, y):
        z1 = d.iloc[i]['latitude']
        z2 = d.iloc[i]['longitude']
        try:
            loc.append((float(z1), float(z2)))
            #a={i:{d.iloc[i]['tweetCreated']:{loc}}}
        except:
            pass

    plugins.MarkerCluster(loc).add_to(m)

    TimestampedGeoJson({
        'type': 'FeatureCollection',
        'features': features
    },
                       period='P1M',
                       add_last_point=True,
                       auto_play=False,
                       loop=False,
                       max_speed=1,
                       loop_button=True,
                       date_options='YYYY/MM',
                       time_slider_drag_update=True).add_to(m)
    #print('> Done.')
    return pollution_map
Ejemplo n.º 9
0
def map_display(data):
    '''create and fill the maps with the filtered dataset infos.'''
    st.markdown('## :earth_americas: **Rental Houses Map**')
    c1, c2 = st.beta_columns((1, 1))

    # 1st map - houses for rent
    lat = 51.1642292
    long = 10.4541194

    map_b = folium.Map(location=[lat, long], zoom_start=5.5)

    prices = plugins.MarkerCluster().add_to(map_b)

    for lat, lng, i in zip(data['lat'],
                           data['long'],
                           list(range(data.shape[0]))):
        label = f'{data["street"].values[i]} - Price: €{data["montly_rent"].values[i]} - {data["pets"].values[i]}'
        label = folium.Popup(label, parse_html=True)
        folium.Marker(
            location=[lat, lng],
            icon=None,
            popup=label).add_to(prices)

    folium.GeoJson(geo_json_data, style_function=lambda feature: {'color': 'darkred', 'weight': 0.5, }).add_to(map_b)

    folium_static(map_b, width=1200, height=550)

    return None
Ejemplo n.º 10
0
 def createMap(self):
     mc = plugins.MarkerCluster()
     
     for index, location in self.data.iterrows():
         mc.add_child(folium.Marker([location['latitude'], location['longitude']])).add_to(self.map)
         
     self.map.save('test.html')
     return self.map
Ejemplo n.º 11
0
def index():

    requested_city = request.args.get('city')
    if requested_city is None:
        requested_city = DEFAULT_CITY

    stumps = Stump.query.join(City).filter(
        City.name == requested_city).join(Stump_type).all()
    stumps_count = len(stumps)
    city_list = City.query.order_by(City.name).all()

    if stumps_count == 0:
        geolocator = Nominatim(user_agent=USER_AGENT)
        location = geolocator.geocode(requested_city)
        if location is None:
            flash("Unknown city {}!".format(requested_city))
            requested_city = DEFAULT_CITY
            location = geolocator.geocode(requested_city)
            stumps = Stump.query.join(City).filter(
                City.name == requested_city).join(Stump_type).all()
            stumps_count = len(stumps)

        base_latitude = location.latitude
        base_longitude = location.longitude
    else:
        base_latitude = stumps[0].latitude
        base_longitude = stumps[0].longitude

    map = folium.Map(location=[base_latitude, base_longitude],
                     zoom_start=13,
                     tiles='OpenStreetMap',
                     scrollWheelZoom=False)

    marker_cluster = plugins.MarkerCluster().add_to(map)

    for stump in stumps:

        latitude = stump.latitude
        longitude = stump.longitude

        stump_description = "<a href='/stumps/details/{}' target='_PARENT'>{}</a> ".format(
            stump.id, stump.stump_type.name)

        stump_icon = folium.Icon(color=stump.stump_type.color,
                                 icon='envira',
                                 angle=180,
                                 prefix='fa')

        folium.Marker([latitude, longitude],
                      popup=stump_description,
                      icon=stump_icon).add_to(marker_cluster)

    return render_template('index.html',
                           map=map._repr_html_(),
                           city_list=city_list,
                           city=requested_city,
                           stumps_count=stumps_count)
Ejemplo n.º 12
0
def top_rated_by_country_map():
    url = 'data/custom.geo.json'
    world_geo = f'{url}'
    world_map = folium.Map(min_zoom=1,
                           max_zoom=6,
                           zoom_start=2,
                           location=(40, 15))

    conn = sqlite3.connect("data/movies.db")
    df = pd.read_sql_query(
        "Select *, Count(m.country) as count from Country c Join Location l on (c.country_id = l.id) Join Movies m on (c.country_id = m.country) where m.rank>=1 and m.rank<=250 group by m.country",
        conn)
    # df.dropna(axis='rows',inplace=True)
    df['e'] = df.iloc[:, 2:31].sum(axis=1)
    df = df[['country_name', 'iso_2', 'iso_3', 'long', 'lat', 'e', 'count']]
    # df.dropna(axis='columns',inplace=True)
    df = df[df['e'] != 0]
    conn.close()

    choropleth = folium.Choropleth(
        geo_data=world_geo,
        name='Number of Produced Movies',
        data=df,
        columns=['iso_3', 'e'],
        key_on='feature.properties.iso_a3',
        fill_color='YlGn',
        fill_opacity=0.7,
        line_opacity=0.2,
        bins=8,
        legend_name='Number of Produced Movies').add_to(world_map)

    choropleth.geojson.add_child(
        folium.features.GeoJsonTooltip(fields=['sovereignt'], labels=False))

    incidents = plugins.MarkerCluster(
        name='Distribution of 250 Top Rated Movies').add_to(world_map)

    for lat, lng, label, in zip(df.lat, df.long, df['count']):
        for i in range(label):
            folium.Marker(
                location=[lat, lng],
                icon=plugins.BeautifyIcon(icon="leaf",
                                          iconSize=[36, 36],
                                          background_color="#87CEFA",
                                          border_color="#B0E0E6",
                                          borderWidth=5,
                                          inner_icon_style='size : 18px',
                                          number=label),
                popup=label,
            ).add_to(incidents)
        i += 1

    world_map.add_child(incidents)

    folium.LayerControl().add_to(world_map)

    return world_map
Ejemplo n.º 13
0
 def test_marker_cluster(self):
     N = 100
     data = np.array([
         np.random.uniform(low=35, high=60, size=N),  # Random latitudes.
         np.random.uniform(low=-12, high=30, size=N),  # Random longitudes.
         range(N),  # Popups.
     ]).T
     mapa = folium.Map([45., 3.], zoom_start=4)
     mapa.add_children(plugins.MarkerCluster(data))
     mapa._repr_html_()
Ejemplo n.º 14
0
def point_adder(df, info):
    latitude = 41.8781
    longitude = -87.6298
    chi_map1 = folium.Map(location=[latitude, longitude], zoom_start=12, tiles='OpenStreetMap')
    r_la = list(df["LATITUDE"])
    r_lo = list(df["LONGITUDE"])
    labels = list(info)
    incidents = plugins.MarkerCluster().add_to(chi_map1)
    for la, lo, label in zip(r_la, r_lo, labels):
        folium.Marker([la, lo], popup=label, icon=None, tooltip="Show me").add_to(incidents)
    chi_map1.add_child(incidents)
    return folium_static(chi_map1)
Ejemplo n.º 15
0
 def test_marker_cluster(self):
     N = 100
     data = np.array([
         np.random.uniform(low=35, high=60,
                           size=N),  # random latitudes in Europe
         np.random.uniform(low=-12, high=30,
                           size=N),  # random longitudes in Europe
         range(N),  # popups are simple numbers 
     ]).T
     mapa = folium.Map([45., 3.], zoom_start=4)
     mapa.add_plugin(plugins.MarkerCluster(data))
     mapa._build_map()
Ejemplo n.º 16
0
def draw_map_mon(ds):
    """
    Esta función recibe un conjunto de incidentes y los dibuja en un mapa usando el paquete folium,
    el mapa se guarda en un fichero.
    :param ds: dataset de incidentes en formato de DataFrame
    """
    incid_map = folium.Map(location=[37.7617007179518, -122.42158168136999], zoom_start=11, tiles='Stamen Terrain')
    marker_cluster = plugins.MarkerCluster().add_to(incid_map)
    for name, row in ds.iterrows():
        folium.Marker([row["Y"], row["X"]], popup=row["Descript"]).add_to(marker_cluster)
    incid_map.save('incidents.html')
    return incid_map
Ejemplo n.º 17
0
def numper(result):
    icd = plugins.MarkerCluster()
    # result=[[ -0.152680,51.514570]]
    # lix=[]
    # for i in result:
    #     lix.append(i)
    # print(len(lix))
    print(result)
    for lat, lng, lable in result:
        folium.Marker(location=[lat, lng], icon=None,
                      popup=str(lable) + ',').add_to(icd)
    return icd
Ejemplo n.º 18
0
def make_markersmap(map_obj):
    curs.execute("SELECT ip from log_mapper.markers ORDER BY INET_ATON(ip);")# ip ASC;")
    list_ips = curs.fetchall()
    mc = plugins.MarkerCluster()
    for ip_tup in list_ips:
        if ip_tup[0] is None:
            continue
        try:
            make_marker(mc, str(ip_tup[0]))
        except:
            print("[*] Error with IP: {}".format(ip_tup[0]))
    map_obj.add_child(mc)
    return map_obj
Ejemplo n.º 19
0
    def getMap_with_statistic_area(self, input_data):  # 區域統計地圖
        new_map = self.get_clean_map()
        features = plugins.MarkerCluster().add_to(new_map)

        for lat, lng, label, in zip(input_data.lat, input_data.lng,
                                    input_data.address):
            folium.Marker(
                location=[lat, lng],
                icon=None,
                popup=label,
            ).add_to(features)
        new_map.add_child(features)
        return new_map
Ejemplo n.º 20
0
    def cluster_map(self):
        '''
        Creates and saves a map that shows a cluster of stop lat/lng points that have over 50 data points and
        assigns them an icon based on their mode of transportation. The icon is also shaded to represent the 
        on-time departure distribution with red being low and green being high.

        Args:
            None
        '''
        # Cluster of Stops with On-Time Departure %
        on_time = self.data.groupby(['stop_id', 'stop_name', 'stop_lat', 'stop_lng', 'route_type']).departure_status.apply(lambda x: (x == 'on_time').sum()).reset_index(name='on_time_stops')
        total = self.data.groupby(['stop_id', 'stop_name', 'stop_lat', 'stop_lng', 'route_type']).size().reset_index(name='total_stops')

        map_data = pd.merge(on_time, total, on=['stop_id', 'stop_name', 'stop_lat', 'stop_lng', 'route_type'])
        map_data['on_time_percent'] = map_data.on_time_stops / map_data.total_stops
        map_data['on_time_str'] = map_data.on_time_percent.apply(lambda x: f"{x:.1%}")
        map_data['map_icon'] = map_data.route_type.apply(lambda x: x if x=='bus' else 'train')
        map_data = map_data[map_data.total_stops >= 50]

        step = cmp.LinearColormap(
            ['red', 'yellow', 'green']
            ,vmin=round(min(map_data.on_time_percent),2)
            ,vmax=round(max(map_data.on_time_percent),2)
            ,caption='On-Time Departure Percentage'
            )

        stops = map_data[['stop_lat', 'stop_lng']]
        stop_list = stops.values.tolist()
        icon_list = map_data.map_icon.tolist()
        on_time_list = map_data.on_time_percent.tolist()
        name_list = map_data.stop_name.tolist()

        stop_map = folium.Map(location=[39.7426534, -104.9904138]
                             ,tiles='Stamen Terrain')

        marker_cluster = plugins.MarkerCluster().add_to(stop_map)

        for stop in range(0, len(stop_list)):
            folium.Marker(location=stop_list[stop]
                        ,icon=folium.Icon(
                            color='white'
                            ,icon_color=step(on_time_list[stop])
                            ,icon=icon_list[stop]
                            ,prefix='fa')
                            ,popup=f"{name_list[stop]}: {on_time_list[stop]:.1%}"
                        ).add_to(marker_cluster)
        
        if self.route_label == 'All':
            stop_map.save(f"html/{self.route_type}_cluster_map.html")
        else:
            stop_map.save(f"html/{self.route_label}_cluster_map.html")
Ejemplo n.º 21
0
def cctv_map():
    popup=[]
    data_lat_log=[]
    a_path='c:/hj/data/'
    df=pd.read_csv(os.path.join(a_path,'cctv.csv'),encoding='utf-8')
    print(df)
    for data in df.values: #필드빼고 값만 가져온다.
        if data[4]>0:
            popup.append(data[1])
            data_lat_log.append([data[10],data[11]])
            
    m=folium.Map([35.1803305,129.0516257],zoom_start=11)
    plugins.MarkerCluster(data_lat_log, popups=popup).add_to(m)
    m.save(os.path.join(TEMPLATE_DIR, 'map/map01.html'))
Ejemplo n.º 22
0
def cctv_map():
    popup = []
    data_lat_log = []
    a_path = 'E:/pythonProject/data/'
    df = pd.read_csv(os.path.join(a_path, "cctv/CCTV_20190917.csv"),
                     encoding="utf-8")
    for data in df.values:
        if data[4] > 0:
            popup.append(data[1])
            data_lat_log.append([data[10], data[11]])

    m = folium.Map([35.1803305, 129.0516257], zoop_start=11)
    plugins.MarkerCluster(data_lat_log, popups=popup).add_to(m)
    m.save(os.path.join(TEMPLATE_DIR, "map/map01.html"))
def map_hydrant_data(relpath):
    # Load data
    df = pd.read_csv(relpath, sep=';')

    # Custom function Get Type, Latitude, Longitude
    def return_coordinates(x):
        d = json.loads(x)
        lst = [d['type']]+ d['coordinates']
        return pd.Series(lst, index=['type','lon','lat'])

    # Add processed data
    df = pd.concat([df, df['Geom'].apply(return_coordinates)], axis=1)
    df['color'] = df['COLOR'].fillna('NA')

    # Color map for hydrants
    colors= {'Blue':'blue', 
             'Green':'green',        
             'Yellow':'#ffff00',         
             'Red':'red',    
             'NA':'gray',       
             'White':'white'}


    # Use folium to display hydrants on the map
    van_cluster = folium.Map(location=[49.28721476882593,-123.11269938372442],zoom_start=16)

    from folium import plugins
    cluster = plugins.MarkerCluster().add_to(van_cluster)

    for idx, location in enumerate(zip(df.lat, df.lon)): 
        popup_html = '<p>ID: {ID}<br>STATUS: {STATUS}</p>'.format(**dict(df.loc[idx, ['ID','STATUS']]))
        popup_iframe = folium.IFrame(html= popup_html, width=200, height=50)

        if (idx < 50):
            popup = folium.Popup(popup_iframe, parse_html=True, show=True)
        else:
            popup = folium.Popup(popup_iframe, parse_html=True)

        folium.CircleMarker(
                        location,
                        radius=6,
                        color=colors[df['color'][idx] ],
                        fill=True,
                        fill_color=colors[df['color'][idx]],
                        fill_opacity=0.4,
                        popup=popup
                ).add_to(cluster)

    return van_cluster
Ejemplo n.º 24
0
def gethos():

    let = df.iloc[0, 2]
    let2 = df.iloc[0, 3]
    m = folium.Map(location=[let, let2], zoom_start=12)

    N = 100

    data = df[["latitude", "longitude"]].values

    # popups = [str(i) for i in range(N)] # Popups texts are simple numbers.
    m = folium.Map([let, let2], zoom_start=7)
    plugins.MarkerCluster(data).add_to(m)

    return m._repr_html_()
Ejemplo n.º 25
0
def build_map(data,data_1):

    ###Initialize a map centered [avg_lat, avg_lng]
    m = folium.Map([avg_lat, avg_lng], zoom_start=10)
    ### add markers to the map which shows the information of ['Name','famous_for','webpage','address','rating_in_blog','rating_in_yelp','sentiment_score_review','sentiment_score_comment','weather','temperature'].
    folium.GeoJson(data, name='Restaurants', tooltip=folium.features.GeoJsonTooltip(fields=['Name','famous_for','webpage','address','rating_in_blog','rating_in_yelp','sentiment_score_review','sentiment_score_comment','weather','temperature'], localize=True)).add_to(m)
    ### add additional layer which shows the open hour
    folium.GeoJson(data, name='Open Hours', tooltip=folium.features.GeoJsonTooltip(fields=['Name','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'], localize=True)).add_to(m)
    ### add additional layer which shows the concentration of the restaurants based on cluster
    plugins.MarkerCluster(data_1, popups=list(df['name']), name='Concentration').add_to(m)###this uses data_1 as lat and lng are the only information needed to make this layer
    folium.LayerControl(collapsed=False).add_to(m)
    m.save('../Result/map_LA')

    ###Save as an html file
    m.save(outfile='../Result/map_LA.html')
    return m
Ejemplo n.º 26
0
def map_02_details():
    # let's start again with a clean copy of the map of United State
    san_map = folium.Map(location=[latitude, longitude], zoom_start=4)
    # 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 lat, lng, label, in zip(data.latitude, data.longitude, cdata1.Title):
        folium.Marker(
            location=[lat, lng],
            icon=None,
            popup=label,
        ).add_to(incidents)
    # add incidents to map
    incident_map2 = san_map.add_child(incidents)
    display(incident_map2)
    incident_map2.save('templates/map_02_details.html')
    return render_template("map_02_details.html")
def folium_map(map_object,
               data,
               zoom_start=11,
               popup=False,
               icon=False,
               color=False):
    """
    map_object: The variable name of the map object that you have instantiated.
    data: List of lists, or array, of latitude and longitude data
    popup = String information that pops up when clicking on a map marker.
    """
    marker_cluster = fp.MarkerCluster().add_to(map_object)
    folium.Marker(data).add_to(marker_cluster)
    name = str(map_object)
    map_object.save(name + '.html')

    return map_object
Ejemplo n.º 28
0
def createLayer(df, layerName, header_value, header_base, tooltip_func):
    layer = fl.FeatureGroup(name=layerName, overlay=False, control=True)

    df_ratio = df[header_value] / df[header_base]

    maxCases = df_ratio.max()

    # vmax = maxCase*100 lenne ideális esetben, de egy színkód lesz az összes adathoz
    colormap = cm.LinearColormap(
        colors=['yellow', 'green', 'blue', 'purple', 'red'], vmin=0, vmax=100)

    # különböző koordináták
    unique_locs = df[['lats', 'longs']].drop_duplicates()

    marker_cluster = flp.MarkerCluster(name='SzocInt',
                                       overlay=True,
                                       control=False,
                                       icon_create_function=None)

    # koordináták szerint rakjuk ki a markereket, mert az egy helyre esoket
    # így lehet majd láthatóvá tenni (mint a google térképnél)
    for idx, loc in enumerate(zip(unique_locs['lats'], unique_locs['longs'])):
        if loc[0] < 0.001:
            continue

        # az azonos térképi koordinátára eső sorok
        mask = (df['lats'] == loc[0]) & (df['longs'] == loc[1])

        df_part = df[mask]
        df_ratio_part = df_ratio[mask]

        for i in range(df_part.shape[0]):

            row = df_part.iloc[i]
            # 0 férőhelyszámnál/dolgozószámnál szürkével jelöli meg
            color = "#808080ff" if pandas.isnull(df_ratio_part.iloc[i]) \
              else colormap(df_ratio_part.iloc[i]*100)

            fl.Marker(location=[row['lats'], row['longs']],
                      tooltip=tooltip_func(row),
                      icon=fl.Icon(color='black', icon_color=color)).add_to(
                          layer if df_part.shape[0] == 1 else marker_cluster)

    marker_cluster.add_to(layer)

    return layer
Ejemplo n.º 29
0
def test_marker_cluster():
    N = 100
    np.random.seed(seed=26082009)
    data = np.array([
        np.random.uniform(low=35, high=60, size=N),  # Random latitudes.
        np.random.uniform(low=-12, high=30, size=N),  # Random longitudes.
        range(N),  # Popups.
    ]).T
    m = folium.Map([45., 3.], zoom_start=4)
    mc = plugins.MarkerCluster(data)
    m.add_child(mc)
    m._repr_html_()

    out = m._parent.render()

    # We verify that imports
    assert ('<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.'
            'markercluster/1.0.0/leaflet.markercluster.js"></script>') in out
    assert ('<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/'
            'libs/leaflet.markercluster/1.0.0/MarkerCluster.css" />') in out
    assert ('<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/'
            'libs/leaflet.markercluster/1.0.0/MarkerCluster.Default.css" />'
            ) in out

    # Verify the script part is okay.
    tmpl = Template("""
        var {{this.get_name()}} = L.markerClusterGroup();
        {{this._parent.get_name()}}.addLayer({{this.get_name()}});

        {% for marker in this._children.values() %}
            var {{marker.get_name()}} = L.marker(
                [{{marker.location[0]}},{{marker.location[1]}}],
                {
                    icon: new L.Icon.Default()
                    }
                )
                .addTo({{this.get_name()}});
        {% endfor %}
    """)
    assert ''.join(tmpl.render(this=mc).split()) in ''.join(out.split())

    bounds = m.get_bounds()
    assert bounds == [[35.147332572663785, -11.520684337300109],
                      [59.839718052359274, 29.94931046497927]], bounds
def add_clusters(dictionary):
    """
    (dict) -> class 'folium.map.FeatureGroup'

    Returns clusters to add it to the map
    """
    clusters = folium.FeatureGroup(name="Clusters by the area")
    first_loc = []
    second_loc = []
    for key in dictionary:
        points = dictionary[key]
        first_loc.append(points[0])
        second_loc.append(points[1])
    data = np.array(
        [np.array(first_loc),
         np.array(second_loc),
         range(len(dictionary))]).T
    plugins.MarkerCluster(data).add_to(clusters)
    return clusters