我开始使用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",
答案 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)