Folium adding an overlay (.geojson) to map - python

This is what I have so far:
import folium
m = folium.Map(
    location=[43.761539, -79.411079],
    tiles="Stamen Toner",
    zoom_start=11
    )
m.save("index.html")
folium.GeoJson("file.geojson").add_to(m)
m
Up until the folium.GeoJson... line the map shows up but the overlay makes nothing render

You need to add a LayerControl():
import folium
m = folium.Map(
location=[43.761539, -79.411079],
tiles="Stamen Toner",
zoom_start=11
)
folium.GeoJson("file.geojson", name="geojson").add_to(m)
folium.LayerControl().add_to(m)
m.save("index.html")
m

Related

Folium Multiple frames of Global Map splitting geo coordinates - Python

I am trying to plot route on map using folium in python. It is splitting coordinates in the final result. I would like to plot them continuously in one frame. Below is the python code i am using.
import folium
import numpy as np
waypoint_lat = [46.18143,41.181091,41.116669,41.106354,41.096893,41.088089,41.079468,41.07132,41.066666,41.65184,42.302689,42.932678,43.538879,44.118713,44.350006,44.566467,44.795288,45.021225,45.228516,45.441422,45.672607,45.899078,46.085281,46.249039,46.4021,46.541992,46.667572,46.780228,46.886292,46.985153,47.077133,47.166321,47.252747,47.335037,47.4104,47.479202,47.539337,47.589584,47.629623,47.658722,47.676178,47.681091,47.672974,47.651947,47.618027,47.571045,47.516556,47.451935,47.37735,47.291672,47.194977,47.087677,46.972733,46.847122,46.711166,46.567368,46.41391,46.253204,46.082031,45.901016,45.710999,45.510651,45.302277,45.081284,44.849564,44.6017,44.345261,44.085999,43.816605,43.531265,43.245621,42.949341,42.635452,42.3078,41.976959,41.637436,41.282333,40.91713,40.541733,40.158661,39.764236,39.36058,38.950378,38.531982,38.10463,37.670044,37.22699,36.768356,36.287155,35.790436,35.306839,34.832123,34.355316,33.886368,33.633331,33.062317,32.48587,31.900589,31.302673,30.687531,30.07962,30.066666,29.484695,28.896545,28.311295,27.724777,27.136093,26.538879,25.937531,25.336563,24.732254,24.129868,23.524063,22.919983,22.314301,21.705246,21.096741,20.487854,20.100006,19.558319,19.449997,18.789169,18.129257,17.475418,16.82338,16.166107,15.51886,14.872589,14.22435,13.566574,12.905838,12.243958,11.579559,10.912247,10.243134,9.568069,8.888062,8.201279,7.639999,7.1884,6.432449,5.686813,4.948334,4.266663,3.409943,2.639999,1.717728,1.5,1.416672,1.316666,1.293335,1.278336,1.261673,1.21051,1.185333,1.173126,1.138107]
waypoint_lon = [-135.63028, -131.869141, -131.916672, -132.936081, -133.873093, -134.743637, -135.597321, -136.405945, -136.883331, -137.526886, -138.242645, -138.948761, -139.629333, -140.298294, -140.566666, -141.428207, -142.375839, -143.353027, -144.290405, -145.299164, -146.45517, -147.659042, -148.711578, -149.692413, -150.66423, -151.607285, -152.506775, -153.364441, -154.224182, -155.080688, -155.935669, -156.830948, -157.777847, -158.774689, -159.799591, -160.870987, -161.971848, -163.091309, -164.236511, -165.407211, -166.606674, -167.825409, -169.055115, -170.274704, -171.492157, -172.712128, -173.829758, -174.933807, -176.02684, -177.125153, -178.225937, -179.323364, 179.608582, 178.539032, 177.471298, 176.423508, 175.380585, 174.35704, 173.331573, 172.308563, 171.29277, 170.27713, 169.273163, 168.259186, 167.245453, 166.210403, 165.186951, 164.195953, 163.20784, 162.20282, 161.235336, 160.268799, 159.28215, 158.28949, 157.322495, 156.363739, 155.394485, 154.430481, 153.471542, 152.523804, 151.578018, 150.639374, 149.713593, 148.796509, 147.886139, 146.98584, 146.092697, 145.192749, 144.273666, 143.350204, 142.474213, 141.635101, 140.811829, 140.020126, 139.600006, 138.87883, 138.150818, 137.421051, 136.676163, 135.918533, 135.15126, 135.133331, 134.340576, 133.540741, 132.751831, 131.963806, 131.178192, 130.385071, 129.59021, 128.801056, 128.009583, 127.22702, 126.441483, 125.663651, 124.886047, 124.107986, 123.334137, 122.562057, 121.999954, 121.166656, 121.0, 120.299118, 119.60025, 118.911514, 118.226517, 117.538605, 116.863647, 116.191223, 115.519699, 114.839066, 114.158752, 113.477951, 112.797043, 112.114349, 111.431427, 110.744141, 110.052628, 109.356384, 108.710007, 108.340073, 107.724884, 107.118484, 106.518951, 105.949997, 105.510513, 105.110001, 104.651566, 104.543335, 104.443329, 104.32666, 104.203339, 104.109161, 104.0, 103.879089, 103.825546, 103.793686, 103.742111]
clubbed_position = np.column_stack((waypoint_lat,waypoint_lon))
latlon = clubbed_position
mapit = folium.Map( location=latlon[[0,1], [0,1]], zoom_start=2,min_zoom=1,max_zoom=8 )
for coord in latlon:
folium.CircleMarker(location=[ coord[0], coord[1] ], fill_color='#43d9de', radius=5).add_to(mapit)
mapit.save('map.html')
As you can see in above image, routes are separated (splitted). We want to see one continuous path.
Request your help.
Best Regards
Take a look at PolyLine, which can be used to plot routes: https://nbviewer.org/github/python-visualization/folium/blob/main/examples/Quickstart.ipynb#Polylines

Folium popup does not appear python

I have a geodataframe with Multistring Geometry. I wanted to plot an interactive map, on which when I click on each line, the name and id would appear! I can see that mouse form would change but nothing will appear. I also tried to define the names as labels but it did not work!
Ex_centreLine_map= folium.Map(location = [43.7180, -79.3762], zoom_start=12)
folium.Choropleth(
centreline_gdf[centreline_gdf.geometry.length> 0.00001],
line_weight=3,
line_color='blue',
popup=centreline_gdf[['lf_name', 'lfn_id']]).add_to(Ex_centreLine_map)
Ex_centreLine_map
you have not provided any sample data, so I have used some road data to make a MWE
you can do native folium however it's simpler to use geopandas explore()
for native folium you can to use folium.GeoJson()
import geopandas as gpd
import pandas as pd
import shapely.wkt
import io
df = pd.read_csv(io.StringIO("""ref;lanes;highway;maxspeed;length;name;geometry
A3015;2;primary;40 mph;40.68;Rydon Lane;MULTILINESTRING ((-3.4851169 50.70864409999999, -3.4849879 50.7090007), (-3.4857269 50.70693379999999, -3.4853034 50.7081574), (-3.488620899999999 50.70365289999999, -3.4857269 50.70693379999999), (-3.4853034 50.7081574, -3.4851434 50.70856839999999), (-3.4851434 50.70856839999999, -3.4851169 50.70864409999999))
A379;3;primary;50 mph;177.963;Rydon Lane;MULTILINESTRING ((-3.4763853 50.70886769999999, -3.4786112 50.70811229999999), (-3.4746017 50.70944449999999, -3.4763853 50.70886769999999), (-3.470350900000001 50.71041779999999, -3.471219399999999 50.71028909999998), (-3.465049699999999 50.712158, -3.470350900000001 50.71041779999999), (-3.481215600000001 50.70762499999999, -3.4813909 50.70760109999999), (-3.4934747 50.70059599999998, -3.4930204 50.7007898), (-3.4930204 50.7007898, -3.4930048 50.7008015), (-3.4930048 50.7008015, -3.4919513 50.70168349999999), (-3.4919513 50.70168349999999, -3.49137 50.70213669999998), (-3.49137 50.70213669999998, -3.4911565 50.7023015), (-3.4911565 50.7023015, -3.4909108 50.70246919999999), (-3.4909108 50.70246919999999, -3.4902349 50.70291189999999), (-3.4902349 50.70291189999999, -3.4897693 50.70314579999999), (-3.4805021 50.7077218, -3.4806265 50.70770150000001), (-3.488620899999999 50.70365289999999, -3.4888806 50.70353719999999), (-3.4897693 50.70314579999999, -3.489176800000001 50.70340539999999), (-3.489176800000001 50.70340539999999, -3.4888806 50.70353719999999), (-3.4865751 50.70487679999999, -3.4882604 50.70375799999999), (-3.479841700000001 50.70784459999999, -3.4805021 50.7077218), (-3.4882604 50.70375799999999, -3.488620899999999 50.70365289999999), (-3.4806265 50.70770150000001, -3.481215600000001 50.70762499999999), (-3.4717096 50.71021009999998, -3.4746017 50.70944449999999), (-3.4786112 50.70811229999999, -3.479841700000001 50.70784459999999), (-3.471219399999999 50.71028909999998, -3.4717096 50.71021009999998))"""),
sep=";")
gdf = gpd.GeoDataFrame(df, geometry=df["geometry"].apply(shapely.wkt.loads), crs="epsg:4326")
gdf.explore(style_kwds={"weight":10})
native folium
import folium
m = folium.Map(
location=[sum(gdf.total_bounds[[1, 3]]) / 2, sum(gdf.total_bounds[[0, 2]]) / 2],
zoom_start=12,
)
def style_fn(x):
return {"color":"blue", "weight":3}
folium.GeoJson(
gdf,
style_function=style_fn,
popup=folium.GeoJsonPopup(gdf.drop(columns=["geometry"]).columns.tolist()),
tooltip=folium.GeoJsonTooltip(["ref"]),
).add_to(m)
m

folium draw circle not drawing

I'm trying to draw some circles to outline koala sightings around Brisbane Aus. When I try and run it in jupyter, it draws the map and if I replace the coordinate[["decimalLatitude"],coordinate["decimalLongitude"]] with actual values, it displays, but otherwise it doesn't. Here's my code and a sample pic of the data.
import folium
map_of_koala_sightings = folium.Map(
location =[-27.470125,153.021072],
zoom_start=13, tiles='Stamen Terrain'
)
for coordinate in koala_df:
try:
folium.Circle(
radius=300,
location = coordinate[["decimalLatitude"],coordinate["decimalLongitude"]],
color='#3388ff',
fill=True).add_to(map_of_koala_sightings)
except:
pass
map_of_koala_sightings
Sample Data
This works for me (with a subset of coordinates).
import folium
import pandas as pd
koala_df = pd.DataFrame(columns = ['decimalLatitude','decimalLongitude'],
data = [[-26.770484,152.838467],
[-28.103458,153.375882],
[-26.4,146.25]])
print(koala_df.head())
map_of_koala_sightings = folium.Map(
location =[-27.470125,153.021072],
zoom_start=5, tiles='Stamen Terrain'
)
for idx,coordinate in koala_df.iterrows():
folium.Circle(radius=300,
location = [coordinate['decimalLatitude'],coordinate['decimalLongitude']],
color='#3388ff',
fill=True).add_to(map_of_koala_sightings)
#map_of_koala_sightings
#For saving to html file
map_of_koala_sightings.save('koalas.html')
Output:
decimalLatitude decimalLongitude
0 -26.770484 152.838467
1 -28.103458 153.375882
2 -26.400000 146.250000
and 'koalas.html' contains:

How to add Cluster markers to Choropleth with Folium

I've been working for a while with Choropleth and Cluster marker maps in Folium (which are great). My question is whether it is possible to combine them in one map, which is so that I can see how much one variable affects another. I can get both map types to work individually so no problems there. This is my attempted code to combine the two so far:
import pandas as pd
import folium
from folium.plugins import MarkerCluster
input_filename="input_filename.csv"
df = pd.read_csv(input_filename,encoding='utf8')
geo = 'blah.json'
comparison = 'comparison.csv'
comparison_data = pd.read_csv(comparison)
m = folium.Map(location=[Lat,Lon], zoom_start=12)
folium.Choropleth(
geo_data=geo,
name='choropleth',
data=comparison_data,
columns=['col1','col2'],
key_on='feature.properties.ID',
fill_color='OrRd',
fill_opacity=0.5,
line_opacity=0.5,
legend_name='Blah (%)'
).add_to(m)
folium.LayerControl().add_to(m)
marker_cluster = MarkerCluster().add_to(m)
for row in df.itertuples():
folium.Marker(location=[row.Lat,row.Lon],popup=row.Postcode).add_to(marker_cluster)
m
It produces the choropleth but won't layer the cluster markers as well. Worth noting that I've had a problem with cluster markers separately where they wouldn't display in Jupyter notebook, but I got around it by saving the file as an html, which was then viewable.
Ok so I've solved it, really pleased!! The solution was to do the marker cluster first, and then follow-up with the Choropleth:
import pandas as pd
import folium
from folium.plugins import MarkerCluster
m = folium.Map(location=[Lat,Lon], zoom_start=12)
input_filename="input_filename.csv"
df = pd.read_csv(input_filename,encoding='utf8')
geo = 'blah.json'
comparison = 'comparison.csv'
comparison_data = pd.read_csv(comparison)
folium.LayerControl().add_to(m)
marker_cluster = MarkerCluster().add_to(m)
for row in df.itertuples():
folium.Marker(location=[row.Lat,row.Lon],popup=row.Postcode).add_to(marker_cluster)
folium.Choropleth(
geo_data=geo,
name='choropleth',
data=comparison_data,
columns=['col1','col2'],
key_on='feature.properties.ID',
fill_color='OrRd',
fill_opacity=0.5,
line_opacity=0.5,
legend_name='Blah (%)'
).add_to(m)
m
from random import randint
import folium
def rgb_to_hex(rgb):
return '#%02x%02x%02x' % rgb
mp = folium.Map(location=[40.6, -73.7], scale = 10)
colors = []
while len(colors) != 50:
r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)
if rgb_to_hex((r, g, b)) not in colors:
colors.append(rgb_to_hex((r, g, b)))
for j in range(df.shape[0]):
lat = df.iloc[j]['latitude']
lon = df.iloc[j]['longitude']
color = colors[int(df.iloc[j]['clust'])]
folium.Circle(location=[lat, lon], radius=8, color = color).add_to(mp)

How Can I Render More Than 1000 Points in Folium

I am trying to render 15,000 points in folium. When I have less than 1000 points I get a map that renders as the attached image (example map). When I include over 1000 my code returns an item void of either a map or points. The following is my code:
z230['marker_color'] = pd.cut(z230['ClosePrice'], bins=5,
labels=['blue','green','yellow','orange','red'])
m = folium.Map(location=[39.2904, -76.6122], zoom_start=12)
for index, row in z230.iterrows():
folium.CircleMarker([row['Latitude'], row['Longitude']],
radius=15, color=row['marker_color']).add_to(m)
m
The only useful workaround I could find was to include cluster markers.
from folium.plugins import FastMarkerCluster
x = #your centering coordinates here LAT
y = #your centering coordinates here LONG
z = #your zoomlevel here
your_map = folium.Map(location=[x, y], tiles="OpenStreetMap", zoom_start=z)
callback = ('function (row) {'
'var circle = L.circle(new L.LatLng(row[0], row[1]), {color: "red", radius: 10000});'
'return circle};')
your_map.add_child(FastMarkerCluster(your_df[['your_LAT_col', 'your_LONG_col']].values.tolist(), callback=callback))
your_map

Categories