Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am using R and the package ggmap to try and generate some random points within the city limits of Chapel Hill, NC. I have downloaded the shapefile for the town of Chapel Hill from the Orange County website: The city limits for Chapel Hill and several other nearby cities are in the file labeled I saved this file to my hard drive and unzipped it. My code is as follows:


map1 <- get_map(location='Chapel Hill, NC', zoom=12, maptype='roadmap')

setwd('<Path to unzipped files>')
city <- readOGR('city.shp','city') <- city[city$CITYCODE == "CH",] # Take only the part of the shapefile we need (the area around Chapel Hill)
city1 <- spTransform(, CRS('+proj=longlat +ellps=WGS84'))

If I simply plot city1 the polygon looks as it should:


but if I try to plot it over my street map of Chapel Hill, I get some weird tearing in the northwest part of the city:

  geom_polygon(data=city1, aes(x=long, y=lat), color='blue', fill='blue', alpha=.3)

Why is this and how could I fix it?

The second thing I want to do is generate some random points within this polygon. The package splancs claims to do this with its csr() function, but so far I cannot get this to work.

poly1pl <- coordinates(city1) # Extracts long and lat into a matrix
randpoints <- data.frame(csr(poly1pl, 20)) 

The last command of this gives me an error: Error in runif(ngen) : invalid arguments I get the same error if I try using csr() on as well, so the error is not a result of using spTransform. What does this error mean and how can I get this to work? Or is there an easier way to generate these points?

share|improve this question
The reason for the error is that you cannot extract polygon vertices coordinates using the "coordinate" function. This results in an invalid object being passed to csr. – Jeffrey Evans Feb 11 '13 at 21:37

You have two questions here and should consider two separate posts. As to your second question on generating random points. There is no need to use splancs. The rgdal library depends on sp and readOGR results in an sp object. As such, you can use the "spsample" function, without coercion, to generate a set of random points within an sp polygon class object.

randpoints <- spsample(city1, n=20, type="random")
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.