How to convert CSV data to geoJSON

A few weeks ago I posted about some things I’ve been reading on how to incorporate data on a map for the web using open-source OpenLayers. While other work has kept me away from making substantial progess on the maps, I have made some steps towards converting data into geoJSON format for use in these types of web applications. The solution I have isn’t exactly elegant since it is very specific one dataset but it works and should be adaptable.

I’m new to using github for code but I have posted the code for this script up there to share with whoever can make something useful of it. You can download the Python script to convert CSV (with lat/long coordinates) to geoJSON or clone the .git repository.

Below I post the body of the Python script for comments if anyone should pass this way with suggestions for improvements.

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()

Comments on this article can be sent to me by e-mail..

2 Responses to “How to convert CSV data to geoJSON”

  1. sha writes:

    awesome! this would be awesome as a web tool.

    though, just reading over this, do you have lon and lat flipped?

  2. Andrew writes:

    Yup, you’re right sha. Thanks for pointing that out and I’ve changed the post to reflect the correction.

    A web tool would be great but I suspect the audience would be quite limited. Those who have regular need for this probably use things like GDAL or some other technology. That said, there are a number of good tools like Google Refine that will likely include the geoJSON format soon enough.