Search code examples
rgeolocationmapsgeospatial

Adding state lines to geocoded data


I am plotting geo-coded data using the function mapview. A sample of my code reads:

locations_sf <- st_as_sf(locations, coords = c("LONGITUDE", "LATITUDE"), crs = 4326)
mapview(locations_sf,cex=locations$FR,color="black",legend = FALSE,label=locations$NAME)

This works fine so far. However, my data is from the US and I would like to add state-lines to the map. So far, I have not found how to do this in mapview. Any suggestions?


Solution

  • Good question. Probably the most important things to consider before starting is where you are getting your geodata from and what type of geodata that you want to be using.

    There are many dataset sources available and most of the R packages have some mapping goedata. A great source of geodata is from the website:

    https://gadm.org/data.html

    This website provides a large selection of geodata. To get the data for the USA with the state boundaries, select the USA from the country dropdown, and then choose USA_1 for the level of detail you want. The USA_0 does not show the individual state boundaries, the USA_1 shows the state boundaries, and the USA_2 shows the county and state boundaries.

    You will need to decide which of the two commonly used geodata types you want: sp or sf. I chose the sf data type for this example because the sf data is easy to use. The data shown in your example was converted from sp into the sf format.

    After the file has been downloaded, read, and assigned to a variable, the states of Hawaii and Alaska are removed from the data. This makes a map having only the Continental 48 states easier to use.

    After that, the data is plotted using mapview() and a browser tab opens displaying the map. None of the mapview() formatting options were used here. Code follows:

    df_1 <- readRDS("C:/python/datasets/GADM_Maps/US/gadm36_USA_1_sf.rds")
    head(df_1, 3)
    df49 <- df_1[df_1$NAME_1 != "Alaska", ]                       # remove AK from data
    df48 <- df49[df49$NAME_1 != "Hawaii", ]                       # remove HI from data
    
    mapview(df48$geom)
    

    The mapview browser page can be viewed at this link: