向folium中的geojson图层添加弹出窗口

ldioqlga  于 2023-04-08  发布在  其他
关注(0)|答案(3)|浏览(195)

下面的代码使用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')

上面的代码生成了一个带有标记的传单Map。问题是它目前在弹出消息中显示一个静态字符串(即“普通弹出字符串”)。我不知道如何显示geojson属性(例如STATUS属性)的值。
有人知道如何实现这一点吗?

0ejtzxu1

0ejtzxu11#

你需要遍历文件。下面提到的文件是一个简单的文件,有三列纬度,经度和海拔。
如果你创建了一个简单的文本文件,这个代码循环遍历一个文件并添加它们。它获取了包含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())
vwhgwdsa

vwhgwdsa2#

请加载您的定制的HTML设计geojson文件,并调用加载后,像这样一个

1.我正在使用Django,请安装必要的模块|packages 1. Geojsongeojson Example

  1. CSVmap 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})

运行正常。如果有什么需要优化的地方请告诉我...

dfty9e19

dfty9e193#

您可以通过使用GeoJsonPopup函数而无需循环来完成此操作。
对于你的代码,这将是这样的:

import folium
markers_geojson='volcanoes_json.geojson'  
m=folium.Map(location=[0,0],zoom_start=6,tiles='Mapbox bright')
geoj = folium.GeoJson(data=open(markers_geojson), name='Volcano')
folium.features.GeoJsonPopup(fields=['VolcanoHeight'], labels=True).add_to(geoj)
geoj.add_to(m)

相关问题