【问题标题】:Adding a popup to a geojson layer in folium向folium中的geojson图层添加弹出窗口
【发布时间】:2016-11-05 10:00:12
【问题描述】:

我有以下代码使用这个geojson file 作为输入。

import folium
markers_geojson='volcanoes_json.geojson'  
map=folium.Map(location=[0,0],zoom_start=6,tiles='Mapbox bright')
map.add_child(folium.GeoJson(data=open(markers_geojson),name='Volcano').add_child(folium.Popup("A plain pop up string")))    
map.save(outfile='test5.html')

以上代码生成带有标记的传单地图。问题是它当前在弹出消息中显示一个静态字符串(即“一个普通的弹出字符串”)。我不知道如何显示 geojson 属性中的值(例如 STATUS 属性)。

有人知道如何实现吗?

【问题讨论】:

    标签: python json leaflet geojson folium


    【解决方案1】:

    您需要遍历文件。下面提到的文件是一个简单的文件,有lat、long和elevation三列。

    如果您以这种格式创建一个简单的文本文件,此代码会循环遍历一个文件并添加它们。它获取具有 lat、long、elevation 的列,并在弹出窗口中创建一个动态弹出窗口。

    data = pandas.read_csv("Volcanoes.txt")
    lat = list(data["LAT"])
    lon = list(data["LON"])
    elev = list(data["ELEV"])
    
    # make a color code for elevation
    def color_producer(elevation):
        if elevation < 1000:
            return 'green'
        elif 1000 <= elevation < 3000:
            return 'orange'
        else:
            return 'red'
    
    # set the base map
    map = folium.Map(location=[47.0, -122.5], zoom_start=12)
    
    # add an additional tile layer
    map.add_tile_layer("Stamen Toner")
    
    fgv = folium.FeatureGroup(name="Volcanoes")
    
    # loop through and plot everything
    for lt, ln, el in zip(lat, lon, elev):
        fgv.add_child(folium.CircleMarker(location=[lt, ln], radius = 6, popup=str(el)+" m",
        fill_color=color_producer(el), fill=True,  color = 'grey', fill_opacity=0.7))
    
    fgp = folium.FeatureGroup(name="Population")
    
    # add a map of shading by 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'}))
    
    
    
    # add the layers
    map.add_child(fgv)
    map.add_child(fgp)
    map.add_child(folium.LayerControl())
    

    【讨论】:

      【解决方案2】:

      请加载您自定义的 html 设计 geojson 文件并在加载后调用它 enter image description here

      1. 我正在使用 Django,请安装必要的模块 |包 1.Geojson:geojson Example

      2. CSV: map Example

        def new_test_map(request, *args, **kwargs): file_path= os.path.join(settings.BASE_DIR,tatic/map/geojson/aus_states.geojson')

         suburbs_json = json.load(open(file_path, "r"))
         file_path=os.path.join(settings.BASE_DIR,"static/map/state_map.csv")
         suburbs_data = pd.read_csv(file_path)
         suburbs_id_map={}
         for feature in suburbs_json["features"]:
             feature["id"] = feature["properties"]["STATE_CODE"]
             suburbs_id_map[feature["properties"]["STATE_NAME"]] = feature["id"]
         suburbs_data["id"] = suburbs_data['state'].apply(lambda x: suburbs_id_map[x])
         suburbs_data.fillna(0)
        
         def datass(feature):
             k1=suburbs_data.loc[(suburbs_data['id'] == feature)].values.tolist()
             print(k1)
             try:
                 k=int(k1[0][5])
                 # if k <=1:
                 #     risk='No Risk'
                 #     color='#808080'
                 if k<=1:
                     l=k1[0][0]
                     return l
                 if k == 2:
                     risk='Significant Risk'
                     color='#edcf64'
                 elif k == 3:
                     risk='High Risk'
                     color= '#be2a3e'    
                 html=f"""<div class="card col " style="border-radius:6px;border-top: 6px solid {color};"><div class="card-body">
                                 <div style='display:flex;justify-content:space-between'">
                                     <h6 class="card-title mb-4" style="font-size: 14px;">State:{k1[0][0]}</h6>
                                     <h6 class="card-title mb-1" style="font-size: 14px;color: {color}">{risk}<br></h6>
                                 </div>
                             </div>
                             <div class="table-responsive">
                                 <table class="table align-middle table-nowrap mb-0">
                                     <thead>
                                         <tr>
                                             <th scope="col" >MECHANISM</th>
                                             <th scope="col">%</th>
                                             <th scope="col">INCIDENTS</th>
                                         </tr>
                                     </thead>
                                     <tbody>
                                         <tr>
        
                                             <td>{k1[0][6]}</td>
                                             <td>{k1[0][8]}</td>
                                             <td >{k1[0][10]}</td>
        
                                         </tr>
                                         <tr>
        
                                             <td >{k1[0][7]}</td>
                                             <td >{k1[0][9]}</td>
                                             <td >{k1[0][11]}</td>
                                         </tr>
                                     </tbody>
                                 </table>
                             </div>
                             <p class="mb-0" style="font-size: 11px;">
                                     FORECAST ACCURACY +-10%
                             </p>
                             <p class="mb-0" style="font-size: 9px;">
                                     updated on {k1[0][12]}
                             </p>
                         </div>
                     </div>          
                     """
                 #print(feature,html)
                 return html
             except:
                 return k1.Suburb_Name
        
        
         for feature in suburbs_json["features"]:
             feature["properties"]["popups"]=datass(feature['id'])
         def style_function_opcity_suburb(feature):
             k1=suburbs_data[(suburbs_data['id'] == feature['id'])]
             try:
                 k=int(k1.risk)
             except:
                 k=0
             if k >1:
                 return 1
             else:
                 return 0
         def style_function_suburb(feature):
             k1=suburbs_data[(suburbs_data['id'] == feature['id'])]
             try:
                 k=int(k1.risk)
             except:
                 k=0
             if k == 1:
                 return '#ffffff'
             elif k == 2:
                 return '#edcf64'
             elif k == 3:
                 return '#be2a3e'    
             else:
                 return '#ffffff'
        
         m = folium.Map(location=[-23.85077947836127, 134.5773586588719],zoom_start=4)
         folium.GeoJson(
             suburbs_json,
             style_function=lambda feature: {
                 'fillColor': style_function_suburb(feature),
                 'color':'black', 
                 'fillOpacity':style_function_opcity_suburb(feature), 
                 'weight': 0.1,
             },
             highlight_function=lambda feature: {
                 'fillColor': style_function_suburb(feature),
                 'color':'black', 
                 'fillOpacity': style_function_opcity_suburb(feature), 
                 'weight': 2,
             },
             tooltip=folium.features.GeoJsonTooltip(
                 fields=['popups'],
                 labels=False,
                 style=("background-color: white; color: #333333; font-family: arial; 
                 font-size: 12px; padding: 10px;") 
             )
         ).add_to(m)
         folium.TileLayer('cartodbpositron').add_to(m)
         m=m._repr_html_() #updated
         return render(request, 'test_map.html', {'my_map':m})
        

      它工作正常。让我知道是否需要优化...

      【讨论】:

        【解决方案3】:

        看看 MarkerCluster 和 FeatureGroup 类。 example here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-07-05
          • 1970-01-01
          • 2020-04-26
          • 1970-01-01
          • 2022-11-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多