I found this R code (Search button for Leaflet R map?) and was able to make a interactive map in R:
library(inlmisc)
city <- rgdal::readOGR(system.file("extdata/city.geojson",
package = "inlmisc")[1])
opt <- leaflet::markerClusterOptions(showCoverageOnHover = FALSE)
map <- CreateWebMap("Topo")
map <- leaflet::addMarkers(map, label = ~name, popup = ~name,
clusterOptions = opt,
clusterId = "cluster",
group = "marker", data = city)
map <- AddHomeButton(map)
map <- AddClusterButton(map, clusterId = "cluster")
map <- AddSearchButton(map, group = "marker", zoom = 15,
textPlaceholder = "Search city names...")
map
I was curious and wanted to see the format and entries of the "city" file. I was expecting this file to be a "tabular" file (i.e. containing rows and columns, like a data frame), but when I opened the file, it did not appear in this format at all - this file is apparently a "SpatialPointsDataFrame":
> head(city)
class : SpatialPointsDataFrame
features : 6
extent : -123.09, -73.8, 31.58, 44.62 (xmin, xmax, ymin, ymax)
crs : +proj=longlat +datum=WGS84 +no_defs
variables : 2
names : name, capital
min values : Abilene TX, 0
max values : Albany OR, 2
I then found this post here (How to convert a spatial dataframe back to normal dataframe?) and saw that you can convert a SpatialPointsDataFrame into a regular data frame like this:
DF <- as.data.frame(city)
> head(DF)
name capital coords.x1 coords.x2
1 Abilene TX 0 -99.74 32.45
2 Akron OH 0 -81.52 41.08
3 Alameda CA 0 -122.26 37.77
4 Albany GA 0 -84.18 31.58
5 Albany NY 2 -73.80 42.67
6 Albany OR 0 -123.09 44.62
But is there a way to convert a regular data frame into a "SpatialDataFrame"? I tried the following code and then tried to plot the results:
#https://stackoverflow.com/questions/29736577/how-to-convert-data-frame-to-spatial-coordinates
library(sf)
city <- st_as_sf(x = DF,
coords = c("coords.x1", "coords.x2"),
crs = "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
map <- CreateWebMap("Topo")
map <- leaflet::addMarkers(map, label = ~name, popup = ~name,
clusterOptions = opt,
clusterId = "cluster",
group = "marker", data = city)
map <- AddHomeButton(map)
map <- AddClusterButton(map, clusterId = "cluster")
map <- AddSearchButton(map, group = "marker", zoom = 15,
textPlaceholder = "Search city names...")
map
The code ran, but I get this warning message:
Warning message:
sf layer has inconsistent datum (+proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs).
Need '+proj=longlat +datum=WGS84
Am I doing this correctly?
Thank you!
Leaflet uses a slightly different format of crs than sf with st_as_sf, which you can read more about on GitHub. You have a few options, where first we could use a shortened crs, like here:
library(sf)
city <- st_as_sf(x = DF,
coords = c("coords.x1", "coords.x2"),
crs = "+proj=longlat +datum=WGS84 +no_defs")
Or you can use sp::CRS along with your crs definition, so that it is properly read by leaflet:
city <- st_as_sf(x = DF,
coords = c("coords.x1", "coords.x2"),
crs = sp::CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"))
Or another option would be to use the SRID 4326 as the crs (which will set the Geodetic CRS):
city <- st_as_sf(x = DF,
coords = c("coords.x1", "coords.x2"),
crs = 4326)
map <- CreateWebMap("Topo")
map <- leaflet::addMarkers(map, label = ~name, popup = ~name,
clusterOptions = opt,
clusterId = "cluster",
group = "marker", data = city)
map <- AddHomeButton(map)
map <- AddClusterButton(map, clusterId = "cluster")
map <- AddSearchButton(map, group = "marker", zoom = 15,
textPlaceholder = "Search city names...")
map
You will notice that in the answer you are using that they are using mapview, which does work with the format that you give (i.e., crs = "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"). So, it would work with your code, but it won't be in the leaflet style:
city <- st_as_sf(x = DF,
coords = c("coords.x1", "coords.x2"),
crs = "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
mapview::mapview(city)
Related
How can I remove the crossing line while using the buffer code below. I tried to create buffers round some point locations and to have a union but ended up getting a crossline.
please see the codes below
train_data
library(raster)
library(dismo)
library(sf)
bioc1 <- getData('worldclim', var='bio', res=5) #
bio1 <- bioc1[[1]]
plot(bio1)
train <- read.csv("forexample_training.csv") # the points locations to be buffered
head(train)
train.sf <- sf::st_as_sf(train, coords=c("longitude", "latitude"), crs=raster::crs(bio1))
plot(train.sf, add=TRUE)
eckertIV <- "+proj=eck4 +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"
train.sf <- sf::st_transform(train.sf, crs = eckertIV)
train.buf <- sf::st_buffer(train.sf, dist = 500000) %>%
sf::st_union() %>%
sf::st_sf() %>%
sf::st_transform(crs = raster::crs(bio1))
plot(bio1, main = names(bio1))
train.sf <- sf::st_as_sf(train, coords=c("longitude", "latitude"), crs=raster::crs(bio1))
plot(train.sf, add=TRUE)
# To add sf objects to a plot, use add = TRUE
plot(train.buf, border = "red", lwd = 3, add = TRUE)
Is it possible to display a projected raster on a projected basemap in R/leaflet? The addRasterImage() functions says that the projection needs to be in EPSG:3857. Can this not be changed by setting project = false? I am able to display projected vector data on a projected basemap, but not raster ...
My attempt:
library(leaflet)
library(raster)
library(sf)
# Find location in northern Canada
ca_df <- data.frame(long = -114.3717401, lat = 62.4525548, name="Yellowknife", stringsAsFactors = F )
ca_pt <- st_as_sf(ca_df,coords = c("long", "lat"), crs = 4326)
# Project to Alaska Polar Stereographic
ca_pt_5936 <- as_Spatial(st_transform(ca_pt, 5936))#coords
# Create raster around point
r_5936 <- raster(
matrix(round(runif(100)), ncol = 10),
xmn = ca_pt_5936[[1]] - 50000, xmx = ca_pt_5936[[1]] + 50000,
ymn = ca_pt_5936[[2]] - 50000, ymx = ca_pt_5936[[2]] + 50000,
crs = "EPSG:5936"
)
# Project raster to Web Mercator (needed to get the extent in lat/long)
r_3857 <- projectRaster(r_5936, crs="EPSG:3857", method = "ngb")
# Prep for leaflet: https://github.com/rstudio/leaflet/issues/550
tile_url <- 'https://services.arcgisonline.com/arcgis/rest/services/Polar/Arctic_Ocean_Base/MapServer/tile/{z}/{y}/{x}.png'
origin <- c(-2.8567784109255e+07, 3.2567784109255e+07)
resolutions <- c(
238810.813354,119405.406677, 59702.7033384999, 29851.3516692501,14925.675834625,
7462.83791731252,3731.41895865639, 1865.70947932806,932.854739664032,
466.427369832148, 233.213684916074, 116.60684245803701, 58.30342122888621,
29.151710614575396, 14.5758553072877, 7.28792765351156, 3.64396382688807,
1.82198191331174, 0.910990956788164, 0.45549547826179, 0.227747739130895,
0.113873869697739, 0.05693693484887, 0.028468467424435)
epsg5936 <- leafletCRS(
crsClass = 'L.Proj.CRS',
code = 'EPSG:5936',
proj4def = '+proj=stere +lat_0=90 +lat_ts=90 +lon_0=-150 +k=0.994 +x_0=2000000 +y_0=2000000 +datum=WGS84 +units=m +no_defs',
origin = origin,
resolutions = resolutions
)
# Map
leaflet(r_3857,
options= leafletOptions(
crs=epsg5936)) %>%
addTiles(urlTemplate = tile_url,
attribution = "Esri, DeLorme, GEBCO, NOAA NGDC, and other contributors",
options = tileOptions(minZoom = 0, maxZoom = 4)) %>%
addRasterImage(r_5936, project = F)
The output doesn't display the raster.
This is an example of a list with two separate (not adjacent or overlapping) SpatialPolygons and I would like to join them into one shapefile. For some reason no matter what I try I keep getting an error:
library(sp)
coords = matrix(c(78.46801, 19.53407,
78.46801, 19.74557,
78.83157, 19.74557,
78.83157, 19.53407,
78.46801, 19.53407),
ncol = 2, byrow = TRUE)
P1 = Polygon(coords)
Ps1 = SpatialPolygons(list(Polygons(list(P1), ID = "a")), proj4string=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"))
coords2 = matrix(c(77.46801, 17.53407,
77.46801, 17.74557,
77.83157, 17.74557,
77.83157, 17.53407,
77.46801, 17.53407),
ncol = 2, byrow = TRUE)
P2 = Polygon(coords2)
Ps2 = SpatialPolygons(list(Polygons(list(P2), ID = "a")), proj4string=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"))
P_list <- list(Ps1,Ps2)
joined = SpatialPolygons(lapply(P_list, function(x){x#polygons[[1]]}))
Error in validObject(res) :
invalid class “SpatialPolygons” object: non-unique Polygons ID slot values
So I have the following script trying to prepare the data to do modelling on them later on using "biomod2" package. It tries to overlay species (xlm) presence points on environmental layers (bio1, bio7).
library(biomod2)
library(raster)
data <- structure(list(longitude = c(-122.84,-119.418,-78.6569,-78.1834, -89.3985), latitude = c(45.28,36.7783,37.4316,-1.8312, 32.3547)), .Names = c("X_WGS84",
"Y_WGS84"), class = "data.frame", row.names = c(NA, -5L))
data$xlm<-1
spdf <- SpatialPointsDataFrame(coords = xy, data = data,
proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
myRespName <- 'xlm'
myResp <- as.numeric(data[,myRespName])
myRespXY <- data[,c('X_WGS84','Y_WGS84')]
myExpl = stack( system.file( "external/bioclim/current/bio3.grd", package="biomod2"),
system.file( "external/bioclim/current/bio4.grd", package="biomod2"))
myBiomodData <- BIOMOD_FormatingData(resp.var = myResp,expl.var = myExpl,resp.xy = myRespXY,resp.name = myRespName)
plot(myBiomodData)
It works in this case, however, the issue is when I want to replace "bio4.grd" and "bio3.grd" layers in the package with my own data, it doesn't work. I have tried it as follow. First i thought it might be "asci" file format but even by converting them to "grd" still I don't get the points overlayed on layers stacked. It does overlay only one point in Southern USA (around Louisiana, Mississippi) though.
library(biomod2)
library(raster)
data <- structure(list(longitude = c(-122.84,-119.418,-78.6569,-78.1834, -89.3985), latitude = c(45.28,36.7783,37.4316,-1.8312, 32.3547)), .Names = c("X_WGS84",
"Y_WGS84"), class = "data.frame", row.names = c(NA, -5L))
data$xylella<-1
spdf <- SpatialPointsDataFrame(coords = xy, data = data,
proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
myRespName <- 'xylella'
myResp <- as.numeric(data[,myRespName])
myRespXY <- data[,c('X_WGS84','Y_WGS84')]
bio2<-raster("C:\\Data\\BioClim_V2_MaxEnt\\wc2.0_bio_10m_02.asc")
crs(bio2) <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
writeRaster(bio2, "C:\\Data\\BioClim_V2_MaxEnt\\bio2", overwrite=TRUE)
bio7<-raster("C:\\Data\\BioClim_V2_MaxEnt\\wc2.0_bio_10m_07.asc")
crs(bio7) <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
writeRaster(bio7, "C:\\Data\\BioClim_V2_MaxEnt\\bio7", overwrite=TRUE)
myExpl = stack (bio2,bio7)
myBiomodData <- BIOMOD_FormatingData(resp.var = myResp,expl.var = myExpl,resp.xy = myRespXY,resp.name = myRespName)
plot(myBiomodData)
Any help highly appreciated. Many thanks.
I have run sum analysis on points summarized within a SpatialPointsDataFrame:
> trjct_pts
class : SpatialPointsDataFrame
features : 104559
extent : 696621.4, 696688.7, 167659.2, 167739.8 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs
variables : 1
names : Intensity_kJ
min values : 161.951
max values : 1192.526
Which I have used to create 2 rasters:
library(raster)
rockfall_count <- raster (xmn = 696583.6, xmx = 696799.6, ymn = 167579.6, ymx = 167789.6, res = 2,
crs = "+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs")
rockfall_intensity <- raster (xmn = 696583.6, xmx = 696799.6, ymn = 167579.6, ymx = 167789.6, res = 2,
crs = "+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs")
# count unique ID per raster
rockfall_count <- rasterize(trjct_points_coords, rockfall_count, fun = "count", by = ID)
rockfall_count
plot(rockfall_count,col=brewer.pal(9,"YlOrRd"))
# average kinetic energy per raster cell
rockfall_intensity <- rasterize(trjct[, c('x', 'y')], rockfall_intensity, trjct$Etot, fun = mean)
plot(rockfall_intensity, col=brewer.pal(9,"YlOrRd"))
For nice illustration, I would like to download the corresponding satellite image. I have tried the following:
library(rgdal)
longlatcoor<-spTransform(trjct_pts,CRS("+proj=longlat"))
coordinates(longlatcoor)
longlatcoor
library(ggmap)
library(ggplot2)
# Set a range
lat <- c(-13.4003, -13.39943)
lon <- c(35.419, 35.41961)
# Get a map
map <- get_map(location = c(lon = mean(lon), lat = mean(lat)), zoom = 14,
maptype = "satellite", source = "google")
ggmap(map)
#limit lon and lat.
tschamut <- ggmap(map)+
scale_x_continuous(limits = c(-13.4003, -13.39943), expand = c(0, 0)) +
scale_y_continuous(limits = c(35.419, 35.41961), expand = c(0, 0))
tschamut
However, R crashes everytime i try to run this code, so i suspect something is seriously wrong with it. I derived the number used in the code from the bounding box:
> longlatcoor
class : SpatialPointsDataFrame
features : 104559
extent : -13.4003, -13.39943, 35.419, 35.41961 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +ellps=WGS84
variables : 1
names : Intensity_kJ
min values : 161.951
max values : 1192.526
How can I import the aerial photograph into R ?