Reputation: 8072
I have the following code which uses this geojson file as input.
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')
The above code produces a leaflet map with markers. The problem is it currently displays a static string (i.e. "A plain pop up string") in the popup message. I don't know how to show a value from the geojson properties (e.g.the STATUS property).
Anyone have any idea of how to implement this?
Upvotes: 4
Views: 11646
Reputation: 3454
You can do this without a loop by making use of the GeoJsonPopup
function.
With your code this would be something like:
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)
Upvotes: 1
Reputation: 11
Kindly load your customized html design geojson file and call that after loading like this one
I am working Django please install necessary module | packages 1.Geojson: geojson 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})
It works fine. Let me know if anything needs to be optimized...
Upvotes: 1
Reputation: 1850
You need to loop through the file. The file mentioned below is a simple file that has three columns of lat, long and elevation.
If you create a simple text file in this format, this code loops through a file and adds them. It gets the columns which have lat, long, elevation and in the popup creates a dynamic popup.
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())
Upvotes: 4