## ----setup,include=FALSE-------------------------------------------------

library('knitr')
library('mapmisc')

fact = 0.5
reRun = FALSE

# uncomment for nicer images
# fact = 1 
# reRun = TRUE

opts_chunk$set(dpi=72*fact,dev.args=list(bg='white'), out.width='200')	

theNames = names(osmTiles())
africaExtent = c(25, 25)
trafalgarSquare=c(-0.128056,51.508056)
stjohns=c(-52.62, 47.53)


## ----downloadTiles,include=FALSE-----------------------------------------

if(reRun) {

  africaTiles = openmap(africaExtent, path=theNames,zoom=2,
    verbose=TRUE, 
    crs = crsMerc, 
    fact=fact)

  londonTiles = openmap(trafalgarSquare,zoom=12,path=theNames,
    verbose=TRUE, 
    crs = crsMerc, 
    fact=fact)

  nfTiles = openmap(stjohns, zoom=14, path=theNames,,
    verbose=TRUE, 
    crs = crsMerc, 
    fact=fact)

  # save the data
  if(FALSE) {
    # make sure all data is stored in memory not on disk
    # so that caching will work
    for(D in names(africaTiles))
	  values(africaTiles[[D]]) = values(africaTiles[[D]])
    for(D in names(londonTiles))
	  values(londonTiles[[D]]) = values(londonTiles[[D]])
    for(D in names(nfTiles))
	  values(nfTiles[[D]]) = values(nfTiles[[D]])

    save(africaTiles, londonTiles, nfTiles,
			file="../inst/extdata/tiles.RData",
			compress="xz")
  }

} else { # don't rerun
  load(system.file("extdata", "tiles.RData", package = "mapmisc"))
}

## ----someTiles, echo=FALSE, results='asis', fig.height=3, fig.width=3----


mytiles = list(africaTiles, londonTiles, nfTiles)

for(D in theNames){
	Dsub = gsub("-",".", D)

	threeTiles = length(
			grep(
				paste("^", Dsub, "([rR]ed|[gG]reen|[bB]lue)$", sep=""), 
				names(mytiles[[1]])
			)
		) == 3
	
	cat("\n\n# ", D, "\n\n")
	cat("`plot", "RGB"[threeTiles], 
		"(openmap(x,path=\"", D, "\"))`\n\n", 
	    sep='')
  	cat(openmapAttribution(D, 'html'), '\n\n')
	
	cat("\n|     |     |     |\n|-----|-----|-----|\n")
	for(Dplot in 1:length(mytiles)) {
	cat("|")

		oneTileName = grep(paste("^", Dsub, "$", sep=""), 
				names(mytiles[[Dplot]]), value=TRUE)
		threeTilesName = grep(paste("^", Dsub, 
						"([rR]ed|[gG]reen|[bB]lue)$", sep=""), 
				names(mytiles[[Dplot]]),value=TRUE)

		if(length(threeTilesName)==3) { # plotRGB
			map.new(mytiles[[Dplot]])
			
			plotRGB(mytiles[[Dplot]][[
								paste(Dsub, c("Red","Green","Blue"),sep="")
								]],add=TRUE)
	
		} else if (length(oneTileName)==1){
		
			map.new(mytiles[[Dplot]])
			plot(mytiles[[Dplot]][[oneTileName]],add=TRUE)

		} else {

			plot(0.5, 0.8)
			text(0.5, 0.8, paste(D, "is\n not currently\navailable"))
		
		}

	}
	cat("|")
	
}


