Ploting image in shiny R - r

I am starting to play with shinny apps and I am getting the following error when I try to run the code. The output$myrgb and output$mynrgvariables are not being ploted.
I think the issue is realted to the way I am closing the brackets but I have tried several alternatives and the issue is still happening.
Any idea?
library(shiny)
library(leaflet)
library(dbplyr)
library(raster)
library(rgdal)
ui<-fluidPage(
titlePanel("Calculation"),
"SHORT DESCRIPTION ---- ",
"Study area location",
textInput(inputId = "mypath", label = "Path to Sentinel images"),
leafletOutput("mymap",height = 1000),
imageOutput(outputId = "myrgb"),
imageOutput(outputId = "mynrg"),
imageOutput(outputId = "ndvi")
)
server<-function(input, output) {
output$mymap <- renderLeaflet({
m <- leaflet() %>%
addTiles() %>%
setView(lng=-60.143, lat=-19.9052, zoom=7)
m
# Load images
bands<-c("B((0[2348]_10m)).jp2$")
S2<-list.files(input$mypath, full.names = TRUE, pattern = ".SAFE")
S2<-list.files(S2, recursive = TRUE, full.names = TRUE, pattern=bands)
S2<-lapply(1:length(S2), function (x) {raster(S2[x])})
S2<-stack(S2)
utmcoor<-SpatialPoints(cbind(xmin(S2[[1]]),ymax(S2[[1]])), proj4string=CRS(proj4string(S2[[1]]))) # prepare UTM coordinates matrix
longlatcoor<-spTransform(utmcoor,CRS("+proj=longlat +datum=WGS84")) # converting
utmcoor2<-SpatialPoints(cbind(xmax(S2[[1]]),ymin(S2[[1]])), proj4string=CRS(proj4string(S2[[1]]))) # prepare UTM coordinates matrix abajo derecha
longlatcoor2<-spTransform(utmcoor2,CRS("+proj=longlat +datum=WGS84")) # converting
lng1<-xmin(longlatcoor) # extract coordinates to variable
lng2<-xmin(longlatcoor2)
lat1<-ymin(longlatcoor)
lat2<-ymin(longlatcoor2)
leaflet() %>% addTiles() %>% # Add coordinates to map
addRectangles(
lng1=lng1, lat1=lat1,
lng2=lng2, lat2=lat2,
fillColor = "transparent")
})
output$myrgb <- renderPlot({plotRGB(S2, r=3, g=2, b=1, scale=maxValue(S2[[1]]), stretch="lin")})
output$mynrg <- renderPlot({plotRGB(S2, r=4, g=3, b=2, scale=maxValue(S2[[1]]), stretch="lin")})
}
shinyApp( ui=ui, server=server)
EDIT ---
ERROR: object of type 'closure' is not subsettable

It's hard to help without your files. But you should do something like that. Use a reactive conductor to pass the raster object.
server<-function(input, output) {
Raster <- reactive({
bands <- c("B((0[2348]_10m)).jp2$")
S2 <- list.files(input$mypath, full.names = TRUE, pattern = ".SAFE")
S2 <- list.files(S2, recursive = TRUE, full.names = TRUE, pattern=bands)
S2 <- lapply(1:length(S2), function (x) {raster(S2[x])})
stack(S2)
})
output$mymap <- renderLeaflet({
m <- leaflet() %>%
addTiles() %>%
setView(lng=-60.143, lat=-19.9052, zoom=7)
S2 <- Raster()
utmcoor<-SpatialPoints(cbind(xmin(S2[[1]]),ymax(S2[[1]])), proj4string=CRS(proj4string(S2[[1]]))) # prepare UTM coordinates matrix
longlatcoor<-spTransform(utmcoor,CRS("+proj=longlat +datum=WGS84")) # converting
utmcoor2<-SpatialPoints(cbind(xmax(S2[[1]]),ymin(S2[[1]])), proj4string=CRS(proj4string(S2[[1]]))) # prepare UTM coordinates matrix abajo derecha
longlatcoor2<-spTransform(utmcoor2,CRS("+proj=longlat +datum=WGS84")) # converting
lng1<-xmin(longlatcoor) # extract coordinates to variable
lng2<-xmin(longlatcoor2)
lat1<-ymin(longlatcoor)
lat2<-ymin(longlatcoor2)
m %>% # Add coordinates to map
addRectangles(
lng1=lng1, lat1=lat1,
lng2=lng2, lat2=lat2,
fillColor = "transparent")
})
output$myrgb <- renderPlot({
S2 <- Raster()
plotRGB(S2, r=3, g=2, b=1, scale=maxValue(S2[[1]]), stretch="lin")
})
output$mynrg <- renderPlot({
S2 <- Raster()
plotRGB(S2, r=4, g=3, b=2, scale=maxValue(S2[[1]]), stretch="lin")
})
}

Related

Shiny page with global variables crashes

I have some large shapefiles that I want to run some intersect analysis on using user input on a leaflet map. My shiny page displays a map that a user can draw a polygon on and I want to see if that polygon intersects either of the two shapefiles. I built a working version of this where the server reads in the shapefiles each time a user connects to the server, but obviously that isn't a great user experience. So I have been trying to move the shapefile reading to global variables that the server loads once, and the user just has to run the intersect on. I'll skip posting my 3 lines of UI for now but this app works locally, it's only when I run it on a dedicated Shiny server that is crashes after the user "closes" the polygon. I have a feeling it's an issue with the global variable declarations, but there is no log file generated so I'm having a really hard time debugging it.
App.R
library(shiny)
source("/ui.R")
source("/server.R")
shpfile1 <- st_read("path_to_shpfile1")
shpfile2 <- st_read("path_to_shpfile2")
ui <- ui()
server <- server()
shinyApp(ui = ui, server = server)
Server.R
# a number of libraries
server <- function(input, output, session) {
output$s1 <- renderText({"Define project area..."})
output$s2 <- renderText({"Define project area..."})
print("Reading New Jersey boundary...")
mapStates = map("state", "New Jersey", fill = FALSE, plot = FALSE)
output$map <- renderLeaflet({
leaflet(data = mapStates) %>% addTiles() %>% addPolygons(fillColor = topo.colors(10, alpha=0.8), stroke=FALSE) %>%
addDrawToolbar(targetGroup = "projectArea",
rectangleOptions = F,
polylineOptions = F,
markerOptions = F,
circleMarkerOptions = F,
editOptions = editToolbarOptions(edit = FALSE, remove = TRUE, selectedPathOptions = selectedPathOptions()),
circleOptions = F)
})
observeEvent(input$drawPoints, {
proxy %>% clearShapes()
for (i in seq_along(data)) {
proxy %>% addPolygons(
data[[i]][,"lon"],
data[[i]][,"lat"],
layerId=i,
opacity=0.4,
color = c('red','green')[i]
)
Sys.sleep(2) # - this is to see first (red) polygon
}
})
observeEvent(input$map_draw_new_feature, {
withProgress(message = "Please wait...", value = 0, {
# capture project area and convert to usable format for intersecting
feat <- input$map_draw_new_feature
coords <- unlist(feat$geometry$coordinates)
coords <- matrix(coords, ncol=2, byrow=TRUE)
poly <- st_sf(st_sfc(st_polygon(list(coords))), crs = "+proj=longlat +datum=WGS84")
# intersect project area with constraint layers
incProgress(1/3, detail = "Analyzing shapefile1...")
i_shp1 <- st_intersects(poly, shpfile1)
c_shp1 <- sapply(i_shp1, length)
incProgress(2/3, detail = "Analyzing shapefile2...")
i_shp2 <- st_intersects(poly, shpfile2)
c_shp2 <- sapply(i_shp2, length)
if(c_streams > 0) {
output$s1 <- renderText({"does intersect shapefile 1"})
} else {
output$s1 <- renderText({"does not intersect shapefile 1"})
}
if(c_wetlands > 0) {
output$s2 <- renderText({"does intersect shapefile 2"})
} else {
output$s2 <- renderText({"does not intersect shapefile 2"})
}
})
})
}

