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.
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
Now, let’s add the necessary simplekml bits:
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 refers to “Charleston County, SC”, and row 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,row)] 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.