我有一个Django应用程序,它从外部API请求数据,我的目标是将以列表/字典格式返回的数据转换为一个带有Geojson格式的新REST。
我偶然遇到了django-rest-framework-gis,但我不知道我是否可以在没有模型的情况下使用它。但如果是的话,怎么做?
发布于 2022-04-25 14:20:39
我认为最好的方法是使用python库geojson
pip install geojson如果您没有类似geodjango中的模型,则必须根据您拥有的数据显式地描述几何学。
from geojson import Point, Feature, FeatureCollection
data = [
{
"id": 1,
"address": "742 Evergreen Terrace",
"city": "Springfield",
"lon": -123.02,
"lat": 44.04
},
{
"id": 2,
"address": "111 Spring Terrace",
"city": "New Mexico",
"lon": -124.02,
"lat": 45.04
}
]
def to_geojson(entries):
features = []
for entry in entries:
point = Point((entry["lon"], entry["lat"]))
del entry["lon"]
del entry["lat"]
feature = Feature(geometry=point, properties=entry)
features.append(feature)
return FeatureCollection(features)
if __name__ == '__main__':
my_geojson = to_geojson(data)
print(my_geojson)结果:
{“特征”:[{“几何”:{“坐标”:-123.02,44.04,“类型”:“点”},“属性”:{“地址”:"742常绿露台“,”城市“:”春田“,"id":1},”类型“:”特征“},{”几何“:{”坐标“:-124.02,45.04,”类型“:”点“}“属性”:{“地址”:“111个春季平台”、“城市”:“新墨西哥州”、"id":2}、"type":“Feature”}、"type":"FeatureCollection"}
这里有更多信息:文献资料- Geojson图书馆
https://stackoverflow.com/questions/71964048
复制相似问题