9

I am plotting some maps using folium. Works pretty smoothly. However, I could not figure out how to pre-calculate the right level of zoom

I can set it automatically

import folium
m = folium.Map([point_of_interest.iloc[0].Lat, point_of_interest.iloc[0].Long])

but in my use case I would need to pre-calculate zoom_start such that:

  • all couples (Lat,Long) from my pandas dataframe of point_of_interest are within the map
  • the zoom level is the mnimum possilbe
00__00__00
  • 4,834
  • 9
  • 41
  • 89

1 Answers1

20

folium's fit_bounds method should work for you

Some random sample data

import folium
import numpy as np
import pandas as pd

center_point = [40, -90]

data = (
    np.random.normal(size=(100, 2)) *
    np.array([[.5, .5]]) +
    np.array([center_point])
)

df = pd.DataFrame(data, columns=['Lat', 'Long'])

Creating a map with some markers

m = folium.Map(df[['Lat', 'Long']].mean().values.tolist())

for lat, lon in zip(df['Lat'], df['Long']):
    folium.Marker([lat, lon]).add_to(m)

fit_bounds requires the 'bounds' of our data in the form of the southwest and northeast corners. There are some padding parameters you can use as well

sw = df[['Lat', 'Long']].min().values.tolist()
ne = df[['Lat', 'Long']].max().values.tolist()

m.fit_bounds([sw, ne]) 
m

enter image description here

Bob Haffner
  • 8,235
  • 1
  • 36
  • 43