Last active
May 5, 2016 15:58
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: