Skip to content

Instantly share code, notes, and snippets.

@DeepanshKhurana
Last active February 10, 2019 14:34
Show Gist options
  • Save DeepanshKhurana/76665bedaee5ee0722343c118a43e291 to your computer and use it in GitHub Desktop.
Save DeepanshKhurana/76665bedaee5ee0722343c118a43e291 to your computer and use it in GitHub Desktop.
A simple function that uses plyr and ggmap along with the Google Maps API to fetch a dataframe of City, Location, State and Country
# @dependency ggmap for the geocode function
# @dependency plyr for ldply
#
#
# @param lat - The latitude value or column using $ notation
# @param long - The longitude value or column using $ notation
# @param api.key - Your Google Geocoding API key.
# You'll need to get one here: https://developers.google.com/maps/documentation/geocoding/start
# The Geocoding API requires you to sign up with payment details. You may get charged for using it in huge volumes.
# Please refer to the official documentation provided by Google on their pages.
#
#
# @return dataframe with four columns namely, CITY, STATE, COUNTRY, PINCODE
#
reverse.geolocate <- function(lat, long, api.key) {
require(ggmap)
require(plyr)
register_google(key = api.key)
result <- lapply(paste(lat, long, sep = ","), geocode, output = "more")
columns <- c(15:18)
geo.data <- (ldply(result, data.frame))[, columns]
colnames(geo.data) <- c("CITY", "STATE", "COUNTRY", "PINCODE")
return(geo.data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment