将CSV转换为GeoJSON

时间:2018-04-09 14:59:46

标签: python json python-3.x csv geojson

我开始使用Python3,我正在编写一个脚本,将CSV文件转换为GeoJSON文件。 转换工作但我仍然有坐标问题,没有采取正确的格式。我需要删除双引号,但它不起作用。

以下是我的代码的一部分:

def readCsvFile():
    features=[]
    geoJson={}
    with open('resources/data_export.csv',newline= '') as csvfile:
        csvReader = csv.DictReader(csvfile,delimiter=',',quotechar='|')
        for row in csvReader:
            features.append({'type': 'Feature',
                            'geometry': {
                                'type': 'Point', "coordinates" : [str(row['longitude']), str(row['latitude'])]}, 'properties': {'id': decodeString(row['id']), 'field1': decodeString(row['field1']), 'field2': decodeString(row['field2'])})

    geoJson = {'type': 'FeatureCollection', 'features': features}
    return json.dumps(geoJson)

我得到了那个结果:

{"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": {"type": "Point", "coordinates": ["16.394564", "48.246426"]}, "properties": {"id": "0", ...

虽然我应该得到:

{"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": {"type": "Point", "coordinates": [16.394564, 48.246426]}, "properties": {"id": "0",

2 个答案:

答案 0 :(得分:4)

尝试将其转换为浮点数而不是字符串:

"coordinates" : [float(row['longitude']), float(row['latitude'])]}

答案 1 :(得分:2)

我在不同的项目中做了很多这样的事情。我喜欢使用熊猫并重新编写您可以使用的代码示例(如果您感兴趣的话)。 Pandas将确保您的列自动转换为浮动。

import pandas as pd
import json
import requests

def df2geojson(df, latlng = []):
    """Function converting pandas table to GEOJSON-format-string"""
    features = []
    for ind, row in df.iterrows():
        geometry = dict(type='Point', coordinates=row[latlng].tolist())
        properties = {k:v for k,v in row.items() if k not in latlng}
        features.append(dict(type='Feature',geometry=geometry, properties=properties))
    return dict(type="FeatureCollection",features=features)

data = '''\
id,field1,field2,longitude,latitude
0,100,100,0,16.394564,48.246426
1,200,200,0,16.494564,48.346426'''

filelikeobject = pd.compat.StringIO(data)          # simulates a file-object
df = pd.read_csv(filelikeobject)                   # should be: 'resources/data_export.csv'
jsonstr = df2geojson(df, ['latitude','longitude']) # pass dataframe and latlng colnames

#with open('output.geojson','w') as f:              # finally write to file
#    json.dump(jsonstr,f,indent=2)                  # disabled

baseurl = 'http://geojson.io/#data=data:application/json,'     # geojson.io url
url = baseurl+requests.utils.requote_uri(json.dumps(jsonstr))  # encode the json

print(url)

导致您可以单击的URL(如果是大文件,则使用文件转储):http://geojson.io/#data=data:application/json,%7B%22type%22:%20%22FeatureCollection%22,%20%22features%22:%20[%7B%22type%22:%20%22Feature%22,%20%22geometry%22:%20%7B%22type%22:%20%22Point%22,%20%22coordinates%22:%20[48.246426,%2016.394564000000003]%7D,%20%22properties%22:%20%7B%22id%22:%20100.0,%20%22field1%22:%20100.0,%20%22field2%22:%200.0%7D%7D,%20%7B%22type%22:%20%22Feature%22,%20%22geometry%22:%20%7B%22type%22:%20%22Point%22,%20%22coordinates%22:%20[48.346426,%2016.494564]%7D,%20%22properties%22:%20%7B%22id%22:%20200.0,%20%22field1%22:%20200.0,%20%22field2%22:%200.0%7D%7D]%7D

enter image description here

相关问题