用 Folium 和 Geopandas 绘制多边形不起作用

Plotting polygons with Folium and Geopandas don't work

我尝试使用 Geopandas official tutorial and this 数据集绘制多边形以使用 Geopandas 和 Folium 进行映射。我尽量按照字面意思按照教程进行操作,但 Folium 仍然不绘制多边形。 Matplotlib 地图有效,我也可以创建 Folium 地图。代码:

import pandas as pd
import geopandas as gdp
import folium
import matplotlib.pyplot as plt

df = pd.read_csv('https://geo.stat.fi/geoserver/wfs?service=WFS&version=2.0.0&request=GetFeature&typeName=postialue:pno_tilasto&outputFormat=csv')
df.to_csv('coordinates.csv')

#limit to Helsinki and drop unnecessary columns 
df['population_2019'] = df['he_vakiy']
df['zipcode'] = df['postinumeroalue'].astype(int)
df['population_2019'] = df['population_2019'].astype(int)
df = df[df['zipcode'] < 1000]
df = df[['zipcode', 'nimi', 'geom', 'population_2019']]
df.to_csv('coordinates_hki.csv')
df.head()

#this is from there: https://gis.stackexchange.com/questions/387225/set-geometry-in-#geodataframe-to-another-column-fails-typeerror-input-must-be
from shapely.wkt import loads
df = gdp.read_file('coordinates_hki.csv')
df.geometry =  df['geom'].apply(loads)
df.plot(figsize=(6, 6))
plt.show()

df = df.set_crs(epsg=4326)
print(df.crs)
df.plot(figsize=(6, 6))
plt.show()

m = folium.Map(location=[60.1674881,24.9427473], zoom_start=10, tiles='CartoDB positron')
m

for _, r in df.iterrows():
    # Without simplifying the representation of each borough,
    # the map might not be displayed
    sim_geo = gdp.GeoSeries(r['geometry']).simplify(tolerance=0.00001)
    geo_j = sim_geo.to_json()
    geo_j = folium.GeoJson(data=geo_j,
                           style_function=lambda x: {'fillColor': 'orange'})
      
    folium.Popup(r['nimi']).add_to(geo_j)
    geo_j.add_to(folium.Popup(r['nimi']))                  
m

这里的诀窍是要意识到您的数据不是以度为单位的。您可以通过查看多边形的质心来确定这一点:

>>> print(df.geometry.centroid)
0     POINT (381147.564 6673464.230)
1     POINT (381878.124 6676471.194)
2     POINT (381245.290 6677483.758)
3     POINT (381050.952 6678206.603)
4     POINT (382129.741 6677505.464)
                   ...              
79    POINT (397465.125 6676003.926)
80    POINT (393716.203 6675794.166)
81    POINT (393436.954 6679515.888)
82    POINT (395196.736 6677776.331)
83    POINT (398338.591 6675428.040)
Length: 84, dtype: geometry

这些值远远大于地理空间数据的正常范围,经度为 -180 到 180,纬度为 -90 到 90。下一步是弄清楚它实际上在什么 CRS 中。如果你拿你的数据集 URL,并去掉 &outputFormat=csv 部分,你会得到这个 URL:

https://geo.stat.fi/geoserver/wfs?service=WFS&version=2.0.0&request=GetFeature&typeName=postialue:pno_tilasto

在该文档中搜索 CRS,您会发现:

<gml:Envelope srsName="urn:ogc:def:crs:EPSG::3067" srsDimension="2">

原来你的数据在 EPSG:3067 中,这是代表芬兰坐标的标准。

您需要将此告知 geopandas,并转换为 WGS84(最常见的坐标系)以使其与 folium 兼容。

df.geometry =  df['geom'].apply(loads)
df = df.set_crs('EPSG:3067')
df = df.to_crs('WGS84')

函数set_crs(), changes the coordinate system that GeoPandas expects the data to be in, but does not change any of the coordinates. The function to_crs()获取数据集中的点并将它们重新投影到新的坐标系中。这两个调用的效果是从EPSG:3067转换为WGS84.

通过添加这两行,我得到以下结果: