Skip to content

Instantly share code, notes, and snippets.

@arvi1000
Last active May 5, 2016 15:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arvi1000/a67c0bf9b5ae2a32b8f5 to your computer and use it in GitHub Desktop.
Save arvi1000/a67c0bf9b5ae2a32b8f5 to your computer and use it in GitHub Desktop.
Example of reading data from an Excel file, geocoding, simple calculations, and plotting with Leaflet
library(leaflet)
library(readxl) # for read_excel()
library(ggmap) # for geocode()
library(fields) # for rdist.earth()
### read data from excel ----
# download to default working directory
download.file('https://dl.dropboxusercontent.com/u/12146012/place_names.xlsx',
destfile='place_names.xlsx')
places <- read_excel('place_names.xlsx')
# file looks like this:
# city state color
# Calgary AB red
# Banff AB red
# Whitefish MT red
# Oakland CA blue
# San Luis Obispo CA blue
# Brooklyn NY green
# Philadelphia NJ green
# Cape May NJ green
### geocode ----
coords <- geocode(paste0(places$city, ', ', places$state))
places <- cbind(places, coords)
### calculate center & radius for 'green' group ----
green_places <- subset(places, color=='green')
# center: mid point of lat/lon ranges
green_center <- with(green_places, c(mean(range(lon)), mean(range(lat))))
# each point's distance from the center (in meters)
green_dist_from_center <-
rdist.earth(t(green_center), green_places[, c('lon', 'lat')],
miles = FALSE) * 1000
# add to map ----
my_map <- leaflet() %>%
addTiles() %>%
addCircleMarkers(data=places, lng= ~lon, lat= ~lat, popup= ~city, color= ~color) %>%
addCircles(lng = green_center[1], lat = green_center[2],
# radius = 2x center to most distant point
radius = max(green_dist_from_center * 2),
weight = 1, color='green', fill = 0)
# my_map can be seen in RStudio viewer, or embedded in html via RMarkdown
# screen shot of output: http://i.imgur.com/9pCG07y.png
@arvi1000
Copy link
Author

arvi1000 commented May 5, 2016

Result:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment