如何将一组 folium 标记保存到 geojson?

How do I save a set of folium markers to a geojson?

我有以下 folium 标记,想将它们保存到 python 中的 geojson 文件中。

neb1 = folium.Marker([nebraska[0]+1.73, nebraska[1]-3.46], icon = folium.Icon()).add_to(m)
neb2 = folium.Marker([nebraska[0]+2.73, nebraska[1]-3.46], icon = folium.Icon()).add_to(m)
neb3 = folium.Marker([nebraska[0]+2.73, nebraska[1]-5.46], icon = folium.Icon()).add_to(m)
neb4 = folium.Marker([nebraska[0]+4.73, nebraska[1]-3.46], icon = folium.Icon()).add_to(m)
neb5 = folium.Marker([nebraska[0]+4.73, nebraska[1]], icon = folium.Icon()).add_to(m)
neb5 = folium.Marker([nebraska[0]+1.73, nebraska[1]+3.2], icon = folium.Icon()).add_to(m)

如何实现?

谢谢!

您可以使用 geojson 库创建 GeoJSON 文件。

注意folium.Marker()使用坐标按纬度、经度顺序和geojson Point()坐标按经度、纬度顺序所以记得使用正确的顺序。

from geojson import Feature, Point, FeatureCollection, dumps

nebraska = [38.2, -98.5] # lat, lon

points = [
    Point((nebraska[1]-3.46, nebraska[0]+1.73)),
    Point((nebraska[1]-3.46, nebraska[0]+2.73)),
    Point((nebraska[1]-5.46, nebraska[0]+2.73)),
    Point((nebraska[1]-3.46, nebraska[0]+4.73)),
    Point((nebraska[1], nebraska[0]+4.73)),
    Point((nebraska[1]+3.2, nebraska[0]+1.73))
    ]

features = [Feature(geometry=p) for p in points]
feature_collection = FeatureCollection(features)
with open("out.geojson", "w") as fout:
    fout.write(dumps(feature_collection))

这将输出具有以下结构的 GeoJSON 文件:

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    -101.96, 39.93
                ]
            },
            "properties": {}
        },
        ...
}

然后您可以使用 folium.GeoJson() 函数将 GeoJSON 文件加载到 folium 地图中。

folium 地图中显示的 GeoJSON 文件如下所示: