Skip to content

Instantly share code, notes, and snippets.

@dylanpieper
Last active July 15, 2022 22:03
Show Gist options
  • Save dylanpieper/47682656cdf80674a61127f985e27b61 to your computer and use it in GitHub Desktop.
Save dylanpieper/47682656cdf80674a61127f985e27b61 to your computer and use it in GitHub Desktop.
Convert latitude and longitude to county fips code and create a leaflet map
# Convert latitude and longitude to county FIPS code from a survey and create a leaflet map
# Load your survey and define the lat/long variables as numeric
survey <- tibble::tribble(
~Latitude, ~Longitude, ~Name,
44.617000, -92.556600, "<b>Hagar City, WI</b> </br> Trenton Bluff Prairie </br> Ridge Soaring </br> S to SW </br> P2",
43.256443, -89.789153, "<b>Sauk City, WI</b> </br> Towing </br> E or W </br> P2",
43.036036, -89.502803, "<b>Madison, WI</b> </br> Elver Park </br> Training Hill </br> NNE to NNW </br> P1",
44.9369, -91.3929, "<b>Chippewa Falls, WI</b> </br> Home"
)
survey$Latitude <- as.numeric(survey$Latitude)
survey$Longitude <- as.numeric(survey$Longitude)
# Define a function to use lat/long variables to get the FIPS code data from the FCC's census using JSON
geo2fips <- function(latitude, longitude) {
res <- jsonlite::fromJSON(sprintf("https://geo.fcc.gov/api/census/area?lat=%f&lon=%f&format=json",
latitude, longitude))[["results"]][["county_fips"]]
unique(res)
}
# Apply the function to each row of the dataframe (this may take awhile if you have a large dataset)
survey$fips <- mapply(geo2fips, survey$Latitude, survey$Longitude)
# Create the leaflet map with the county polgygons, population percentiles, and location markers
tracts <- tigris::tracts(state = 'WI', cb=TRUE)
fetched <- tidycensus::get_acs(geography = "county",
variables = "B01003_001",
state = "WI",
geometry = TRUE,
key = "XXX") # Insert your API key here (https://api.census.gov/data/key_signup.html)
pal <- leaflet::colorQuantile(palette = "viridis", domain = fetched$estimate, n = 5)
fetched %>%
sf::st_transform(crs = "+init=epsg:4326") %>%
leaflet::leaflet(width = "100%") %>%
leaflet::addProviderTiles(provider = "CartoDB.Positron") %>%
leaflet::addProviderTiles(leaflet::providers$OpenTopoMap, group='Topo') %>%
leaflet::addPolygons(popup = ~ stringr::str_extract(NAME, "^([^,]*)"),
stroke = FALSE,
smoothFactor = 0,
fillOpacity = 0.4,
color = ~ pal(estimate)) %>%
leaflet::addLegend("bottomright",
pal = pal,
values = ~ estimate,
title = "Population percentiles",
opacity = 1) %>% # Add default OpenStreetMap map tiles
leaflet::addMarkers(lng = survey$Longitude, lat = survey$Latitude, popup = survey$Name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment