spof sf packages, or data frames with lattitude/longitude columnsTo install this R package, run this commnad at your R prompt
install.packages("leaflet")
## Installing package into '/home/rstudio-user/R/x86_64-pc-linux-gnu-library/3.6'
## (as 'lib' is unspecified)
You create a Leaftlet map with these basic steps
Create a map widget by calling leaflet().
Add layers (i.e features) to the map by usind layer functions (e.g: addTiles, addMarkers, addPolygons) to modify the map widget
Repeat step 2 as desired
Print the map widget to display it
Here is a basis example:
library(leaflet)
m<- leaflet()%>% addTiles() %>%addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
m #Print the map
leaflet returns a Leaflets map widget. Most functions in this package have an argument mp as their first argument, which makes it easy to use the pipe operatoroptions argument as shown below.leaflet(options= leafletOptions(minZoom=0,maxZoom = 18))
You can manipulate the attributes of the map widget using a series of methods. Please see the help page ?setView for details
setView() sets the enter of the map view and the zoom level
fitBounds() fits the view into the rectangle [lng1, lat1]- [lng2,lat2];
clearBounds() clears the bound, so that the view will be automaticaly determined by the range of latitude/ longitude data in the map layers if provided
Both leaflet() and the map layer functions have an optional data parameter that is designed to receive spatial data in one of several forms:
sp package
SpatialPoints[DataFrame]Line/LinesSpatialLines[DataFrame]Polygon/PolygonsSpatialPolygons[DataFrame]From the **maps** packages
The data argument is used to derive spatial data for functions that need it; for example, if data is a SpatialPolygonsDataFrame object, then calling addPolygons on that map widget will know to add the polygons from that SpatialPolygonsDataFrame
It is straightforward to derive these variables from sp packages since they always represent spatial data in the same way. On the other hand, for a normal matrix or data frame, any numeric column could potentially contain spatial data. So we resort to guessing based on column names
- The latitude variable is guessed by looking for columns named `lat`
You can always explicity identify latitude/ longitude columns by providing `lng` and `lat` arguments to the layer function
For example, we do not specify the values for the argument lat and lng in addCircles() below, but the columns Lat and Long columns (see below for more info on the ~ syntax)
# add some circles to a map
df<- data.frame(Lat=1:10,Long=rnorm(10))
leaflet(df)%>% addCircles()
You can also explicitly specify the Lat and Long columns (see below for more info on the ~ syntax):
leaflet(df)%>% addCircles(lng=~Long,lat=~Lat)
A map layer may use a different data object to override the data providded in leaflet(). We can rewrite the above example as:
leaflet()%>%addCircleMarkers(data=df,lat=~Lat,lng=~Long)
Leaflet supports basemaps using map tiles (setTiles()), popularized by Gooogle Maps and now used by nearly all interactive web maps
The easiest way to add tiles is by calling addTiles() with no arguments; by default, OpenStreetMap tiles are used
Alternatively, many popular free third-party basemaps can be added using the addProviderTiles() function, which is implemented sing the leaflet providers plugin.
As convenience, leaflet also provides a nanmed list of all the third-party tile providers that are supported by the plugin. This enables you to use auto-completion feature of your favourite R IDE (like R studio)
Just type the providers$ and **Choose from one of the options. You can also use names(providers) to view all of the options
m %>% addProviderTiles(providers$CartonDB.Position)
## Custom Tile URL Template
If you happen to have a custom map tile URL template to use, you can provide it as an argumet to addTiles()
You can use addWMSTiles() to add WMS (Web Map Service) tiles. Tha map below shows the Base Reflectivity (a measure of the intensity of precipitation occuring) using the WMS from IOWA
leaflet() %>% addTiles() %>% setView(-93.65, 42.0285, zoom = 4) %>%
addWMSTiles(
"http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi",
layers = "nexrad-n0r-900913",
options = WMSTileOptions(format = "image/png", transparent = TRUE),
attribution = "Weather data © 2012 IEM Nexrad"
)
You aren’t restricted to using a single basemap on a map; you can stack them by adding multiple tile layers. This generally only makes sense if the front tiles consist of semi transparent tiles, or have an adjusted opacity via the options argument.
m%>% addProviderTiles(providers$MtbMap)%>% addProviderTiles(providers$Stamen.TonerLines, options=providerTileOptions(opacity=0.35))%>%addProviderTiles(providers$Stamen.TonerLabels)
Use markers to call out points on the map. Marker locations are expressed in latidude/ longitude coordinates, an can either appear as icons or as circles
Point data for markers can come from a variety of sources:
- `SpatialPoits` or `SpatialPointsDataFrame` objects (from the sp package)
- `POINT, sfc_POINT` and `sf` objects (from `sf` package); only X and Y dimensions will be considered
Example “addMarkers(lng=Longitude,lat=Latitude)”
data(quakes)
leaflet(data=quakes[1:20,])%>% addTiles()%>% addMarkers(lng = ~long,lat = ~lat, popup = ~as.character(mag),label = ~as.character(mag))
You canprovide custom markers in one of several ways, depending on the scenario. FOr each of these ways, the icon can be provided aseither a URL or as a file path
From the simple case of applyying a single icon to a set of markers, use makeIcon()
greenLeafIcon<- makeIcon(
iconUrl="http://leafletjs.com/examples/custom-icons/leaf-green.png",iconWidth = 38, iconHeight = 95, iconAnchorX = 22, iconAnchorY = 94, shadowUrl = "http://leafletjs.com/examples/custom-icons/leaf-shadow.png",shadowWidth = 50,shadowHeight = 64,shadowAnchorX = 4,shadowAnchorY = 62
)
leaflet(data=quakes[1:4,])%>%addTiles()%>% addMarkers(lng = ~long, lat=~lat,icon=~greenLeafIcon)
If you have several icons to apply that vary only by a couple of couple of the parameter (same size but different character). icons function() make this like a dataframe
quakes1<- quakes[1:10,]
leafIcons<- icons(
leafIcons <- icons(
iconUrl = "http://leafletjs.com/examples/custom-icons/leaf-green.png",
"http://leafletjs.com/examples/custom-icons/leaf-red.png"
), iconWidth = 38, iconHeight = 95,
iconAnchorX = 22, iconAnchorY = 94,
shadowUrl = "http://leafletjs.com/examples/custom-icons/leaf-shadow.png", shadowWidth = 50, shadowHeight = 64, shadowAnchorX = 4,shadowAnchorY = 62
)
leaflet(data=quakes1)%>% addTiles()%>% addMarkers(lng=~long,lat=~lat,icon=leafIcons)