Developing the Plot

Preparing to Add Points to Our Map

To use the PBSmapping’s addPoints function, the reference manual suggests we treat our foreclosures as "EventData“. The EventData format is a standard R data frame (more on data frames below) with required columns X, Y, and a unique row identifier EID. With this in mind we can write a function around our geocoding code that will accept a list of streets and return a kosher EventData-like dataframe.

  #input:vector of streets
  #output:data frame containing lat/longs in PBSmapping-like format
  > geocodeAddresses<-function(myStreets){
      'appid<-'<put your appid here>'
       myGeoTable<-data.frame( 
       address=character(),lat=numeric(),long=numeric(),EID=numeric())
    for(myStreet in myStreets){
      requestUrl<-paste(
      "http://local.yahooapis.com/MapsService/V1/geocode?appid=",
      appid,
      "&street=",URLencode(myStreet),
      "&city=Philadelphia&state=PA",sep="")
      cat("geocoding:",myStreet,"\n")
      tryCatch({
        xmlResult<-
          xmlTreeParse(requestUrl,isURL=TRUE,addAttributeNamespaces=TRUE)
        geoResult<-xmlResult$doc$children$ResultSet$children$Result
        if(geoResult$attributes['precision'] == 'address'){
          lat<-xmlValue(geoResult[['Latitude']])
          long<-xmlValue(geoResult[['Longitude']])
          myGeoTable<-rbind(myGeoTable,
            data.frame(address = myStreet, Y = lat, X  =
            long,EID=NA))
        }
      }, error=function(err){
        cat("xml parsing/http error:", conditionMessage(err), "\n")
      })
      Sys.sleep(0.5) #this pause helps keep Yahoo happy
    }
 #use built-in numbering as the event id for ...

Get Data Mashups in R now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.