A Primer to Creating Interactive Maps with Leaflet in Shiny

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
okay uh thanks jody and josh um i believe i've started sharing my screen so i'll just jump right into it um let's start this slide show so uh we already introduced the what i'll talk about today so let's just jump right into the presentation overview um so like josh mentioned first i'm gonna introduce the project i've been working on in my postdoc briefly and that's working it's a krook tribe led project um and berkeley we're just uh helping out with that project and uh it's focused on roosevelt elk habitat and populations within their ancestral territory in northern california um so in the spring i built a our shiny app as part of a course um run through succinct that i highly recommend dennis said that they may run run this course again next year um so keep an eye out for that might not be through succinct but that was really helpful and really advanced my understanding about shiny very quickly so i built this app as part of that course and to with the idea that it could be used as a decision support tool by the kuruk tribe um kind of to help support fire prescribed burning and wildlife management um so here's a just a quick screenshot of what that app will be and i'll i'll do a walk through that that app uh in the near future but then part two i'm gonna stay in the same study system uh but i've uploaded some dummy data that we'll be using it's not real elk presence data so there's nowhere worries about that sensitive resource and i'll be just live coding in our studio so we might run into some live errors and common pitfalls that i uh i make and hopefully that'll be useful too um all right so to introduce the study system briefly roosevelt elk and the klamath uh were actually extirpated in the 1800s i think the last elk in siskiyou county were seen in the 1870s mostly this was a result of over hunting once euro-american settlers reached the area and the gold rush elk were pretty quickly hunted out and also killed because of foraging on agricultural crops as retaliation another big factor is that uh the kuruk tribe um has for you know since time memorial been doing a lot of management on their landscape um and a lot focused on fire traditional fire practices and uh some of those management practices were focused on improving angular habitat so for for deer and elk and so uh when the you know euro americans arrived there was a lot of uh persecution and eventually um those fire practices were completely outlawed by um us government and we're just now kind of starting to get back into the prescribed burns um so a quick map of this study area here so you can see we're in northwest california just inland from the coast the blue line is crooks ancestral territory um these orange and red lines i have on here are both existing and planned prescribed burns and this kind of furthest inset map on the right here is uh our main study area for this project so most of our elk data comes from this this uh area okay um so one of the big questions in our project has been what are the effects of prescribed burn treatments on elk habitat uh and we went about to answering this question through a series of methods that i'll just briefly uh describe here so first we fit species distribution models to elk scat locations uh collected in 2018 and using uh vegetation cover data remotely sensed at 30 meter resolution with with landsat data as our habitat predictor variables in that species distribution model we then used that model to predict elk habitat suitability um not only in 2018 but also in 2013 um where we also had remotely sensed data available and uh using those two predictions come up with a change in predicted health habitat between and over those five years um so with that kind of change layer we then fit spatial auto regressive models um to predict that change based on the prescribed burns that were done over those five years in those areas as well as some control variables that might affect the vegetation change like elevation and terrain ruggedness and aspect so to quickly talk about the prescribed burns uh we'll be discussing so one of the main ones in the area is these broadcast burns that are kind of uh allowed to spread across the ground in the understory so it's a little bit wider but low intensity burn and then um the other main ones we'll see are the the hand piled burns and also jackpot burns both of those prescribed burn types are more concentrated burns of like gathered fuel um but not really allowed to spread okay so uh what were the results of this um with little surprise to the the kuruk the prescribed burn patterns that we done on the landscape that most resembled kuru traditional ecological knowledge uh maximized elk habitat increases so generally these were broadcast burns group did a lot of these traditionally and cyclical like multi-year broadcast burns that were repeated in an area had the some of the biggest increases in elk habitat um that's likely because elk are generally um preferential grazers even though they're generalists that can eat forage on shrubs as well but they really like these open habitats with meadows a lot of grasses and forbs to forage on and so the broadcast burns kind of open up um the availability for for the those conditions to come back uh just treating a site with hand pile or jackpot burns actually had a negative effect on elf habitat but interestingly if if you we saw that mixed uh jackpot hand pile burns with then multiple years of broadcast burns that had the highest positive effect on elk habitat so probably some benefit of clearing the fuels and then having a broader understory burn um so that was cool to see and um i uh you know good good results for um the kuruk tribe on this project but how might we apply these results um so we've got a very specific study time frame of five years so given current elk habitat conditions we're able to maybe propose a prescribed burn plan in a given area and then predict what that would do to the elk habitat in another five years um so that's the power of this particular model um but to actually do that it's super time intensive to learn you know r coding as i'm sure everyone here is aware um and then to you know code out different treatment plans and predict those effects and try something else is is just uh a lot to ask for managers and even for you know us as study authors um this would take forever um changing that code one one plan at a time um so that's where the power of a shiny app comes in and so we built an app or i built an app like i said this year that allows the users to propose different prescribed burn plans in a given user-drawn area in our study system and then predict the effects of that plan on else habitat change and i think it's a lot easier to comprehend and and visualize with this shiny app uh and i've already gotten some pretty good feedback from the crew tribe and and that they gonna want to put this in front of you know the burn uh planners and so they can take into account wildlife and elk habitat in particular when they're making their plans so as a decision support tool i think shiny apps can be extremely useful in actually connecting the science to the management uh so i'll jump into the app right now uh show you around it let's see i think i've got everything loaded so i'm just to hit run and this is still a work in progress i'm looking at using a dashboard layout right now that i'm kind of liking so the app brings up an introductory page tells the user about the app and how to use it but since i'll be walking through it let's just go right to the explore treatment effects tab so that's going to bring up this map on the top left box here and as you can see i've got a a raster loaded in of um current elk habitat suitability in the study area and you can kind of see it's cropped uh this is to the elks winter range so elk in this region are migratory and we're most worried about their winter habitat that's the most kind of restricted so that's what this study was focused on and uh we've got a you know a background based map that people can you know a manager could orient themselves on you know the main highway uh or you know the creeks or forest roads in the area and the the main functionality here is that once the user you know identifies a area they might want to propose a prescribed burn plan for um they go here to draw a polygon so maybe they notice there's some you know lower looking habitat suitability in this area so maybe they want to propose a burn and this polygon and once they click this finish drawing then a conditional panel pops up um down here called proposed treatment so they've got five years to uh propose and you know they could leave it as completely no treatment but based on study results you know we know that generally the multi-year broadcast burns seem to have a good effect on elf habitat so let's propose a couple years of prescript uh prescribed broadcast burns and then when they click predict change in in habitat suitability um on the server side it's you know predicting our model uh clipping the rasters um to this polygon and then outputting those um predicted uh habitat changes and zooming right to it in this box here so right away the user can see okay there's pretty high predicted changes in um the habitat based on that burn plan and then there's also a little table we spit out to give them a summary of the minimum maximum and mean predicted change um so that's that's where the app is at now um already i think pretty useful but we're hoping to add some further functionality like a download of the results and the proposed you know polygons so if they wanted to a prescribed burn manager could you know download this to a gps and give it to their field crews um and and they could directly start the burn plan with that so um that was the run through and i'm happy to talk about this app more later if you want but i will jump into the second part of the webinar for now and uh before we get coding i think perhaps everyone has some functionality or knowledge of shiny uh but i really liked this overview slide from josh's seminar earlier in the year and i i just kind of stole it because it's a great one to just refresh what shiny is about i think um so say you you know publish a shiny app to the web um over here on the left and uh hopefully we've coded a nice user interface for the the user to look at and make some selection on the app um and then that's pushed to the server which you know can perform some calculation or maybe render a map um working with leaflet and it will return that to the to the user interface and present that to the user so um pretty simple overview but uh i think what i struggled with most you know getting started with these apps is just figuring out how how that connection was happening especially with reactive inputs you know how the ui was talking to the server and to briefly introduce leaflet uh so it's an open source javascript mapping software and if you've ever played around with um like new york times uh mapping uh tools published you know news pieces that's all running on leaflet i think the washington post also uses leaflet as well as map box so a lot of different outlets using leaflet and that way it's kind of like a competitor of google maps in a way um just another option and there's really great functionality with with leaflet um in r and r shiny uh which we'll be talking about today and so that's a big advantage and there's great resources out there for for getting started with leaflet in r and r shiny this is one of them and if you're looking to learn more i highly recommend going through those kind of intro exercises and documents um all right so like i briefly mentioned going to stay in the same study system with this kind of uh interactive coding session a bit simpler data dummy data just elk presence data i'm going to upload and we're starting with the very basic uh leaflet map and then we're going to start adding that data and more interactivity and certain steps so i believe all of that has been uploaded to the github so you can download each script but if you want to start with the base app and work along with me i'm going to try to do some live coding and go from there and yeah i'll just get to the rstudio okay so if we start with our base app dot r script um this is the the basic you know beginning and these are the five packages that we'll need to progress to the the last step that i'm hoping to get to today um but i'll briefly go over what's in this base app so this is like the very beginning of of just having a map so we've got our ui our user interface and the the fluid page is a common like pretty nice layout um that's easy to make for for shiny apps so you'll see it a lot and within that page i've got a title panel i'm calling it map for exploring and our main page is going to be this leaflet um i think thomas yeah we might have lost them temporarily so this will give them a second to connect again oh looks like i dropped off for a second there i'm sorry about that you did you were just starting in on your base code okay yes oh okay so i haven't talked about server yet for everyone or let's see let me share the screen again um okay so yeah uh hopefully this isn't repeating too much that i've just talked about but we've got our main page which is uh a leaflet output and we're the the ui is looking for an output from the the server side so that's gonna be this map here um and as you can see within our server function we've got um an output dollar sign map so that's what we're pushing to the ui and that's a render leaflet function um where we we have our leaflet map and then we're adding a very basic background map in this case with this add provider tiles function and you can choose there's a lot of different loaded background tiles provider tiles and you can quickly kind of search through those by just hitting dollar sign after providers and you know there's a huge list here but we'll just start with the the default kind of first one open street map so with this basic app let's just see what it does i haven't loaded any of our own data we're just kind of um loading a world map here and um already at this level you know there's some interactivity here we the user can can zoom in pan around um and so we might want to zoom over to our study area and start checking things out but there's nothing else going on so let's um add some load some data into the uh global environment and then uh start coding some some stuff for the user to do with the data so i'm gonna load in uh the elk dummy presence data and uh that's a shape file so if you have the raster package i think it's able to work with that using the shape file function and let's see i think i've called that out jittered so if you've downloaded that you can can get that loaded in and we can ignore the spatial warnings for now we're just working with some dummy data okay um so let's take a quick look at that spatial points data frame now um so we've got longitude latitude and then a src that's a data source so some of these points are coming from camera traps hypothetically and some of them are coming from scat presence locations um so i'm first thing i want to do is add some functionality for the user to display different presence points based on where they came from so the way i'm going to do that is in the ui i'm going to add a bit bit more so after the title we're gonna do a sidebar layout and so now there's gonna be like us a side menu and then a main uh display page with the with the sidebar layout um and so on the sidebar panel i'm going to add a picker input so this comes from the shiny widgets package and i think it's like a nice kind of menu for people to select different options and so we're going to have to call this this uh input something for the server to read later so the input id i'm gonna call uh data source because we're gonna you know have them choose either camera or scat and for the user we'll make a little bit nicer of a label i'm just going to say select a data source and then we're going to point to the actual file as to define their choices so that way if we update this file in the future you know it's just going to search that data source column for any unique values and present that to the user as a as choices um all right let's leave it there for now and yeah as far as common pitfalls go i often get really mixed up with the parentheses especially in the ui so as you can see you know i've opened a sidebar layout and um i'm already like oh gosh where where are these errors coming from um so i think what happened here oh this this is a comma is needed to kind of end the sidebar oh that's the sidewalk no comma here okay i think we've fixed it so uh you'll notice in the scripts that i've i've i've published for you everyone is i really like to to hashtag out notes to myself and say okay this is where i'm closing the sidebar layout and this parentheses is where i'm closing the uh you know main uh page or the sidebar panel um but for now let's just keep going with the oops yeah already messed up something with this input so i'm just going to go ahead and jump to face up step one um so we can see this is what it should look like and in addition to defining those choices i i kind of wanted the the user to have something to find for them at the beginning so i'm in the picker input i'm specifying uh selected equals the camera points and i also want the user to be able to choose both camera and scat as or whatever other data sources might come in the future so i'm specifying multiple equals true here um so they can select uh multiple things um okay so now we've got our user interface but there's nothing yet on the server side to actually you know subset out our data and then present that to the to the user so uh to do that we need a reactive expression here um so i'm i'm calling that pres that cell for you know selected data opening the reactive expression and then doing a simple base r subset here so um and and whatever is being subseted i'm pointing to uh that user input so the input dollar sign data source is gonna have the server look for this picker input which you know we've defined our input id up here so that's what the server is looking for so we're sub setting that out and then returning the resulting data set in this reactive expression um okay so moving on to the actually showing this to the user um i've added we've piped in another line here um after the base map and we're adding circle markers um for the points where i think those work pretty well for any kind of point shape file uh and we just you know point to the data and another common pitfall is within these reactive expressions you actually have to um open and close a parenthesis to to point to the what you're returning inside there and um for color i'm yeah if if you remember when i hit head i've kind of pre-computed what colors i want the scat versus camera data to be so um i'm just pointing to that um column here so you can see there's a column called color and so um that's what the circle markers function is going to look for to color these points all right then finally i think every map should probably add scale bar and and just the basic scale bar in leaflet is really nice it'll update you know if you're zooming in or out um to help orient the user a little bit better and then finally i'm also adding a very basic legend for the user um just to be able to differentiate the what the green and blue circle markers are actually representing which is the the camera and scat points okay um so let's see how it looks after we've added all this all right so now we're you know we're zoomed in to the the camera points because that was our default uh menu option we defined uh we can add scat points and we can see you know the legend is telling us which are which and those markers are kind of automatically updating as well as we zoom in and out so some pretty cool functionality but we're still you know basically uh some kind of a gis uh application here where we're not really running um anything in the background and the true power of the our shiny apps is that you know the whole host of open source our packages out there are available to you to run on the server side and do whatever you want so let's um start adding a little more functionality uh bring in some some spatial packages and and do some work on the server side uh so i thought it'd be cool to add the ability for the user to buffer these points um by a certain distance that they may want and then uh you know click a button to to run create the buffer and then present to them what that buffer looks like uh so in order to do that let's start on the ui side again our user interface and i'm going to add a what's called a slider input so that's going to define for the user um how far they want to buffer those presence selected presence points by uh so back to live coding here uh we're gonna call it um buff distance something straightforward to use in the server later and for the user we'll label it something a little same thing but just nicer to look at um and then we're going to need a minimum value a maximum value and default um so this is in in meters which by default which i'll keep keep that the raster buffer function that is uh so we'll start with 0 meters we'll say let's let them go up to ten thousand meters for ten kilometers and we'll leave it at a default value of uh say 400 or so um so there's our slider input um but i don't want this to just be creating buffers whenever they you know slide around on this input i want them to you know choose something and then have to click an action button to actually create the buffer so let's add an action button to this uh sidebar panel and we'll just call this create buffer for the server to read and and for the user again just a little bit nicer of a label um okay so i think our ui should be nice and updated but now let's actually start using um those user inputs on the server side um so now we're gonna need to create a an event reactive so this is relying this function is relying on both this uh presence data reactive data set and also on the user clicking that action button so um what we'll call that this one a presdat buffer and let's make it a event reactive that's going to rely on a couple things i just mentioned so we've got our pres that cell reactive data and also the input of the user clicking create buffer so once those conditions are are met this uh code will run and we're gonna put the that buffer function from the raster package in there so we'll say prez buff is and i always like to specify the raster package i've run into problems with other packages having buffer functions and messing me up before but we're only going to buffer what data the user selects so we're going to once again point to that reactive data set and then we're going to buffer it by whatever that slider input ends up being so the input dollar sign buff distance and then we'll return the that buffer um in this event reactive expression okay so that's all and good but um we're still again once again not presenting that to the user in the leaflet map we have to add that functionality as well and um instead of adding that to the map it's directly within this render leaflet i'm going to create an observe event um and just add instead of redrawing the whole map we'll just add to the existing map so that that should really streamline things so here's our beginning of our observe um and i'm also going to add a couple requirements to this observe event and that's because if you uh don't require for example that um action button to be clicked uh you can run into some some errors where it's trying to to um you know add this this buffer line that's not there and it'll it'll crash out so uh let's require the action button being clicked buffer let's also require that there be some data at all selected because we don't want to run a buffer on nothing and error out that way too so the way i'm going to do this is just look at the number of rows in our reactive data set make sure that's more than zero okay and after that will finally open up a leaflet proxy um so this this is like i was mentioning earlier not creating a new map just adding to our existing render leaflet function map so that's why we specify this map here and let's type in the the actual addition of the buffer line so first i want to actually clear any previous buffer lines uh that are drawn so i don't want you know the map getting super messy with a ton of different lines every time the user proposes a new buffer and finally add polylines pointing to that uh event reactive data set i think thomas rose again yeah i hope he uh comes back pretty quick okay hi everybody sorry about that i've switched to my phone hotspot because something is going on with the the wi-fi uh i hope this still is enough uh bandwidth to uh present this um so i think we left off where we just tried to code out the buffer um addition of a buffer distance to the to the leaflet and um so let's just go ahead and and run that okay so now we've got our our slidey slider input where we can drag uh the user can drag this this circle along the bar to propose a different buffer distance um so maybe they want about a 5 000 meter buffer and maybe they want that with just the scat points so they can come in here click the create buffer and then there we go that triggers all the reactive expressions and this buffer is created and presented in the leaflet map um so we're getting to some pretty cool functionality here maybe you know the user is trying to select some area to run a species distribution model it needs like to understand the background conditions and they might hypothesize that some distance around the presence points is a biologically meaningful background area um and it's like an easy way to explore that visually so there we tried a slightly smaller buffer um all right so before i talk i want or end the talk i wanted to um take one more step um but a couple more complicated uh lines of code are needed in this so i instead of typing this out in the instance of top interest of time i'm just going to jump right to the final step of this base app and what i wanted to do here was it use some of the cool functionality that leaflet has directly on the render leaflet function and particularly allowing the user to draw cert certain shapes um that can then be read and used on the the server side so um let's see i'll start down at the server here um so what i've done is in our uh you know main map output i've added a draw toolbar um as the last option and so a lot of lines here but mostly this is just getting rid of some of the drawing options i just want the like for my uh prescribed burn app i just wanted them to be able to draw polygons so i've set that as true here and so that uh you know i'll just show that real quick that immediately brings up this drawing option on the leaflet so here we go it's there's a draw polygon option and like in the burn app the user can select points and then finish the polygon but we still haven't added anything for the user to do with that so i thought it would be cool if uh we're letting the user uh you know propose a polygon and then cropping the presence data to that polygon um so to do that and on the server side we actually need to access that whatever the user has drawn um and that kind of i found to be a bit complicated there may be a better way to do this that's prettier to look at but i know that this at least works where um the the user's drawn polygon is actually added into the input as map draw new feature and we can access the geometry and the coordinates of that shape and if we do that on the server side you know we can of course start working with with that data and do whatever we want within r um so i'm uh basically going through the rather complicated steps to make an sp polygon from the sp package spatial polygon um and so at the end of this step we have our spatial polygons and then i just wanted to run the basic crop function on um the whatever presence data has been selected by the user and crop it to to the polygon that they drew um so that's kind of a long uh a bunch of lines to get to this somewhat simple result in a within an event reactive but it is a cool feature that you can do with with leaflet um and once again instead of adding that to our main render leaflet function we're going to do an observe uh function where we require the user to hit an action button that we're going to create uh we need there to be something in that data set cropped data points and once there there is something we'll open up another leaflet proxy to that main map add the circle markers um and just color them purple so they can differentiate from the the main green and blue points okay uh so just to quickly show uh what that looks like on the ui side let's scroll back up um so i've done at times when maybe there's a lot going on in the shiny app and you don't necessarily want the user to see all your menus until they you know have started interacting with the app so this conditional panel i've coded to show up once um the user actually draws a polygon and clicks finish um so that condition is is met here by this output.crop um on the server end and just to show you how to add that it's just a event reactive that that looks for that drawn map feature and then sets crop to true once it happens um okay and then once that happens we just have another action button pop up conditionally to to begin that that crop um series of functions okay so finally let's let's see what the end result is go through the whole process um so yeah maybe maybe the user's interested in in just the northern end of the study area and just the camera data so they might just want to crop out those data like so they finish their polygon and then up comes this conditional button that says crop the data to the polygon and here we go we've got our our cropped points and those are presented to the user and purple here um so that's about all i had i wanted to go through some of the cool functionality that leaflet has i'll definitely be available for questions um as long as i'm needed thanks a lot for coming and i'm sorry for the some of the internet problems that i had i hope that uh it's been somewhat cohesive um and useful see i'll start my share for now oh thanks thomas that was a great presentation i'll uh see what questions we have at the moment um the first being what function is or what package is this the shapefile function and that you were using oh uh yeah that should be in the sd package but raster should load that i i always like to load raster because it loads some other dependent dependencies um so yeah if if for some reason that's not working you could try just to load sp directly i think it's in there um and while i'm talking also i if there was a part that i thought i was presenting but i was you know dropping out please let me know i can go over that real quick if that was unclear maybe it would be helpful to tell folks about some of the uh the conflicts that you mentioned briefly between like raster and sp and other and other packages and and how you figured that out that that was an issue oh sure yeah so once in a while you know you'll try to use a function and uh be expecting some outcome and it just is completely not what you're expecting or just errors out by default and when that happens i just like to specify exactly what package i want to call from with uh by typing out the package and then the two colons and then it'll know our nose to look for the function within that package that you're using um but yeah there's a lot of cases where there's like five different packages you know using as an exaggeration the same function um so it's good to watch out for that well i think that was the only question well another one okay uh will leaflet work with uh the terror package and just asked do you know um yeah i think you can well so i don't know anything about the terror package so i can't speak to that but sf it will it'll definitely work you know you can do a lot i think josh you are using sf and leaflet in your presentation um and it yeah sf ii i think is gaining a lot more popularity more quickly than sp i've just traditionally used sp um more than sf because of its easy compatibility with the raster package which has like just a ton of cool spatial functions for for rasters and also vector data um [Music] so that's why i've been using sp but i think sf would work just fine for most if not all of the functions yeah i think my experience was that um sp i think has a little more uh functionality or supported better by leaflet and sf you gotta kind of rig things up a little bit sometimes um so that was yeah just my experience trying to do that stuff um okay there's another question asking regarding your last r script to the step three is it using the draw underscore stop event to detect when users are finished drawing or just the action button the begin crop uh okay let me bring up that step three scripts um okay sorry so the question was what is it looking for to detect uh when the user stops drawing was that uh yeah so um is it using the draw stop events to detect when they're finished or um like if you have to click an action button for it to detect that it's done oh gotcha no um it you don't have to click an action button directly i just it kind of when you click finish within the draw tool bar it it registers that as the end of the user drawing and you can access that with uh well okay yeah that's another i guess a good point i should have gone over a little bit more i was a little rushing at the end but so the way to hold on let me share my screen again um so in my case uh so the user clicks finish and it um then i have an event reactor that sorry an event reactive that is looking for that in the input so that's stored here the input dollar sign map draw new feature so when the and then i have it so that when the user clicks finish and it's logged in there um i have this this kind of conditional crop equals true come up but i guess that's only needed because i wanted to have the conditional panel um if you just wanted the button to be up there you don't really have to worry about you know register registering on the server side when the user's finished drawing through some reactive like this um yeah all right i think that might be all the questions from paul everywhere um i guess if anybody else has a question uh feel free to ask if you want or pour it out to the chat or pull everywhere um come anything last minute yeah since we're at the top of the hour people can feel free to leave if they need to but we can also open it up if anyone has questions yeah it looks like there's some talk in the chat about the the succinct class that i took and i'll just put another plug-in for that that was run by dennis and uh lindsay who are here um there was another guy helping too i think um but yeah that that was a really good course and hopefully they're able to offer that again through you know if not to sync somewhere else um because you know i was complete never had touched shiny before starting that that workshop and it was able to get to like what i was felt was a pretty useful um app by the end of it as a and that was focused on decision support tools which i think is such a powerful use case for shiny all right well if that's it then i guess we're done um just thank you again to thomas um for rounding out this this webinar series and hopefully we'll be able to have some uh either future webinars or a short course in the in the near future all right well thanks a lot everyone for coming
Info
Channel: Ecological Forecasting
Views: 151
Rating: undefined out of 5
Keywords:
Id: f2sBa69kq3s
Channel Id: undefined
Length: 54min 1sec (3241 seconds)
Published: Wed Sep 15 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.