0

I am trying to take data from a raster and push it to KML format so that I get a series of gridded polygons.

Looking at samples on the web it would appear that the way to go is to using grid2poly with plotKML. Unfortunately I have hit an error that I can seem to unblock.

library(dismo)
require(plotKML)

library(rgdal)

tmin <- getData("worldclim", var = "tmin", res = 10)  # this will download 
# global data on minimum temperature at 10' resolution

tmin1 <- raster(paste(getwd(), "/wc10/tmin1.bil", sep = ""))  # Tmin for     January

newext <- c(-1, 1, 40, 43.5)
tmin1.c <- crop(tmin1, newext)
plot(tmin1.c)

tmin1.c  # look at the info
head(tmin1.c,5)

tminvals <- rasterToPoints(tmin1.c)

tminvals # look at the info
head(tminvals,5)
str(tminvals)

###########################
#Everything works down to here
###########################

library(sp)
coordinates(tminvals) <- ~x+y
gridded(tminvals) <- TRUE

proj4string(tminvals) <- CRS("+proj=longlat +datum=WGS84")
data(SAGA_pal)

dem_poly <- grid2poly(tminvals, "tmin1", method = "sp")

## visualize the data in Google Earth:
kml(dem_poly, colour_scale = SAGA_pal[[1]], colour = tmin1, kmz = TRUE)

I get an error for all the lines from coordinates(tminvals) <- ~x+y which looks like this:

From Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘coordinates<-’ for signature ‘"matrix"’

I don't understand what I am doing wrong. When I look at the dataset tminvals It looks much the same in content as the original example data eberg_grid.

989
  • 12,579
  • 5
  • 31
  • 53
SteveG
  • 99
  • 1
  • 11

1 Answers1

1

Why polygons and not a raster KML?

library(raster)
tmin <- getData("worldclim", var = "tmin", res = 10) 
tmin1 <- tmin[[1]]
newext <- c(-1, 1, 40, 43.5)
tmin1.c <- crop(tmin1, newext)

KML(tmin.c, 'test.kml')

If you need polygons:

p <- rasterToPolygons(tmin.c)

and now you can use KML (or kml) again

Now to explain the error message you are getting. The coordinates function expects a data.frame, you are giving it a matrix. It will probably go away if you do this:

tminvals <- data.frame(tminvals)
coordinates(tminvals) <- ~x+y
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
  • You suggestions worked - many thanks. I want to use polygons to introduce some exagguration in the vertical scale. The problem is that even when I have _plotKML(tminvals, altitude=5000+tmin1*100, tessellate= TRUE, extrude= TRUE)_ in the kml file itself the is set to 'clampedtoground'. I can use a text editor to chnage this to absolute but I really want to do it all from R . – SteveG Mar 09 '15 at 10:17
  • I just discovered the alpha, altitude and altitudeMode parameters! – SteveG Mar 10 '15 at 08:59