2

我有以下代码,它使用这个geojson 文件作为输入。

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')

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

任何人都知道如何实现这一点?

4

3 回答 3

2

您需要遍历文件。下面提到的文件是一个简单的文件,它有纬度、经度和海拔三列。

如果您以这种格式创建一个简单的文本文件,此代码将循环通过一个文件并添加它们。它获取具有 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())
于 2018-10-10T02:41:26.257 回答
0

看看 MarkerCluster 和 FeatureGroup 类。这里的例子

于 2021-07-31T18:59:46.580 回答
0

请加载您自定义的 html 设计 geojson 文件,并在加载后调用它,在 此处输入图像描述

  1. 我正在工作 Django 请安装必要的模块 | 1. Geojson : geojson 示例

  2. CSV地图示例

    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})
    

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

于 2021-07-31T03:14:59.597 回答