简体   繁体   English

从文本文件中读取逗号分隔值并使用 python 创建 geoJson 文件

[英]Read comma separated values from a text file and create a geoJson file using python

I am currently working on a Google Maps project.我目前正在做一个谷歌地图项目。 Here I would like to collect coordinates (multiple points/polygon) from users and extract those values and dynamically create a new geoJson file which I can then append to the primary geoJson file which loads on my map.在这里,我想从用户那里收集坐标(多个点/多边形)并提取这些值并动态创建一个新的 geoJson 文件,然后我可以将 append 到加载到我的 map 上的主要 geoJson 文件中。

For example, a user uploads a file (contents below):例如,用户上传文件(内容如下):

latitude, longitude
30.095319, -95.993581
30.096340, -95.993399
30.096015, -95.991854
30.095040, -95.992219

I want to be able to extract these coordinates and create the geoJson file below:我希望能够提取这些坐标并在下面创建 geoJson 文件:

{
    "type": "Feature",
    "geometry": {
        "type": "Polygon",
        "coordinates": [
            [
                [
                    -95.972251,
                    30.091505,
                    0
                ],
                [
                    -95.970337,
                    30.091318,
                    0
                ],
                [
                    -95.970973,
                    30.092492,
                    0
                ],
                [
                    -95.972136,
                    30.09262,
                    0
                ]
            ]
        ]
    }
}

read the csv with csv , turn the rows into the list of lists that you want, build a python dictionary with all the fields that you want and put the list of lists where it needs to be, then write the dictionary out as JSON with json read the csv with csv , turn the rows into the list of lists that you want, build a python dictionary with all the fields that you want and put the list of lists where it needs to be, then write the dictionary out as JSON with json

import csv
import json

with open("path/to/the/uploaded/file.csv") as f:
    reader = csv.DictReader(f)
    coordinates = []
    for row in reader:
        coordinates.append([row["longitude"], row["latitude"], 0])

geo_json = {"type": "Feature", "geometry": {"type": "Polygon", "coordinates": []}}

geo_json["geometry"]["coordinates"].append(coordinates)

with open("path/where/you/want/to/save/to.json", "w") as f:
    json.dump(geo_json, f, indent=4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM