Skip to content

Plotting shapefiles on top of Google map tiles

6 messages · Patrick Crutcher, Robert J. Hijmans, milton ruser +1 more

1 day later
#
Patrick,

I have had some success with plotting sp objects on top of G maps with
this function


gmap <- function(xy, maptype='terrain', ...) {
    require(RgoogleMaps)
	fun = points
	if (inherits(xy, 'Spatial')) {
		b = bbox(xy)
		if (inherits(xy, 'SpatialPoints')) {
			xy = coordinates(xy)
		} else {
			x = unlist(lapply(xy at polygons, function(i)slot(i, 'Polygons')))
			x = lapply(x, function(x)slot(x, 'coords'))
			xy = matrix(ncol=2, nr=0)
			for (i in 1:length(x)) xy = rbind(xy, x[[i]], c(NA,NA))
			fun = lines
		}
	} else {
		b = rbind(range(xy[,1], na.rm=TRUE), range(xy[,2], na.rm=TRUE))
	}
	mykey <-  ### fill in your google maps API key for http://localhost/
    gm <- GetMap.bbox(key=localhostkey, lonR=b[1,], latR=b[2,], maptype=maptype)
    tmp <- PlotOnStaticMap(gm, lon=xy[,1], lat=xy[,2], FUN=fun, verbose=0, ... )
}


a = matrix(runif(100)*100-50, ncol=2)
gmap(a)

library(sp)
gmap(SpatialPoints(a), col='red', cex=2, pch='+')

library(maptools)
data(wrld_simpl)
hti = wrld_simpl[wrld_simpl$ISO3=='HTI',]
gmap(hti, lwd=2, col='red')


Hth,
Robert
On Sat, Jan 16, 2010 at 5:35 PM, Patrick Crutcher <pcrutcher at gmail.com> wrote:
#
Dear Milton,

You need a Google maps API key for this. If you have a Google account,
you can request one for http://localhost/
at http://code.google.com/apis/maps/signup.html

I have made this more explicit by adding a mykey argument to the function:

gmap <- function(xy, maptype='terrain', mykey, ...) {
    require(RgoogleMaps)
	fun = points
	if (inherits(xy, 'Spatial')) {
		b = bbox(xy)
		if (inherits(xy, 'SpatialPoints')) {
			xy = coordinates(xy)
		} else {
			x = unlist(lapply(xy at polygons, function(i)slot(i, 'Polygons')))
			x = lapply(x, function(x)slot(x, 'coords'))
			xy = matrix(ncol=2, nr=0)
			for (i in 1:length(x)) xy = rbind(xy, x[[i]], c(NA,NA))
			fun = lines
		}
	} else {
		b = rbind(range(xy[,1], na.rm=TRUE), range(xy[,2], na.rm=TRUE))
	}
    gm <- GetMap.bbox(key=mykey, lonR=b[1,], latR=b[2,], maptype=maptype)
    tmp <- PlotOnStaticMap(gm, lon=xy[,1], lat=xy[,2], FUN=fun, verbose=0, ... )
}


Robert
On Sun, Jan 17, 2010 at 11:37 PM, milton ruser <milton.ruser at gmail.com> wrote:
#
On Mon, Jan 18, 2010 at 8:23 AM, milton ruser <milton.ruser at gmail.com> wrote:
To put data onto Google Earth then you need to make a KML file. You
can probably do this with writeOGR from the rgdal package, or the kml*
functions in maptools - but if you want to do anything fancy then you
need to write your own KML file from your data. I have found the
'brewer' package useful for writing templates to make KML files.

 You'll have to study the KML specification from Google as well.

Barry