# Create a graph from KML file

I'm wondering how I can take a .KML (Keyhole Markup Language) file and convert/express it as a graph for use in Mathematica. Even just in general, is it possible to convert a KML file to a graph?

I'm hoping to express the US railroad system in the 19th century as a graph using this data:

• You could try a KML to CSV converter. CSV can be imported in Mathematica. Jan 17 '14 at 6:56
• Maybe this can help blog.wolfram.com/2009/04/17/mapping-gps-data Jan 17 '14 at 7:05
• That blog uses gpx not kml. Jan 17 '14 at 7:34
• Well then he can do this first kml2gpx.com Jan 17 '14 at 7:42
• I'm sure you're aware MM supports KML as an import (and export) format. To turn an imported file into a graph (I'll assume you mean in the topological sense) you'll need to pull the appropriate attributes from the import and parse them into data that can be used with the MM graph functions. MM does not intrinsically have conversion from KML to graph format.
– ciao
Jan 17 '14 at 8:45

using the KML to CSV converter converted the file South_Depots.kml from the site http://railroads.unl.edu/resources/ to CVS file. Then inside Mathematica, loaded the data and first drew on the US map

SetDirectory[NotebookDirectory[]];
FileNames["*.csv"] trainCoord = Import["South_Depots.csv"];
trainCoord = trainCoord[[All, {1, 2}]]; (*only need first 2 columns *)
trainCoord[[All, {1, 2}]] = trainCoord[[All, {2, 1}]]; (*swap coordinates*)
trainCoordGeo = Map[GeoGridPosition[GeoPosition[#], "Mercator"][] &,
{trainCoord}, {2}][];  (*make it GEO*)

UScoords = CountryData["UnitedStates", "Coordinates"];
UScoordsGeo = Map[GeoGridPosition[GeoPosition[#], "Mercator"][] &,
{UScoords}, {2}][]; (*make it GEO*)

Graphics[
{
{Gray, Polygon[UScoordsGeo]},
{Red, PointSize[.005], Point[trainCoordGeo]}
}] To convert the data to Mathematica graph data, one way is

SetDirectory[NotebookDirectory[]];
trainCoord = Import["South_Depots.csv"];
trainCoord = trainCoord[[All, {1, 2}]];
Needs["GraphUtilities"];
g = Rule @@@ trainCoord[[1 ;; 20]];
coords = GraphCoordinates[g] now that you have the CVS data, you can do any other graph operations you want on it inside Mathematica.

Update: I just saw Rasher comment above that M supports reading KML. Yes, I just tried it

   trainCoord = Import["South_Depots.kml"];


This can be another option to read the data. It seems to be graphic data. • By default it returns graphics, yes, but take a look at Import["file","Elements"] and specifically Import["file","Data"]`. Jan 17 '14 at 14:55
• Thank you very much for your answer. I've successfully repeated your steps. My problem now is that the vertices don't have edges connecting them. But why would they? I've only given the graph unconnected points, correct? Jan 18 '14 at 0:29
• @RobertMogel: KML are not obligated to have paths (routes). If they don't, you're probably out of luck, unless you have some other data to associate points to paths.
– ciao
Jan 18 '14 at 1:05