Create a KML file with Python

If you want a quick and dirty way to visualize datapoints on a map, python makes it easy to create a KML file that you can overlay on a map embedded on a webpage or on Google Earth.

Let’s say you’ve extracted placenames from somwhere, and geocoded them, and now have a file that looks like:

'Charleston County, SC',32.7956561,-79.7848422
'Norfolk City, VA',36.8507689,-76.2858726
'Stafford County, VA',38.4334566,-77.4242972
'Barbour County, WV',39.1398692,-80.0087746
'York County, VA',37.2103925,-76.3868797

Using the python simplekml module makes creating a KML file of these points unfairly easy.

If you haven’t already, you’ll first need to get the simplekml module.

There are really only three crucial lines of code needed to use simplekml. 1) Create a simplekml object; 2) Add points to it; 3) Write the object to a file.

Let’s start by reading the lines of our CSV file in our usual way

import csv

inputfile = csv.reader(open('geocoded-placenames.csv','r'))

for row in inputfile:
  #do something

Now, let’s add the necessary simplekml bits:

import csv
import simplekml

inputfile = csv.reader(open('geocoded-placenames.csv','r'))

for row in inputfile:
  kml.newpoint(name=row[0], coords=[(row[2],row[1])])'battleplaces.kml')

The simplekml newpoint method requires that we send it a NAME and a COORDS, each of which we can easily pull directly from the CSV file that we’ve opened via our csv reader. Because csv.reader returns a list, we can access elements of that list by their numerical index. For the first row of our CSV file, row[0] refers to “Charleston County, SC”, and row[1] refers to 32.7956561.

We saved our coordinates as lat,long but simplekml wants them in the reverse order (long, lat), which is why we need to create the list like [(row[2],row[1])] as seen above.

So for each row in our CSV file, we create new point via the newpoint method of the kml object. Once we’ve finished with the file, we just need to call the save method on the kml object, and it will create a perfect KML file (‘battleplaces.kml’) for us.