3

I'm looking for demographic information and various things, and most of the time data are available as CSV (my application use geoJSON format).

Shall I encode the CSV to geoJSON or is there a "library" for geoJSON or some kind of a database of geojson files ?

2

2 Answers 2

4

If you use python, you can handle csv file for generating geojson from it....

the basic way:

import csv, json

file = open( 'test.csv', 'r' )
reader = csv.DictReader( file , fieldnames = ( "id","name","attribute","lat","lng" ) )
outfile = json.dumps( [ row for row in reader ] )

print outfile

out = open("output.txt", "w")
out.write(outfile) 
out.close()

the other way is from Andrew Dyck here with using geojson template which u created:

import csv

# Read in raw data from csv
rawData = csv.reader(open('sample.csv', 'rb'), dialect='excel')

# the template. where data from the csv will be formatted to geojson
template = \
    ''' \
    { "type" : "Feature",
        "id" : %s,
            "geometry" : {
                "type" : "Point",
                "coordinates" : ["%s","%s"]},
        "properties" : { "name" : "%s", "value" : "%s"}
        },
    '''

# the head of the geojson file
output = \
    ''' \
{ "type" : "Feature Collection",
    {"features" : [
    '''

# loop through the csv by row skipping the first
iter = 0
for row in rawData:
    iter += 1
    if iter >= 2:
        id = row[0]
        lat = row[1]
        lon = row[2]
        name = row[3]
        pop = row[4]
        output += template % (row[0], row[2], row[1], row[3], row[4])

# the tail of the geojson file
output += \
    ''' \
    ]
}
    '''

# opens an geoJSON file to write the output to
outFileHandle = open("output.geojson", "w")
outFileHandle.write(output)
outFileHandle.close()
1
  • 1
    there is also a geojson specific python library in addition to the json library. Commented Jun 13, 2012 at 16:13
2

If you're only concerned with point data, Aragon's example is perfect. For more complex shapes you will need a bit more.

You can use ogr2ogr to convert nearly any type of data to geoJSON. I would employ some quality checks before relying on the conversion.

ogr2ogr -f geoJSON out.json in.shp

If you're more comfortable with a GUI, qGIS uses the same methods but it's easier to view / modify your process. qGIS can also help you import data from a CSV.

2
  • I briefly used qGIS in the past but didn't realize it could convert shapefile/csv to geoJson ! I'll give a try to ogr2ogr.
    – Olivier
    Commented Jun 15, 2012 at 11:53
  • I haven't used it in a while, but I think its in the file types under File > Save As.
    – nagytech
    Commented Jun 15, 2012 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.