PythonでGeoJSONを作る時、、、
今まではすごい無理矢理な感じで書き出して作り出してたのです。
ただ、もっと絶対にいい方法あるだろ。。。と思って、血眼になってググったところ
PythonにGeoJSONのモジュールがあることに今更気付いたので、これを使ってJSONからGeoJSONを生成していこうかなと思います。
Pythonのモジュールはこちらをご参照ください。結構なんでもできますね!
https://pypi.org/project/geojson/
早速使ったコードはこちら
今回作ったPythonはこちら。
geojsonモジュールを入れております。
import json
import geojson
from geojson import Point, Feature, FeatureCollection, dump
data = "<input JSON File>"
f = open(data)
j = json.load(f)
features = []
for d in j:
coords = <JSONのLon,Lat部分>
feature = geojson.Feature(
geometry=geojson.Point(coords),
properties={
"aa": d["aa"],
"bb": d["bb"],
"cc": d["cc"],
"dd": d["dd"]
}
)
features.append(feature)
feature_collection = geojson.FeatureCollection(features)
with open("<Output File>", "w") as f:
geojson.dump(feature_collection, f, indent=2)
こ、、、これでできるんだ。。。今までの俺は一体。。。な感想でした。
今まではJSONを律儀に読み取り、一つずつ分けて書き出し、GeoJSONのお作法に則るという
まさに「なんちゃってGeoJSON」。
PythonでできたOutPutは。。。。
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
139.880647,
35.629796
]
},
"properties": {
"aa": "aaa ",
"bb": " ",
"cc": "-1",
"dd": "2023-03-22 00:00:53.095615"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
136.843610,
35.050258
]
},
"properties": {
"aa": "abc ",
"bb": " ",
"cc": "-1",
"dd": "2023-03-22 00:00:53.095615"
}
}
]
}
geojson.ioでも表示できました!
ディズニーランドとレゴランドの位置情報が入っていました〜!
GeoJSONモジュールの入れ方
どうやって入れるんだ、はよ教えろ。と思ったあなた!
この呪文をターミナルに入力してみてください〜
pip3 install geojson