[R-sig-Geo] maptools/kmlPolygon example: two SPDFs, different results

Robert J. Hijmans r.hijmans at gmail.com
Thu Aug 27 19:06:28 CEST 2009


Rick, I had the same problem. Perhaps I simply misunderstood the
maptools function. I wrote the script below and that worked for me (it
includes all polygons). It probably has some limitations. Robert


polykml <- function(sw, filename, kmlname, namefield, kmldesc="Made with R" ) {
	out <- sapply(slot(sw, "polygons"),
		function(x) {
			kmlPolygon(x,  name=as(sw, "data.frame")[slot(x, "ID"), namefield],
				col="#df0000aa", lwd=1.5, border='black', description=as(sw,
"data.frame")[slot(x, "ID"), desc] )
		}
	)
	kmlFile <- file(filename, "w")
	cat(kmlPolygon(kmlname=kmlname, kmldescription=kmldesc)$header,
file=kmlFile, sep="\n")
	cat(unlist(out["style",]), file=kmlFile, sep="\n")
	cat(unlist(out["content",]), file=kmlFile, sep="\n")
	cat(kmlPolygon()$footer, file=kmlFile, sep="\n")
	close(kmlFile)
# optional, to make a kmz, I do not know how to make this generic for
all systems
#	kmz <- basename(filename)
# change file extension, from raster package	
#	ext(kmz) <- '.kmz'
#	com <- paste("7za a -tzip", kmz, " ", fn, sep="")
#	sss <- system(com, intern=TRUE)
	return(TRUE)
}


On Thu, Aug 27, 2009 at 9:27 AM, rick reeves<reeves at nceas.ucsb.edu> wrote:
> Hello List:
>
> I'm using R 2.9 on Windows XP/64 for this example, with recent builds of
> maptools and rgdal packages.
>
> The shape file used in this example can be obtained from:
>
> http://nceas.ucsb.edu/scicomp/upload/UsCountiesGeogProj.zip
>
> While studying the example for kmlPolygon() in the maptools.pdf
> documentation (pp 22  - 23), I ran the
> example code (top of page 23), using the wrld_simpl data set, and used
> slot() to extract a subset of the
> Polygons component of the sample data set, then create a KML file using
> kmlPolygon. The example
> worked as planned with the indicated data set.
>
> Then, I read the attached polygon shape file using readOGR, into a
> SpatialPolygonsDataFrame, and
> substituted this dataset for the wrld_simpl data set. In this case, the
> slot() statement returned ONLY
> the FIRST polygon from the SPDF. As a result, the resulting KML file
> contains only one polygon,
> instead of the entire set.
>
> I have reviewed the structure of each SPDF, using 'str(MySPDF[1:3,])', and
> the data objects seem
> to have the same structure. Yet the 'one polygon' problem persists. I would
> appreciate it if someone
> could repeat the experiment with the attached data set and let me know where
> I might be mistaken!
>
> Thanks,
> Rick Reeves
>
> --
> Rick Reeves
> Scientific Programmer/Analyst and Data Manager
> National Center for Ecological Analysis and Synthesis
> UC Santa Barbara
> www.nceas.ucsb.edu
> 805 892 2533
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at stat.math.ethz.ch
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>



More information about the R-sig-Geo mailing list