使用Folium和Geopandas绘制面不起作用

tquggr8v  于 2023-04-28  发布在  其他
关注(0)|答案(1)|浏览(126)

我尝试使用Geopandas official tutorialthis数据集绘制多边形以使用Geopandas和Folium进行Map。我试着按照教程作为字面上,因为我可以,但仍然叶不画多边形。MatplotlibMap工作,我可以创建叶Map太多。验证码:

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
yzxexxkh

yzxexxkh1#

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

>>> 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这一点,并转换成WGS 84(最常见的坐标系),使其与folium兼容。

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

函数set_crs()更改GeoPandas期望数据所在的坐标系,但不更改任何坐标。函数to_crs()获取数据集中的点,并将它们重新投影到新的坐标系中。这两个调用的效果是将EPSG:3067转换为WGS 84。
通过添加这两行,我得到以下结果:

相关问题