Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Script to Convert CSV to GeoJSON

I am needing a Python script to convert CSV data to GeoJSON output. The output should match the format, below:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates":  [ -85.362709,40.466442 ]
      },
      "properties": {
        "weather":"Overcast",
        "temp":"30.2 F"
      }
    }
  ]
}

I am using this script to run the process, but it does not produce the desired output:

import csv, json
    li = []
    with open('CurrentObs.csv', newline='') as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        for latitude, longitude, weather, temp in reader:
            li.append({
               "latitude": latitude,
               "longitude": longitude,
               "weather": weather,
               "temp": temp,
               "geo": {
                    "__type": "GeoPoint",
                    "latitude": latitude,
                    "longitude": longitude,
                }
            })

    with open("GeoObs.json", "w") as f:
        json.dump(li, f)

Any help is greatly appreciated!

like image 523
user5834454 Avatar asked Feb 02 '18 16:02

user5834454


2 Answers

one could use directly the geojson package:

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

features = []
with open('CurrentObs.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for latitude, longitude, weather, temp in reader:
        latitude, longitude = map(float, (latitude, longitude))
        features.append(
            Feature(
                geometry = Point((longitude, latitude)),
                properties = {
                    'weather': weather,
                    'temp': temp
                }
            )
        )

collection = FeatureCollection(features)
with open("GeoObs.json", "w") as f:
    f.write('%s' % collection)
like image 122
ewcz Avatar answered Oct 11 '22 07:10

ewcz


Check if this script resolves

import csv
import json
from collections import OrderedDict

li = []
with open('CurrentObs.csv', 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for latitude, longitude, weather, temp in reader:
        d = OrderedDict()
        d['type'] = 'Feature'
        d['geometry'] = {
            'type': 'Point',
            'coordinates': [float(latitude), float(longitude)]
        }
        d['properties'] = {
            'weather': weather,
            'temp': temp
        }
        li.append(d)

d = OrderedDict()
d['type'] = 'FeatureCollection'
d['features'] = li
with open('GeoObs.json', 'w') as f:
    f.write(json.dumps(d, sort_keys=False, indent=4))
like image 40
wallace manzano Avatar answered Oct 11 '22 06:10

wallace manzano