2 Must Know folium Python tricks 👌

If you are performing any sort of machine learning or data science type work using python, then here are 3 tricks to make your geo location mapping life with folium a little easier.

Shaun Enslin
2 min readNov 7, 2022
Photo by Z on Unsplash

#1 Center your image

Nothing is more frustrating than not having your folium map not centering on your plotted points. Our data has a longitude/latitude and we want to show these points on a map, using a different color for each sales rep.

# Colors to use on the map
lst_colors = ['#3498DB','#E74C3C','#512E5F','#A569BD','#154360','#85C1E9','#909497','#76D7C4','#229954','#82E0AA','#7D6608','#F7DC6F','#F5B041','#F39C12','#784212','#909497','#2C3E50','#2C3E51']
## Encode RepID's
le = LabelEncoder()
df['RepIDnum'] = le.fit_transform(df['RepID'])
# Plot initial for the report
lst_reps = sorted(list(df.RepIDnum.unique()))
k = len(lst_reps) - 1
# Get our list of unique clusters
lst_elements = sorted(list(df.RepIDnum.unique()))
# Add color column to dataframe and apply colors
df["color"] = df["RepIDnum"]
df["color"] = df["color"].apply(lambda x: lst_colors[lst_elements.index(x)])

Now that we have that, lets go and find the center of our plotted points

middle = df[['Latitude', 'Longitude']].median().values.tolist()

We have the centre of our map’s plotted points, lets add our markers, but be sure to set initial location to middle.

m = folium.Map(location=middle)
for index, row in df[df['CustomerID'] != 'Home'].iterrows():
folium.CircleMarker(location= [float(row['Latitude']),float(row['Longitude'])],radius=6,fill=True,fill_color=row['color'],
).add_to(m)

Finally, generate the map

m

#2 Optimal zoom location

Ok, now that we have an image where the plots are in the middle, lets get an optimal zoom location. So using above code, simply add where we find the south west and north east locations. Then use fit_bounds to get a perfect zoom.

sw = df[['Latitude', 'Longitude']].min().values.tolist()
ne = df[['Latitude', 'Longitude']].max().values.tolist()
m.fit_bounds([sw, ne])
m

You should end up with an image that is centred and zoomed to perfection.

--

--