[英]python - writing geojson to file
我正在使用Google Maps API,我想獲取PolyLine,然后將其轉換為Lat,Lon,然后轉換為GeoJSON,以便可以使用Mapbox對其進行可視化。 我已經掌握了大部分方法,但仍停留在如何將最終的GeoJSON寫入文件中。
這是我到目前為止的代碼:
#creates empty list for geoJSON
geoList = []
for i in URLlist:
polylineData = json.load(urllib2.urlopen(i))
# try ... except will do what you want when true and put exceptions into false
try:
# looks up polyline string from JSON
polylineExcerpt = polylineData['routes'][0]['overview_polyline']['points']
# use polyline module to decode into lat,lon
waypointData = polyline.decode(polylineExcerpt)
# use geojson library to encode to GeoJSON
encodeWaypoint = LineString(waypointData)
# uses swapCoord function to reverse lat lon
for feature in encodeWaypoint['coordinates']:
flip = swapCoords(feature)
appendLine = geoList.append(flip)
# # puts it back into GeoJSON
convertToGeoJSON = LineString(geoList)
except:
print('something went wrong')
因此,我將所有JSON元素都放在列表中,但不確定如何將其以正確的編碼寫入文件中。 如果我做類似的事情:
with open('data.json', 'a') as f:
json.dump(convertToGeoJSON, f)
然后它不會產生有效的JSON,有沒有辦法更好地創建最終JSON?
您可以通過在循環的每次迭代中一次將一個GeoJSON附加到一個列表中來創建一個GeoJSON列表。 然后,最后一次將Json數組寫入文件。
例如:
geo_json_list = []
for i in your_list:
#code to generate your geoJSON
geo_json_list.append(geo_json)
with open('data.json', 'a') as f:
json.dump(geo_json_list, f)
將其加載到python時,您只需執行此操作
json=open('data.json')
data = json.load(json)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.