Folium地图无法显示多边形问题排查求助
问题
通过API获取坐标后用Shapely创建多边形,点是否在多边形内的判断功能正常(能正确输出The point is inside a area),但使用Folium展示时,地图仅显示点,无法显示多边形。怀疑与多坐标系使用有关,需要排查原因并修复。
问题排查与解决
核心原因
问题确实出在坐标系不匹配:
- 从API获取的多边形坐标是SWEREF99(EPSG:3006)格式的平面坐标(单位为米),而Folium地图默认使用WGS84(EPSG:4326)的经纬度坐标(单位为十进制度)。
- 代码中仅转换了用于判断的点,未对多边形坐标做反向转换,导致多边形坐标值与地图的经纬度范围完全脱节,因此无法在地图上渲染出来。
修复步骤
- 定义从SWEREF99到WGS84的坐标转换器
- 遍历每个多边形,将其坐标从SWEREF99转换为WGS84格式
- 转换时保持
always_xy=True,确保坐标顺序为(经度,纬度)
修改后的完整代码
import requests import folium from shapely.geometry import Point, Polygon from shapely.ops import transform import pyproj # Define the coordinate systems wgs84 = pyproj.CRS('EPSG:4326') sweref99 = pyproj.CRS('EPSG:3006') # Fetch the areas from the API url = 'examplecoordinates.com' response = requests.get(url) data = response.json() # 定义SWEREF99转WGS84的转换器 project_sweref_to_wgs84 = pyproj.Transformer.from_crs(sweref99, wgs84, always_xy=True).transform # Extract the polygons from the response and store them in a list polygons = [] polygons_wgs84 = [] # 存储转换后的WGS84格式多边形 for feature in data['features']: coords = feature['geometry']['coordinates'][0] polygon = Polygon(coords) polygons.append(polygon) # 将多边形转换为WGS84格式 polygon_wgs84 = transform(project_sweref_to_wgs84, polygon) polygons_wgs84.append(polygon_wgs84) # Define the point to check in WGS84 point_wgs84 = Point(15.0560, 65.7346) # Convert the point to SWEREF99 project_wgs84_to_sweref = pyproj.Transformer.from_crs(wgs84, sweref99, always_xy=True).transform point_sweref99 = transform(project_wgs84_to_sweref, point_wgs84) # Check if the point is inside any of the polygons inside_risk_area = False for polygon in polygons: if polygon.contains(point_sweref99): inside_risk_area = True print('The point is inside a area') break else: print('The point is not inside any area') # Create a map centered at the point of interest m = folium.Map(location=[point_wgs84.y, point_wgs84.x], zoom_start=10) # Add a marker for the point of interest folium.Marker([point_wgs84.y, point_wgs84.x]).add_to(m) # Add the areas as polygons to the map(使用转换后的WGS84多边形) for polygon in polygons_wgs84: coords = [[p[1], p[0]] for p in polygon.exterior.coords] color = 'red' if inside_risk_area else 'green' folium.Polygon(locations=coords, color=color, fill_color=color, fill_opacity=0.3).add_to(m) # Display the map m.save('map.html')
内容的提问来源于stack exchange,提问作者Hugo Lundqvist
相关产品推荐
相关产品推荐

