Convert Mission Planner polygon to kml

This R-script converts a exported polygon (*.poly) from Mission Planner to kml (or any other format supported by rgdal). It is easy to read code and feel free to modify it for your own purpose.

[code lang=”r” wraplines=”TRUE”]
library(sp)
library(rgdal)

# All files in this directory and all subfolders with file ending .poly will be converted to kml.
# It is assumed that the .poly file has a comment lines using #.
# Coordinates of the polygon are in Lat Long and in WGS84 format. Space as separator
setwd("D:\\foldername\\subfolder")

lof <- list.files(path=".", recursive=T, pattern=".\\.poly")

for (i in 1:length(lof)) {
dir <- dirname(lof[i])
fname <- basename(lof[i])
fnameWithoutEnding <- strsplit(fname, "\\.")[[1]][1]

loc <- read.csv(file=lof[i], header=F, sep=" ", comment.char="#")
p <- Polygon(coords=cbind(loc$V2, loc$V1))
ps <- Polygons(srl=list(p), ID = fnameWithoutEnding)
ps_sp <- SpatialPolygons(list(ps), proj4string=CRS("+proj=longlat +datum=WGS84"))
ps_spdf <- SpatialPolygonsDataFrame(ps_sp, data=data.frame("name"=fnameWithoutEnding, row.names = fnameWithoutEnding))
writeOGR(obj = ps_spdf, dsn=paste0(dir, "/", fnameWithoutEnding, ".kml"), driver = "KML", overwrite_layer = T, layer = fnameWithoutEnding)
}

[/code]