Q: R plot building footprint / outline on map using OpenStreetMap data - r

I'm rather new to creating maps and stuff in R, so please bear with me.
I'm trying to plot a building outline in R using data from OpenStreetMap, instead of having to define a polygon myself for plotting the outline of the building. But I cannot get my head around it.
The example below is what I have done so far to get the location:
library(leaflet)
leaflet() %>%
setView(lng=10.153523, lat=57.207181, zoom = 16) %>%
addTiles() %>%
addMarkers(lng=10.153523, lat=57.207181, popup="My building example")
And the example building data is available on https://www.openstreetmap.org/way/481541280
How do I integrate this building outline data into my R script? Is there a neat way of doing this other than extracting the points one by one and making a polygon using leaflet in R?

Related

GGplot geom_map gets distorted when plotting interactively with ggplotly

I am trying to create an interactive map of Germany with plotly and ggplot. At last, I'd like to overlay geom_points with tooltips, but so far I am struggeling with the aspect ratio.
I create the plot like this:
library(tidyverse)
library(ggplot2)
library(plotly)
p <- map_data("world") %>%
filter(region=="Germany") %>%
ggplot(aes(x=long, y = lat, group = group)) +
geom_polygon(fill="grey") +
coord_map()
When simply plotting it with ggplot, the aspect ratio of Germany is how I know it from school.
p
When converting it to a plotly plot with ggplotly the plot is distorted.
ggplotly(p)
Any ideas how to fix it? I don't know whether this is relevant, but I used to run this code in an R Markdown document.
Thanks a lot.
I'll guess you can't get a decent level of detail from the world map you used. With maps there are basically two types: generic, and, GIS (real mapping data).
Below is a non-distorted map of Germany. Here are the steps and data sources.
Download the GIS data - map of Germany. Source, https://gadm.org/download_country_v3.html
Choose the level of detail. 0 - the outline of the country, 1 - the country w/states. These files will have, sp.rds , extensions.
Cut and Paste the downloaded geographical reference data file into your working directory - this is easier than creating a path from the working directory to some other folder location. Since this data is actual geospatial data used in creating this plot of Germany, this data/plot can be used as a base map or overlay map with google maps, Overstreet maps, etc..
Use the following libraries and two lines of code to create the plot of Germany.
library(maptools)
library(raster)
library(rgdal)
gadm <- readRDS("gadm36_DEU_0_sp.rds") # get the gis file from w/d.
plot(gadm)

Using leaflet with large data - ACS data for all counties in U.S

I'm plotting ACS data (counts of low-income children) for each county across the entire U.S. I don't have any markers, just a county shapefile and 6 values for each county that are in separate layers.
Unsurprisingly this is too large for browsers to handle. I've seen some similar questions here that deal with clustering, but since I have nothing to cluster I'm starting a new question.
I've tried breaking it up into 6 regional maps, but even those are too much.
Is there some way to lower the footprint, but still have all the county specific data?
I've looked at tilemill and other options for only loading the data the user is currently viewing and based on the zoom level, but I can't find any information on how to go from an R generated leaflet map to something like that. Alternatives using this route are useful as well.
You can try to simplify the polygons using the rmapshaper package and then try visualising it with mapview. The former will help get rid of 'unnecessary' polygon vertices, while the latter has dedicated functions to enable leaflet rendering of large data (ballpark around 100k features - depending on complexity).
You might also consider the tigris package, which gets you direct access to low-resolution county shapefiles within R:
library(tigris)
library(leaflet)
cty <- counties(cb = TRUE, resolution = "20m")
leaflet(cty) %>% addTiles() %>% addPolygons()
This should allow your Leaflet map to perform well in-browser as the polygons are pre-simplified, if you choose to go this route.

Leaflet Polylines do not show up

