使用LineStrings将CSV转换为Geojson

时间:2019-10-23 12:02:37

标签: python geojson kepler.gl

我是地理空间数据的新手,需要一种以这种格式从CSV中获取数据的方法:

Latitude, Longitude, Altitude, Timestamp, Trip Identifier

并以指定的格式转换为适用于kepler.gl的geojson:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": { "vendor": "A",
      "vol":20},
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [-74.20986, 40.81773, 0, 1564184363],
          [-74.20987, 40.81765, 0, 1564184396],
          [-74.20998, 40.81746, 0, 1564184409]
        ]
      }
    }
  ]
}

我在Python中的尝试(主要基于code from ewcz)没有成功;这将返回ValueError,并且由于记录之间的坐标对数发生变化,因此我看不到合并MultiLineString的方法。

import csv, json
from geojson import Feature, FeatureCollection, Point, LineString

features = []
with open('Trips.csv', newline='', encoding='utf-16') as csvfile:
    reader = csv.reader(csvfile, delimiter='    ')
    for Latitude, Longitude, Altitude, Timestamp, ID in reader:
        Latitude, Longitude = map(float, (Latitude, Longitude))
        features.append(
            Feature(
                geometry = LineString([Latitude,Longitude,Altitude,Timestamp]),
                properties = {
                    'ID': ID,
                }
            )
        )

collection = FeatureCollection(features)
with open("Trips.json", "w") as f:
    f.write('%s' % collection)

给出错误:

ValueError                                Traceback (most recent call last)
<ipython-input-1-5dadf758869b> in <module>
      9         features.append(
     10             Feature(
---> 11                 geometry = LineString([Latitude,Longitude,Altitude,Timestamp]),
     12                 properties = {
     13                     'ID': ID

~/anaconda3/anaconda3/lib/python3.7/site-packages/geojson/geometry.py in __init__(self, coordinates, validate, precision, **extra)
     30         super(Geometry, self).__init__(**extra)
     31         self["coordinates"] = self.clean_coordinates(
---> 32             coordinates or [], precision)
     33 
     34         if validate:

~/anaconda3/anaconda3/lib/python3.7/site-packages/geojson/geometry.py in clean_coordinates(cls, coords, precision)
     53                 new_coords.append(round(coord, precision))
     54             else:
---> 55                 raise ValueError("%r is not a JSON compliant number" % coord)
     56         return new_coords
     57 

ValueError: '0' is not a JSON compliant number

1 个答案:

答案 0 :(得分:0)

问题似乎在于您正在将字符串传递给需要数字的API。

for Latitude, Longitude, Altitude, Timestamp, ID in reader

应替换为将字符串转换为数字的代码。像这样:

for float(Latitude), float(Longitude), int(Altitude), int(Timestamp), ID in reader

数据示例:

51.467525   -0.445004   0   1569324754  EIN159

所以看起来前两个字段是浮点数,字段3,4是整数,字段5是字符串。