Filtering and Clustering SpatialPointDataFrame in a Shiny reactive not working

This reproducible code is based on the meuse dataset from the gstat package.
I'd like to be able to filter the dataset by x and y boundaries and subsequently cluster the data. However - I'm having a few issues:
the first error is seems related to getting my coordinates in the right format:
cannot derive coordinates from non-numeric matrix
the second difficulty is how to actually designate the clustering based on the input parameters.
Is there a better way to cluster points from spatial points?
CODE:
library(tidyverse)
library(sp)
library(rgdal)
library(scales)
library(ggthemes)
library(ggalt)
data(meuse)
meuseLL <- spTransform(
sp::SpatialPointsDataFrame(dplyr::select(meuse, y, x),
data = dplyr::select(meuse, -y, -x),
proj4string = CRS("+proj=utm +zone=19 ellps=WGS84 +south")),
CRS("+proj=longlat +ellps=WGS84 +datum=WGS84")
)
# Convert from Eastings and Northings to Latitude and Longitude and rename columns
colnames(meuseLL#coords)[colnames(meuseLL#coords) == "x"] <- "Long"
colnames(meuseLL#coords)[colnames(meuseLL#coords) == "y"] <- "Lat"
meuseLL_df <- as.data.frame(meuseLL)
ui <- fluidPage(
titlePanel("Custer Mapper"),
sidebarLayout(
sidebarPanel(width = 3,
numericInput("x1", label = h5("longitude bottom left (d.deg.)"), value = -87.79302),
numericInput("y1", label = h5("latitude bottom left (d.deg.)"), value = -112.92162),
numericInput("x2", label = h5("longitude top right (d.deg.)"), value = -87.81127),
numericInput("y2", label = h5("latitude top right (d.deg.)"), value = -111.89575),
numericInput("cdist", label = h5("Distance (km):"), value = .1),
numericInput("dclustn", label = h5("min points in dist cluster"), value = 3)
),
mainPanel(
plotOutput("plot1", width="700px",height="700px"))
))
# Define server logic required to draw a histogram
server <- function(input, output, session) {
F_df <- reactive({
filter(meuseLL_df, Lat > input$y1 &
Lat < input$y2 &
Long > input$x1 &
Long < input$x2)
})
sp_df <- reactive({
# Convert the data to the right projected coordinate system.
x <- spTransform(
sp::SpatialPointsDataFrame(dplyr::select(F_df(), Lat, Long),
data = dplyr::select(F_df(), -Lat, -Long),
proj4string = CRS("+proj=longlat +ellps=WGS84 +datum=WGS84")),
CRS("+proj=utm +zone=19 ellps=WGS84 +south")
)
list(spdata = x#data, xcoords = coordinates(x)[,1], ycoords = coordinates(x)[,2])
})
xy_df <- reactive({
data.frame(sp_df()$spdata,
Clust=hclust(dist(data.frame(rownames=rownames(sp_df()$spdata),
x=sp_df()$xcoords,
y=sp_df()$ycoords)),
method="single") %>%
cutree(input$cdist))
})
xy_df_filt <- reactive({
xy_df() %>%
group_by(Clust) %>%
mutate(n=n()) %>%
filter(n>(input$dclustn-1)) %>%
droplevels()
})
output$plot1 <- renderPlot({
p1 <- xy_df_filt() %>%
dplyr::select(Copper, Long,Lat, Clust) %>%
ggplot() +
geom_point(aes(x=Long, y=Lat, colour = Clust), size=2) +
guides(colour=FALSE) +
coord_fixed() +
theme_hc()
p1
})
}
# Run the application
shinyApp(ui = ui, server = server)

Building Quadrants in Rshiny

I wanna build quadrants on my leaflet as part of my quadrat analysis. currently I have my tessalation object and im trying to draw the tiles on my leaflet. My code is below
library(spatstat)
library(leaflet)
firms_ppp <- ppp(x=cbd_points#coords[,1],y=cbd_points#coords[,2], window =
window)
qc <- quadratcount(firms_ppp)
qc.nu <- as.numeric(qc)
qc.tess <- as.tess(qc)
colorpal4 <- colorNumeric("red",c(min(qc.nu, na.rm = TRUE),max(qc.nu, na.rm = TRUE)))
for (j in 1:length(qc.tess$window$yrange)) {
for (i in 1:length(qc.tess$window$xrange[i])) {
leaflet() %>%
addRectangles(lng1 = qc.tess$window$xrange[i], lng2 = qc.tess$window$xrange[i+1],
lat1 = rev(qc.tess$window$yrange)[j], lat2 = rev(qc.tess$window$yrange)[j+1],
color = colorpal4(qc.nu[j+(i-1)*(length(qc.tess$window$yrange)-1)]),
popup = paste("<h3>",qc.nu[j+(i-1)*(length(qc.tess$window$yrange)-1)],"</h3>")
)
}
}
Any idea how I can build the quadrants? I tried with tiles as well but I cant seem to get it to work too! Pls Help!!
With 2 helping functions found here, which convert a Tesselation object into SpatialPolygons, you can achieve something like this:
library(spatstat)
library(leaflet)
library(sp)
## FUNCTIONS #####################
owin2Polygons <- function(x, id="1") {
stopifnot(is.owin(x))
x <- as.polygonal(x)
closering <- function(df) { df[c(seq(nrow(df)), 1), ] }
pieces <- lapply(x$bdry,
function(p) {
Polygon(coords=closering(cbind(p$x,p$y)),
hole=spatstat.utils::is.hole.xypolygon(p)) })
z <- Polygons(pieces, id)
return(z)
}
tess2SP <- function(x) {
stopifnot(is.tess(x))
y <- tiles(x)
nom <- names(y)
z <- list()
for(i in seq(y))
z[[i]] <- owin2Polygons(y[[i]], nom[i])
return(SpatialPolygons(z))
}
## DATA #####################
cbd_points <- data.frame(
long = runif(100,15,19),
lat = runif(100,40,50)
)
window <- owin(c(0,20), c(30,50))
firms_ppp <- ppp(x=cbd_points$long, y=cbd_points$lat, window = window)
qc <- quadratcount(firms_ppp)
qc.nu <- as.numeric(qc)
qc.tess <- as.tess(qc)
colorpal4 <- colorNumeric("red",c(min(qc.nu, na.rm = TRUE),max(qc.nu, na.rm = TRUE)))
PolyGrid <- tess2SP(qc.tess)
PolyGridDF <- SpatialPolygonsDataFrame(PolyGrid, data = data.frame(ID = 1:length(PolyGrid)), match.ID = F)
## SHINY ########################
library(shiny)
ui <- fluidPage(
leafletOutput("map")
)
server <- function(input, output, session) {
output$map <- renderLeaflet({
pal = colorFactor("viridis", as.character(PolyGridDF$ID))
leaflet() %>%
addTiles() %>%
addPolygons(data=PolyGridDF,
label = as.character(PolyGridDF$ID),
color = ~pal(as.character(PolyGridDF$ID)))
})
}
shinyApp(ui, server)

How to download polygons drawn in leaflet.draw as GeoJson file, from R (Shiny)

I created an application in R-shiny, using the leaflet.extra package, I put a map in which my users can draw polygons, my goal is to be able to download the polygons that my users drew as a GeoJson or Shapefil (.shp) .
My application looks like this:
ui <- fluidPage(
textOutput("text"),leafletOutput("mymap") )
and server:
poly<-reactiveValues(poligonos=list()) #save reactiveValues
output$mymap <- renderLeaflet({
leaflet("mymap") %>%
addProviderTiles(providers$Stamen.TonerLite, #map type or map theme. -default($Stame.TonerLite)
options = providerTileOptions(noWrap = TRUE)
)%>% addDrawToolbar(
targetGroup='draw',
editOptions = editToolbarOptions(selectedPathOptions = selectedPathOptions())) %>%
addLayersControl(overlayGroups = c('draw'), options =
layersControlOptions(collapsed=FALSE)) %>%
addStyleEditor()
})
polygons<- eventReactive(input$mymap_draw_all_features, {
features<-input$mymap_draw_all_features
poly$poligonos<-c(poly$poligonos,features)
return(poly$poligonos)
})
The eventReactive function called "polygons" is responsible for recording the polygons (coordinates) that are drawn, but i din't know how to save them or convert into a GeoJson or shapefile format.
What you can do is take the coordinates of the polygons you made with the DrawToolbar and use them to create polygons in a reactiveValues SpatialPolygonsDataFrame. You can export that SPDF as a shapefile (with the example below you have to publish to the server to make the download option work. It will not work from R Studio).
ui <- fluidPage(
textOutput("text"),leafletOutput("mymap"),
downloadButton('downloadData', 'Download Shp'))
--
server<- function(input, output, session) {
output$mymap <- renderLeaflet({
leaflet("mymap") %>%
addProviderTiles(providers$Stamen.TonerLite, #map type or map theme. -default($Stame.TonerLite)
options = providerTileOptions(noWrap = TRUE)) %>%
addDrawToolbar(targetGroup = "drawnPoly",
rectangleOptions = F,
polylineOptions = F,
markerOptions = F,
editOptions = editToolbarOptions(selectedPathOptions = selectedPathOptions()),
circleOptions=F,
polygonOptions=drawPolygonOptions(showArea=TRUE, repeatMode=F , shapeOptions=drawShapeOptions( fillColor="red",clickable = TRUE))) %>%
addStyleEditor()
})
latlongs<-reactiveValues() #temporary to hold coords
latlongs$df2 <- data.frame(Longitude = numeric(0), Latitude = numeric(0))
#########
#empty reactive spdf
value<-reactiveValues()
SpatialPolygonsDataFrame(SpatialPolygons(list()), data=data.frame (notes=character(0), stringsAsFactors = F))->value$drawnPoly
#fix the polygon to start another
observeEvent(input$mymap_draw_new_feature, {
coor<-unlist(input$mymap_draw_new_feature$geometry$coordinates)
Longitude<-coor[seq(1,length(coor), 2)]
Latitude<-coor[seq(2,length(coor), 2)]
isolate(latlongs$df2<-rbind(latlongs$df2, cbind(Longitude, Latitude)))
poly<-Polygon(cbind(latlongs$df2$Longitude, latlongs$df2$Latitude))
polys<-Polygons(list(poly), ID=input$mymap_draw_new_feature$properties$`_leaflet_id`)
spPolys<-SpatialPolygons(list(polys))
#
value$drawnPoly<-rbind(value$drawnPoly,SpatialPolygonsDataFrame(spPolys,
data=data.frame(notes=NA, row.names=
row.names(spPolys))))
###plot upon ending draw
observeEvent(input$mymap_draw_stop, {
#replot it - take off the DrawToolbar to clear the features and add it back and use the values from the SPDF to plot the polygons
leafletProxy('mymap') %>% removeDrawToolbar(clearFeatures=TRUE) %>% removeShape('temp') %>% clearGroup('drawnPoly') %>% addPolygons(data=value$drawnPoly, popup="poly", group='drawnPoly', color="blue", layerId=row.names(value$drawnPoly)) %>%
addDrawToolbar(targetGroup = "drawnPoly",
rectangleOptions = F,
polylineOptions = F,
markerOptions = F,
editOptions = editToolbarOptions(selectedPathOptions = selectedPathOptions()),
circleOptions=F,
polygonOptions=drawPolygonOptions(showArea=TRUE, repeatMode=F , shapeOptions=drawShapeOptions( fillColor="red",clickable = TRUE)))
})
latlongs$df2 <- data.frame(Longitude = numeric(0), Latitude = numeric(0)) #clear df
})
########################
### edit polygons / delete polygons
observeEvent(input$mymap_draw_edited_features, {
f <- input$mymap_draw_edited_features
coordy<-lapply(f$features, function(x){unlist(x$geometry$coordinates)})
Longitudes<-lapply(coordy, function(coor) {coor[seq(1,length(coor), 2)] })
Latitudes<-lapply(coordy, function(coor) { coor[seq(2,length(coor), 2)] })
polys<-list()
for (i in 1:length(Longitudes)){polys[[i]]<- Polygons(
list(Polygon(cbind(Longitudes[[i]], Latitudes[[i]]))), ID=f$features[[i]]$properties$layerId
)}
spPolys<-SpatialPolygons(polys)
SPDF<-SpatialPolygonsDataFrame(spPolys,
data=data.frame(notes=value$drawnPoly$notes[row.names(value$drawnPoly) %in% row.names(spPolys)], row.names=row.names(spPolys)))
value$drawnPoly<-value$drawnPoly[!row.names(value$drawnPoly) %in% row.names(SPDF),]
value$drawnPoly<-rbind(value$drawnPoly, SPDF)
})
observeEvent(input$mymap_draw_deleted_features, {
f <- input$mymap_draw_deleted_features
ids<-lapply(f$features, function(x){unlist(x$properties$layerId)})
value$drawnPoly<-value$drawnPoly[!row.names(value$drawnPoly) %in% ids ,]
})
#write the polys to .shp
output$downloadData<-downloadHandler(
filename = 'shpExport.zip',
content = function(file) {
if (length(Sys.glob("shpExport.*"))>0){
file.remove(Sys.glob("shpExport.*"))
}
proj4string(value$drawnPoly)<-"+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
writeOGR(value$drawnPoly, dsn="shpExport.shp", layer="shpExport", driver="ESRI Shapefile")
zip(zipfile='shpExport.zip', files=Sys.glob("shpExport.*"))
file.copy("shpExport.zip", file)
if (length(Sys.glob("shpExport.*"))>0){
file.remove(Sys.glob("shpExport.*"))
}
}
)
}
--
shinyApp(ui=ui,server=server)

Drawing journey path using leaflet in R

I am creating a Shiny dashboard with a dataframe of start longitude/latitude and end longitude/latitude cooridnated that I have plotted in R using the leaflet package:
`m=leaflet()%>%
addTiles() %>%
addMarkers(lng=(data$Start_long[i:j]), lat=(data$Start_lat[i:j]),popup="Start") %>%
addCircleMarkers(lng=(data$End_long[i:j]), lat=(data$End_lat[i:j]),popup="End",clusterOptions=markerClusterOptions())`
I was wondering if there was a way to join the start and end coordinated by public transport routes (maybe through google maps API or in-library functions or failing that, join the coordinates by a straight line?
You can use my googleway package to both get the directions/routes, and plot it on a Google map
To use Google's API you need a valid key for each API you want to use. In this case you'll want a directions key, and for plotting the map you'll want a maps javascript key
(You can generate one key and enable it for both APIs if you wish)
To call the Directions API and plot it in R, you can do
library(googleway)
api_key <- "your_directions_api_key"
map_key <- "your_maps_api_key"
## set up a data.frame of locations
## can also use 'lat/lon' coordinates as the origin/destination
df_locations <- data.frame(
origin = c("Melbourne, Australia", "Sydney, Australia")
, destination = c("Sydney, Australia", "Brisbane, Australia")
, stringsAsFactors = F
)
## loop over each pair of locations, and extract the polyline from the result
lst_directions <- apply(df_locations, 1, function(x){
res <- google_directions(
key = api_key
, origin = x[['origin']]
, destination = x[['destination']]
)
df_result <- data.frame(
origin = x[['origin']]
, destination = x[['destination']]
, route = res$routes$overview_polyline$points
)
return(df_result)
})
## convert the results to a data.frame
df_directions <- do.call(rbind, lst_directions)
## plot the map
google_map(key = map_key ) %>%
add_polylines(data = df_directions, polyline = "route")
And similarly in a Shiny app
library(shiny)
library(shinydashboard)
library(googleway)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(
textInput(inputId = "origin", label = "Origin"),
textInput(inputId = "destination", label = "Destination"),
actionButton(inputId = "getRoute", label = "Get Rotue"),
google_mapOutput("myMap")
)
)
server <- function(input, output){
api_key <- "your_directions_api_key"
map_key <- "your_maps_api_key"
df_route <- eventReactive(input$getRoute,{
print("getting route")
o <- input$origin
d <- input$destination
return(data.frame(origin = o, destination = d, stringsAsFactors = F))
})
output$myMap <- renderGoogle_map({
df <- df_route()
print(df)
if(df$origin == "" | df$destination == "")
return()
res <- google_directions(
key = api_key
, origin = df$origin
, destination = df$destination
)
df_route <- data.frame(route = res$routes$overview_polyline$points)
google_map(key = map_key ) %>%
add_polylines(data = df_route, polyline = "route")
})
}
shinyApp(ui, server)
You can addPolylines() to the map.
It takes two vectors as arguments, one for the lat and one for the lng, where each row is a 'waypoint'.
It's difficult to help you without knowing the structure of your data.
MRE:
library(leaflet)
cities <- read.csv(textConnection("
City,Lat,Long,Pop
Boston,42.3601,-71.0589,645966
Hartford,41.7627,-72.6743,125017
New York City,40.7127,-74.0059,8406000
Philadelphia,39.9500,-75.1667,1553000
Pittsburgh,40.4397,-79.9764,305841
Providence,41.8236,-71.4222,177994
"))
leaflet() %>%
addTiles() %>%
addPolylines(lat = cities$Lat, lng = cities$Long)
I use "for loop" to solve such problem,just draw polylines one by one.
(sorry for my Chinese expression ^_^)
for examply :
for(i in 1:nrow(sz)){
if(i<=nrow(sz) ){
a <- as.numeric(c(sz[i,c(8,10)]));
b <- as.numeric(c(sz[i,c(9,11)]));
A <- A %>% addPolylines(a,b,group=NULL,weight = 1,color = "brown",
stroke = TRUE,fill = NULL,opacity = 0.8)}
or like a more complex one
for(j in 0:23){if(j<=23)
#j--切每小时数据
j1 <- as.character(paste(j,"点",sep=''))
sz <- sz121[sz121$h==j,]
sz_4 <- sz121[sz121$bi_state==4 &sz121$h==j ,]
sz_8 <- sz121[sz121$bi_state==8&sz121$h==j,]
#还原A
A <- leaflet(sz121) %>% amap() %>% addLabelOnlyMarkers(~s_lon,~s_lat) %>%
addLegend(title=j1,colors=NULL,labels =NULL,position="topleft")
A <- A %>%addCircleMarkers(data=sz_8,~s_lon,~s_lat,color="orange",fill=TRUE,fillColor = "red", opacity = 1,fillOpacity=0.8,
weight =1,radius = 10) %>%addCircleMarkers(data=sz_4,~s_lon,~s_lat,color="black",fill=TRUE,fillColor = "red",
opacity = 1,fillOpacity=0.8,weight =5,radius = 10 ) %>%
addCircleMarkers(data=sz_8,~e_lon,~e_lat,color="orange",fill=TRUE,fillColor = "blue", opacity = 1,fillOpacity=0.8,weight=1,radius = 10) %>%
addCircleMarkers(data=sz_4,~e_lon,~e_lat,color="black",fill=TRUE,fillColor = "blue", opacity = 1,fillOpacity=0.8,weight =5,radius = 10 )
for(i in 1:nrow(sz)){
#i--画路径
if(i<=nrow(sz) ){
a <- as.numeric(c(sz[i,c(8,10)]));
b <- as.numeric(c(sz[i,c(9,11)]));
A <- A %>% addPolylines(a,b,group=NULL,weight = 1,color = "brown",stroke = TRUE,fill = NULL,opacity = 0.8)
}
if(i==nrow(sz)){print(A)}
}
Sys.sleep(3)
}

Resources