I have a very small SpatialLinesDataFrame which I need to plot with Leaflet in R.
Unfortunately, for some reason I'm not able to do so.
This is the data (it's 12KB).
I try to do:
library(leaflet)
load("mylines.Rdata")
leaflet() %>% addTiles() %>% addPolylines(data=mylines)
However the resulting map does not make sense, I can only see a line in the top of the screen and this is not what should be plotted.
This is the result:
Instead, If I do:
library(mapview)
mapview(mylines)
Result:
It works perfectly, despite mapview using leaflet underneath.
What am I doing wrong in the Leaflet syntax?
I am used to working with leaflet providing rasters, so I usually use the addRasterImage function, which needs data projected over leaflet's display projection (EPSG:3857). However, for polygons and lines, as #TimSalabim correctly pointed out, this is not the case.
So the solution in this case was to just not reproject the data to the leaflet projection beforehand, and provide it in lat-lon coordinates (EPSG:4326).
mapview worked since it does this automagically.

R fastest Leaflet map to load

Background: I am currently drawing a leaflet map using the following code:
library(leaflet)
leaflet()%>%
addProviderTiles("Stamen.TerrainBackground")%>%
setView(lng=-81,lat=45,zoom=6)
Problem: The problem is that it takes around 4 seconds to have the map appear. This is an undesirable feature when I integrate the map with Rshiny, given that the website appears blank until the map finally loads.
I'm wondering two things:
1) Is there an open source map that is known to load quickly compared to other maps.
2) If 1) is not possible, I have noticed that in google maps, the tiles of the map start appearing in sequence. At least like that the user is able to know that the map is loading. Is there a way of having the tiles be drawn sequentially like that?
If you mean the tiles are slow to load, that is most likely either a problem with the tile provider or a problem with your connection. Leaflet itself is usually very fast in my experience.
As far as the tile provider, I've always had good success with open street map in JS.
With R it looks like this link https://rstudio.github.io/leaflet/ has the following example using OSM:
library(leaflet)
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
m # Print the map
So calling "addTiles() %>% should use open street map as default.

Overlaying shapefiles or raster over interactive maps

I'm using R, and I want to overlay some raster data (e.g. a temperature map from a model) over an interactive map which allows panning and zooming. Ideally, I'd like to overlay over Google Maps or OpenStreetMaps. The input data can be in shapefiles, KML, raster data or whatever comes in handy.
I know I can easily do this non-interactively using either googleVis, ggmap or RgoogleMaps. But I do not want to use tiles, I want interaction! Zooming, panning etc., directly from the browser.
googleVis, as far as I know, unfortunately only allows to show interactively points or addresses, not areas.
This question is very similar but I definitely want to try to do this using R. I can create the KML or geoJSON from R, but how do I overlay it from R directly?
OpenStreetMaps is also fine, however I've not found any reference on how to overlay data over it from R, despite the fact that OSM seems to have a pretty straightforward API.
The mapview package has been developed for this particular purpose. It also comes with a variety of background map layers. For a short introduction to what mapview is capable of, feel free to browse the package vignette. Here, for example, is some code that displays locations of selected breweries in Franconian Switzerland overlaid by a sample Landsat 8 scene (band 10). Check out ?breweries91 and ?poppendorf to retrieve information about the data used below and ?mapview to grow familiar with the numerous costumization options.
## require package
# install.packages("mapview")
library(mapview)
## visualize breweries and add landsat 8 band 10
mapview(breweries91) +
poppendorf[[10]]
The leaflet package may be of interest for you. You can easily add a raster object. From the documentation
Two-dimensional RasterLayer objects (from the raster package) can be
turned into images and added to Leaflet maps using the addRasterImage
function.
And here is an example also from the documentation:
library(leaflet)
library(raster)
r <- raster("nc/oisst-sst.nc")
pal <- colorNumeric(c("#0C2C84", "#41B6C4", "#FFFFCC"), values(r),
na.color = "transparent")
leaflet() %>% addTiles() %>%
addRasterImage(r, colors = pal, opacity = 0.8) %>%
addLegend(pal = pal, values = values(r),
title = "Surface temp")

Resources