Adding 1KM grids to Folium map

94 views Asked by At

Could someone suggest a way to adding 1KM wide grids/graticules to folium map? The folium example here uses lat/longitude intervals but doesn't render the grid.


import folium

# Bangkok coordinates
center_lat = 13.7563
center_lon = 100.4911

m = folium.Map(location=[center_lat, center_lon], zoom_start=11)


# Interval in degrees (1 kilometer ≈ 0.00694444 degrees)
interval = 0.00694444

# Create grid lines
grid_lines = []

# East-west lines (from -90 to 90 latitude)
for lat in range(-90, 91, int(1 / interval)):
  west_point = (-180, lat)
  east_point = (180, lat)
  grid_lines.append(folium.PolyLine([west_point, east_point], color="black", weight=0.5, opacity=0.5))

# North-south lines (from -180 to 180 longitude)
for lon in range(-180, 181, int(1 / interval)):
  south_point = (lon, -90)
  north_point = (lon, 90)
  grid_lines.append(folium.PolyLine([south_point, north_point], color="black", weight=0.5, opacity=0.5))

# Add lines to the map
for line in grid_lines:
  line.add_to(m)

# Display the map
m
1

There are 1 answers

4
Timeless On

Your grid does actually render on the map but it's not as you expect because you're using range instead of numpy.arange. Also you're inverting the locations of each PolyLine in your two for-loops. So, here is one possible fix :

import folium
import numpy as np

CLAT, CLON = 13.7563, 100.4911

m = folium.Map(location=[CLAT, CLON], zoom_start=11)

INTERVAL = 1 / 111  # 1 km to degrees, gives ~0.009

LINE_STYLE = {"color": "black", "weight": 0.5, "opacity": 0.5}

def add_gl(m, s, e, hztl, **kwargs):
    for v in np.arange(s, e + 1, INTERVAL):
        coords = [[v, -180], [v, 180]] if hztl else [[-90, v], [90, v]]
        folium.PolyLine(coords, **kwargs).add_to(m)

add_gl(m, -90, 90, True, **LINE_STYLE)
add_gl(m, -180, 180, False, **LINE_STYLE)

NB : It took ~40 seconds for the map to display on my JupyterLab and the navigation is relatively cumbersome/slow. So, if performance is a concern, you may need to reduce the interval :

INTERVAL = 10 / 111  # 10 kms instead of 1km

# with this, the map takes ~2-5s to render

Output (m):

enter image description here