September 30, 2016

Things to do

Install Packages (leaflet,raster,sp)

Go to the console window and type

Install.Packages('sp, leaflet, raster')

The libraries will then load in the console window.Next click on the Packages tab, scroll down the list of packages and tick off the checkbox beside leaflet sp and raster.

Introduction

RStudio is a free and open-source integrated development environment (IDE) for R, a programming language for statistical computing and graphics. A powerful and productive user interface for R. It's free and open source, and works great on Windows, Mac, and Linux.

R package for leaflet serves as a R interface between the leaflet javascript library and the R environment.

R argument explanation of some basic functions

leaflet()%>%
This code will initialize the leaflet map. each line (except the closing code line) is usually followed by a magpipe operator %>%

addTiles() this adds the base map. Default base map is openstreetmaps

setview(lng, lat, zoom) the setview positions the map to the area of interest of the map user as well as setting the initial zoom position when the map is launched.

R argument

Now let us combine these functions to create an R argument. Type the lines below into your console window.Press the Enter key after the last line.

library(leaflet) #calls the functions of the leaflet JS library
leaflet(width = "80%")%>% #option width sets the map width to 80%
setView(8, 9, 6)%>% addTiles() 

Adding features to the map

For our example, we add a point feature using addMarkers in the argument below.

library(leaflet)
leaflet(width = "80%")%>% setView(8, 9, 6)%>%
  addProviderTiles("CartoDB.Positron")%>% #Add tile map from Carto 
addMarkers(7.30, 9.00, popup = "Abuja") #long, lat and popup

Basic functions when adding a shapefile

Here we will require the library(sp) and library(raster)

First we load the shapefile from our local directory into the Rstudio environment tab with the argument as below:

Filename<-shapefile("path to file")

addMarkers() for point features, addPolylines() for line features or addPolygons() for polygon features.

We can also add style options to the layer. e.g. addPolygons(Fill = TRUE, stroke = TRUE, color = "blue", fillOpacity = 0.4)

Example

library(sp)
library(leaflet) 
library(raster)
layer <-shapefile("C:/states shapefiles/fct.shp") 
leaflet(data = layer, width = "70%")%>% setView(8.70, 9.00, 6)%>%
  addTiles(attribution = "overlay data@mapsnigeriainitiative")%>%
  addPolygons(fill = TRUE, stroke = TRUE, color = "yellow")