在Folium地图上添加1KM网格

0 投票
1 回答
92 浏览
提问于 2025-04-14 18:00

有没有人能推荐一种方法,在folium地图上添加1公里宽的网格线?这里的folium示例使用的是经纬度间隔,但并没有显示出网格。


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 个回答

1

你的网格确实在地图上显示出来了,但效果和你预期的有些不同,因为你用了range,而不是numpy.arange。另外,你在两个循环中反转了每个PolyLine的位置。所以,这里有一个可能的解决办法:

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)

注意:在我的JupyterLab上,地图显示大约花了40秒,操作起来也比较麻烦/慢。所以,如果性能是个问题,你可能需要减少间隔:

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

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

输出(m):

在这里输入图片描述

撰写回答