Exporting Interactive Map as a HTML Issue in R - html

I have used the following code to produce a map on R. The issue is when I try and export as a HTML I get this error:
popup.css not found in resource path
When I export as a local html it works fine. Does anyone know why this is and how to fix it? Any help would be greatly appreciated!
#Load shape file
UK_Map<-gadm36_GBR_2_sp
plot(UK_Map)
#Retail Data and Postcodes
Benchmark_Retail <- read_excel("C:/Users/andrew.smith2/Desktop/Benchmark output_v3 (1920).xlsx")
Postcodes <- read_excel("C:/Users/andrew.smith2/Desktop/Postcodes.xlsx")
#Merge Datasets
Retail_data<-merge(Benchmark_Retail,Postcodes,by="Postcode")
Retail_data2<-as.tibble(Retail_data)
locations_sf <- st_as_sf(Retail_data2, coords = c("longitude", "latitude"), crs = 4326)
m=mapview(locations_sf)
mapview(locations_sf)
mapshot(m, url = paste0(getwd(), "/map.html"))

Related

Plotting Polygons with Folium and Pyproj

I'm trying to plot the boundaries of the localities of Brussels. The system of coordinates of my json file has to be converted to a longlat system to display the Polygons on Folium maps. The issue I get is that my coordinates are projected into the Pacific ocean. I guess it is probably due to the fact that the parameters I set are not the good ones. Please find below my code:
import json
import pyproj
import folium
# Load JSON file
with open("districts.json", "r") as f:
data = json.load(f)
# Create a transformation object
in_proj = pyproj.Proj(proj='utm',zone=31,datum='WGS84')
out_proj = pyproj.Proj(proj='longlat',datum='WGS84')
# Transform the coordinates
features = data["features"]
for feature in features:
coords = feature["geometry"]["coordinates"][0]
coords = [pyproj.transform(in_proj, out_proj, coord[0], coord[1]) for coord in coords]
feature["geometry"]["coordinates"] = [coords]
# Plot the polyggon on a map
m = folium.Map()
folium.GeoJson(data).add_to(m)
m
This corresponds to how my json file is structured:
{"type":"FeatureCollection","features":[{"geometry":{"type":"Polygon","coordinates":[[[152914.748398394,173305.19242333],[152947.4133984,173326.530423339],...,[152961.983398418,173225.325423267],[152914.748398394,173305.19242333]]]},...
(https://i.stack.imgur.com/SuU4Q.png)
(https://i.stack.imgur.com/oIKJN.png)
Does anyone has an idea how to solve this? How could I find the right parameters?
I tried different zones but I would rather know of to find the right zone number and understand how it works.

Web Scrape an Image with rvest R

I'm having a problem when trying to scrape an image from this page. My code is as follow:
library(rvest)
url <- read_html("https://covid-19vis.cmm.uchile.cl/chart")
m <- '/html/body/div/div/div[4]/main/div/div/div/div/div/div[2]/div[1]'
grafico_cmm <- html_node(url, xpath = m) %>% html_attr('src')
When I run the above code, the result is NA. Does someone know how can I scrape the plot or maybe the data from the page?
Thanks a lot
It not an image, it is an interactive chart. For an image, you would need to scrape the data points and re-create as a chart and then convert to an image. Xpath is also invalid.
The data comes from an API call. I checked the values against the chart and this is the correct endpoint.
library(jsonlite)
data <- jsonlite::read_json('https://covid-19vis.cmm.uchile.cl/api/data?scope=0&indicatorId=57', simplifyVector = T)
The chart needs some tidying but here is a basic plot of the r values:
data$date <- data$date %>% as.Date()
library("ggplot2")
ggplot(data=data,
aes(x=date, y=value, colour ='red')) +
geom_line() +
scale_color_discrete(name = "R Efectivo", labels = c("Chile"))
print tail(data)

Load a point layer from CSV in PyQGIS QGIS 3.10

I'm trying to use a script that loads in a point layer from CSV. The code that I used is:
uri = "file:///some_path/PyQGIS/Some.csv?delimiter={}&xField={}&yField={}".format(os.getcwd(), ";", "X", "Y")
vlayer = QgsVectorLayer(uri, "Name", "delimitedtext")
QgsProject.instance().addMapLayer(vlayer)
The structure of the .csv file is as follows:
SomeValue ----- X ----- Y
Hereby, the coordinates are put according to Amersfoort (EPSG:4289) e.g.: X = 213404, Y = 500846. When trying to load this in manually, everything is going fine. However in the script, it does not seem to work. To clarify: The delimiter used is a ;
Thanks in advance.
You can specify the projection of your data set by adding &crs=epsg:4723 to the URI definition. So your case becomes:
uri = "file:///some_path/PyQGIS/Some.csv?delimiter={}&crs=epsg:4289&xField={}&yField={}".format(os.getcwd(), ";", "X", "Y")
vlayer = QgsVectorLayer(uri, "Name", "delimitedtext")
QgsProject.instance().addMapLayer(vlayer)
The answer to this is issue has been solved by removing the "os.getcwd()" part of the code. Hope this will help anyone with similar issues.

R: Make interactive maps that can be exported to HTML

I have been working with Leaflet for creating cool interactive maps in R. However, I cannot export the maps, as the background map ends up being grey after export.
library(leaflet)
library(htmlwidgets)
m <- leaflet(data.frame(lat = 55.71654, lng = 12.47484))
m <- addCircles(m, popup = "testpopup")
m <- addTiles(m)
m
saveWidget(m, file="testmap.html", selfcontained = TRUE)
Is there an alternative to Leaflet where you can export your interactive maps as HTML? Or do I have to get into the whole Leaflet/Shiny thing?
As mentioned my #Martin Schmelzer then it all works after updating leaflet through the devtools::install_github('rstudio/leaflet'). Thanks.

How different colors to different sections of a route on leaflet map? [R Studio]

I have a JSON file of a long route. The file contains the lat and long of of this route.
I'm trying to mark different sections of this route based on a set of criteria (which I've compiled in a dataframe). However, I'm facing to problems:
1) How do I break up this long set of lat and longs into segments? (can't do this manually because I have many route variations)
2) How do I assign a variable color to each segment?
I intend to use leaflet map (for its interactivity), but I'm open to better suggestions.
When working with spatial data, it helps to know spatial classes! I am assuming you know hoe to read your JSON file as a data frame into R.
Here's a reproducible example:
library(mapview)
library(sp)
### create some random data with coordinates from (data("breweries91", package = "mapview"))
set.seed(123)
dat <- data.frame(val = as.integer(rnorm(32, 10, 2)),
lon = coordinates(breweries91)[, 1],
lat = coordinates(breweries91)[, 2])
### state condition for creation of lines
cond <- c(8, 9, 10)
### loop through conditions and create a SpatialLines object for each condition
lns <- lapply(seq(cond), function(i) {
ind <- dat$val == cond[i]
sub_dat <- dat[ind, ]
coords <- cbind(sub_dat$lon, sub_dat$lat)
ln <- coords2Lines(coords, ID = as.character(cond[i]))
proj4string(ln) <- "+init=epsg:4326"
return(ln)
})
### view lines with mapview
mapview(lns[[1]], col = "darkred") +
mapview(lns[[2]], col = "forestgreen") +
mapview(lns[[3]], col = "cornflowerblue")
Essentially, what we are doing here is create a valid sp::SpatialLines object for each condition we specify. The we plot those using mapview given you mentioned interactivity. Plotting of spatial objects can be achieved in many ways (base, lattice, ggplot2, leaflet, ...) so there's many options to choose. Have a look at sp Gallery for a nice tutorial.
Note: This answer is only valid for non-projected geographic coordinates (i.e. latitude/longitude)!