I've created a list of lat long coordinates that represent the perimeter of a location. I wish to plot this polygon as a line in Google Earth rather than as push pins.

I have the XML/KML file format for plotting the polygon in Google Earth but is it possible to script this in R to populate this particular field in the KML file?

  • 2
    Convert to SpatialLinesDataFrame with the sp package, then write with e.g. rgdal::writeOGR(x, "file.kml", "file", "KML") – mdsumner Oct 26 '16 at 11:52

Yes, definitely possible.

Assuming your [LongLat.csv] has longitude (lon), latitude (lat), and elevation (z) columns.

MyData <- format(read.csv("LongLat.csv", header = FALSE), nsmall = 5)
colnames(MyData) <- c("lon", "lat", "z")

MyData$lon_lat_z <- paste0(MyData$lon, ", ", MyData$lat, ", ", MyData$z)
paste(unname(unlist(MyData$lon_lat_z)), collapse = " ")

Then you can copy the output from your R console, and paste it into your [coordinates] tags.

  • Hi Kazuhito, thanks for the reply. Ideally I wish to drop my calculated coordinates into my KML template.Since I have >3000 rows of coordinate data to plot, so pasting into my coordinate tags for all this data is too much. In R can you specify what tags R outputs? – TheGoat Oct 31 '16 at 22:50
  • Hi PigWolf, so many points... To enable your R output coordinates along with all necessary tags, you can set it up by {XML} package. I am not skilled in it, so cannot add any meaningful comment. Hopefully it gives you a start. However (if I may) I would suggest alternative approaches. (following Plan B, C, and D) PLAN (B): (1) Group your points into several sub-groups of <1000 points, according to your polygons, and create kml per each group. Then (2) Load these kml files into a GE folder, and save as new place (kml/kmz). (This does not work if all your points belong to single polygon). – Kazuhito Nov 1 '16 at 9:49
  • PLAN (C): (1) Please ignore my code and try writeOGR() as mdsumner's comment. Then (2) Open the output kml by any text editor, and replace the format with yours. Given your data volume, the other part (ie except for [coordinates]tag ) would be relatively easier to handle. I think this PLAN (C) is great time-saver. PLAN (D) is similar to Plan (C), but using kmlPolygon() of {maptools} package can give you more ability to control kml styles, such as color and descriptive comments. Hopefully any of these options works for you. – Kazuhito Nov 1 '16 at 9:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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