\(~\)
\(~\)
\(~\)
\(~\)
The material covered in class and the resources gave very through examples of leaflet maps. One exemption is leaflet plugins. Most of the examples of leaflet plugins that have been integrated into R via leaflet extra are URL’s that have stoped working. In this section we will show the implementation of various leaflet plugins that are taken from the leaflet extra repository made by Bhaskar V. Karambelkar. The codes are imported from there.
The examples will both serve to illustrate the use of the different leaflet plugins but also to show different implementations of leaflet maps in R. In particular, note the various types of formatting of the labels which is something that was not covered in class.
The section will be divided in three parts: - A) Plugins that allow to load different types of data. - B) Draw and measure. - C) Others
Some of the examples are related group projects topics (ie. Restaurants).
Why would we directly use CSV data into a leaflet map?
Ease of use: A CSV (comma-separated values) file is a simple and open file format that stores tabular data in plain-text form. Virtually all spreadsheet and database software can import/export this file format.
Save bandwidth: When used to display markers, GeoJSON files can be up to four times as large as a CSV file containing the same information. This plugin provides the ability to download a CSV file that is then parsed into a GeoJSON document on the client side, saving you bandwidth and reducing load times. In similar scenarios, we recommend using GeoCSV together with MarkerCluster as in the Bankia Offices Map Example.
(Ref: Leaflet Geo repo)
# Point Data: Nearyly 50K World Airports
fName <- system.file("examples/data/csv/world_airports.csv.zip", package = "leaflet.extras")
csv <- readr::read_file(fName)
# Data Wrangling
leaf <- leaflet() %>%
setView(0, 0, 2) %>%
addProviderTiles(providers$CartoDB.DarkMatterNoLabels)
# Example - 50K airports.
leaf %>%
addCSV(
csv,
csvParserOptions("latitude_deg", "longitude_deg"),
markerType = "circleMarker",
stroke = FALSE, fillColor = "red", fillOpacity = 1,
markerOptions = markerOptions(radius = 0.5))
“GeoJSON is a format for encoding a variety of geographic data structures. GeoJSON supports the following geometry types: Point, LineString, Polygon, MultiPoint, MultiLineString, and MultiPolygon. Geometric objects with additional properties are Feature objects. Sets of features are contained by FeatureCollection objects.” (geojson.org)
“JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and transporting data.” (w3schools). See more information here.
The examples show different ways to integrate this type of data into R. We will not look into the details, but note some intresting formatting.
#### Current file: examples/geojsonv2.R
leaf <- leaflet() %>%
addProviderTiles(providers$CartoDB.Positron)
# Plot Polygons
# Example 1: Pre-processing in R
# Here we explicitly convert the GeoJSON to an R List, add a bunch of styling and popup content. This approach is similar to how `leaflet::addGeoJSON` works, but with added advantage of being able to customize popups/labels/markers/highlighting etc.
# Read as a R list
fName <- "https://rawgit.com/benbalter/dc-maps/master/maps/ward-2012.geojson"
geoJson <- jsonlite::fromJSON(readr::read_file(fName))
factpal <- colorFactor(topo.colors(nrow(geoJson$features$properties)),
geoJson$features$properties$NAME)
# Generate one HTML Table per feature with all properties of a feature.
geoJson$features$properties <-
dplyr::rowwise(geoJson$features$properties) %>%
dplyr::do({
result = dplyr::as_data_frame(.)
result$popup = purrr::map_chr(
htmlTable::htmlTable(
t(result),
caption = "Ward Details",
align = "left",
align.header = "left",
col.rgroup = c("#ffffff", "#eeeeee")), ~as.character(.))
result
})
geoJson$features$properties$style = purrr::map(factpal(geoJson$features$properties$NAME), ~list(fillColor = ., color = .))
leaf %>% setView(-77.0369, 38.9072, 11) %>%
addGeoJSONv2(
jsonlite::toJSON(geoJson), weight = 1, fillOpacity = 0.6,
popupProperty = "popup", labelProperty = "NAME",
highlightOptions = highlightOptions(
weight = 2, color = "#000000",
fillOpacity = 1, opacity = 1,
bringToFront = TRUE, sendToBack = TRUE))
# Examples 2 and 3
#' Here we show two different approaches to styling polygons. In 2 we style the polygons similar to example 1 i.e. read data in R and do the styling in R. In example 2 we show an alternate way by using `addGeoJSONChoropleth` and doing the styling entirely in the browser. Example 3 shows how easy it is to customize and plot GeoJSON data.
fName <- "https://raw.githubusercontent.com/MinnPost/simple-map-d3/master/example-data/world-population.geo.json"
geoJson <- jsonlite::fromJSON(readr::read_file(fName))
leaf.world <- leaflet(
options = leafletOptions(
maxZoom = 5,
crs = leafletCRS(
crsClass = "L.Proj.CRS", code = "ESRI:53009",
proj4def = "+proj=moll +lon_0=0 +x_0=0 +y_0=0 +a=6371000 +b=6371000 +units=m +no_defs",
resolutions = c(65536, 32768, 16384, 8192, 4096, 2048)))) %>%
addGraticule(style = list(color = "#999", weight = 0.5, opacity = 1, fill = NA)) %>%
addGraticule(sphere = TRUE, style = list(color = "#777", weight = 1, opacity = 0.25, fill = NA)) %>%
addEasyButton(easyButton(
icon = "ion-arrow-shrink",
title = "Reset View",
onClick = JS("function(btn, map){ map.setView([0,0],0); }"))) %>%
setMapWidgetStyle(list(background = "white"))
# Example 2
#' Similar example to the example 1, but with a custom projection.
geoJson$features$properties$POP_DENSITY <-
as.numeric(geoJson$features$properties$POP2005) /
max(as.numeric(geoJson$features$properties$AREA), 1)
pal <- colorNumeric(
colormap::colormap(colormap::colormaps$copper, nshades = 256, reverse = TRUE),
geoJson$features$properties$POP_DENSITY)
# Generate one HTML Table per feature with all properties of a feature.
geoJson$features$properties <-
dplyr::rowwise(geoJson$features$properties) %>%
dplyr::do({
result = dplyr::as_data_frame(.)
result$popup = purrr::map_chr(
htmlTable::htmlTable(
t(result),
caption = "Ward Details",
align = "left",
align.header = "left",
col.rgroup = c("#ffffff", "#eeeeee")), ~as.character(.))
result
})
geoJson$features$properties$style = purrr::map(pal(geoJson$features$properties$POP_DENSITY), ~list(fillColor = .))
leaf.world %>%
addGeoJSONv2(
rmapshaper::ms_simplify(geojsonio::as.json(geoJson)),
weight = 1, fillOpacity = 0.8, color = "#ffffff",
popupProperty = "popup", labelProperty = "NAME",
highlightOptions = highlightOptions(
weight = 2, color = "#000000",
fillOpacity = 1, opacity = 1,
bringToFront = TRUE, sendToBack = TRUE))
# Example 3
#' This is the same data and same visualization as example 2, but here we use `addGeoJSONChoropleth` instead of `addGeoJSONv2`. This allows us to generate our polygon style on the fly in the browser, with no pre processing required on the R side.
# The geojson in question has some invalid geometry which needs to be fixed before we can use it in a custom projection.
geoJson <- geojsonio::as.json(geoJson) %>%
rmapshaper::ms_simplify()
#' The options `valueProperty`, `scale`, `mode`, `steps` are for the choropleth generation.
#' `valueProperty` can be a simple property or a JS function that computes a value as shown below.<br/>
#' In addition you can specify `labelProperty` & `popupProperty` both of which can be simple property names or functions that generate string/HTML.
leaf.world %>%
addBootstrapDependency() %>%
addGeoJSONChoropleth(
geoJson,
# Calculate the Population Density of each country
valueProperty =
JS("function(feature) {
return feature.properties.POP2005/Math.max(feature.properties.AREA,1);
}"),
scale = c("#ffc77fff", "#000000ff"), mode = "q", steps = 5,
# Select the data attributes to show in the popup.
popupProperty = propstoHTMLTable(
props = c("NAME", "REGION", "ISO_3_CODE", "ISO_2_CODE", "AREA", "POP2005"),
table.attrs = list(class = "table table-striped table-bordered"), drop.na = T),
labelProperty = "NAME",
color = "#ffffff", weight = 1, fillOpacity = 0.9,
highlightOptions = highlightOptions(
fillOpacity = 1, weight = 2, opacity = 1, color = "#ff0000",
bringToFront = TRUE, sendToBack = TRUE),
legendOptions = legendOptions(title = "Pop. Density")
)
# Example 5
#' Here we plot GeoJSON with Point data using customized markers
jsURL <- "https://rawgit.com/Norkart/Leaflet-MiniMap/master/example/local_pubs_restaurant_norway.js"
v8 <- V8::v8()
v8$source(jsURL)
geoJson <- v8$get("pubsGeoJSON")
# Is it a pub or a restaurant?
icons <- awesomeIconList(
pub = makeAwesomeIcon(icon = "glass", library = "fa", markerColor = "red"),
restaurant = makeAwesomeIcon(icon = "cutlery", library = "fa", markerColor = "blue")
)
leaf %>%
setView(15, 65, 5) %>%
addGeoJSONv2(
jsonlite::toJSON(geoJson),
labelProperty = "name",
markerIcons = icons, markerIconProperty = "amenity",
markerOptions = markerOptions(riseOnHover = TRUE, opacity = 0.75),
clusterOptions = markerClusterOptions())
# Example 6
#' Here we plot arts/cultural places and historic places in Washington DC. Notice that we are not loading the GeoJSONs in R, but directly downloading them and parsing them int the browser. We are also specifying popups content to be generated from the feature properties. We are also using marker clustering to cluster our points.
artsAndCultures <- "https://rawgit.com/benbalter/dc-maps/master/maps/arts-and-culture-organizations-as-501-c-3.geojson"
historicLandmarks <- "https://rawgit.com/benbalter/dc-maps/master/maps/historic-landmarks-points.geojson"
artsAndCulture <- makeAwesomeIcon(icon = "paintbrush", library = "ion", markerColor = "red", iconColor = "black")
historicLandmark <- makeAwesomeIcon(icon = "flag", library = "ion", markerColor = "green", iconColor = "black")
leaf %>% setView(-77.0369, 38.9072, 12) %>%
addBootstrapDependency() %>%
addGeoJSONv2(
artsAndCultures,
labelProperty = "NAME",
popupProperty = propstoHTMLTable(
table.attrs = list(class = "table table-striped table-bordered"), drop.na = T),
labelOptions = labelOptions(textsize = "12px", direction = "auto" ),
markerIcons = artsAndCulture,
markerOptions = markerOptions(riseOnHover = TRUE, opacity = 1),
clusterOptions = markerClusterOptions(), group = "Arts/Culture") %>%
addGeoJSONv2(
historicLandmarks,
labelProperty = "LABEL",
popupProperty = propstoHTMLTable(
table.attrs = list(class = "table table-striped table-bordered"), drop.na = T),
labelOptions = labelOptions(textsize = "12px", direction = "auto" ),
markerIcons = historicLandmark,
markerOptions = markerOptions(riseOnHover = TRUE, opacity = 1),
clusterOptions = markerClusterOptions(), group = "Historic Landmarks") %>%
addLayersControl(
overlayGroups = c("Arts/Culture", "Historic Landmarks"),
options = layersControlOptions(collapsed = F))
# Example 7
# This time in addition to the points we also plot the heatmap
fName <- "https://rawgit.com/benbalter/dc-maps/master/maps/historic-landmarks-points.geojson"
geoJson <- readr::read_file(fName)
leaflet() %>% setView(-77.0369, 38.9072, 12) %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addWebGLGeoJSONHeatmap(
geoJson, size = 30, units = "px"
) %>%
addGeoJSONv2(
geoJson,
markerType = "circleMarker",
stroke = FALSE, fillColor = "black", fillOpacity = 0.7,
markerOptions = markerOptions(radius = 2))
Allows to use GPX data.
“GPX, or GPS exchange format, is an XML file format for storing coordinate data. It can store waypoints, tracks, and routes in a way that is easy to process and convert to other forms. All GPS data used by OpenStreetMap is converted to GPX format before it can be uploaded.” (Wiki opeenstreetmap)
# Data Wrangling
airports <- readr::read_file(
system.file("examples/data/gpx/md-airports.gpx.zip", package = "leaflet.extras"))
towns <- readr::read_file(
system.file("examples/data/gpx/md-towns.gpx.zip", package = "leaflet.extras"))
# Map
leaflet() %>%
addBootstrapDependency() %>%
setView(-76.6413, 39.0458, 8) %>%
addProviderTiles(providers$CartoDB.Positron,
options = providerTileOptions(detectRetina = T)) %>%
addWebGLGPXHeatmap(airports, size = 20000, group = "airports", opacity = 0.9) %>%
addGPX(airports,
markerType = "circleMarker",
stroke = FALSE, fillColor = "black", fillOpacity = 1,
markerOptions = markerOptions(radius = 1.5),
group = "airports") %>%
addWebGLGPXHeatmap(towns, size = 15000, group = "towns", opacity = 0.9) %>%
addGPX(towns,
markerType = "circleMarker",
stroke = FALSE, fillColor = "black", fillOpacity = 1,
markerOptions = markerOptions(radius = 1.5),
group = "towns") %>%
addLayersControl( baseGroups = c("airports", "towns"),
options = layersControlOptions(collapsed = FALSE))
“KML is a file format used to display geographic data in an Earth browser such as Google Earth. KML uses a tag-based structure with nested elements and attributes and is based on the XML standard. All tags are case-sensitive and must appear exactly as they are listed in the KML Reference. The Reference indicates which tags are optional. Within a given element, tags must appear in the order shown in the Reference.” (Google Developers)
fName <- system.file("examples/data/kml/crimes.kml.zip", package = "leaflet.extras")
kml <- readr::read_file(fName)
leaflet() %>% setView(-77.0369, 38.9072, 12) %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addWebGLKMLHeatmap(kml, size = 20, units = "px") %>%
addKML(
kml,
markerType = "circleMarker",
stroke = FALSE, fillColor = "black", fillOpacity = 1,
markerOptions = markerOptions(radius = 1))
#' ## Shape Data
#' We plot US states. Notice the convenient "propsToHTMLTable" function for pretty popups.
fName <- system.file("examples/data/kml/cb_2015_us_state_20m.kml.zip",
package = "leaflet.extras")
kml <- readr::read_file(fName)
leaflet() %>%
addBootstrapDependency() %>%
setView(-98.583333, 39.833333, 4) %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addKMLChoropleth(
kml,
valueProperty = JS(
"function(feature){
var props = feature.properties;
var aland = props.ALAND/100000;
var awater = props.AWATER/100000;
return 100*awater/(awater+aland);
}"),
scale = "OrRd", mode = "q", steps = 5,
padding = c(0.2, 0),
popupProperty = "description",
labelProperty = "NAME",
color = "#ffffff", weight = 1, fillOpacity = 1,
highlightOptions =
highlightOptions(fillOpacity = 1, weight = 2, opacity = 1, color = "#000000",
bringToFront = TRUE, sendToBack = TRUE),
legendOptions = legendOptions(
title = "% of Water Area",
numberFormatOptions = list(style = "decimal",
maximumFractionDigits = 2))
)
Plugin that allows you to define and draw patterns in a map.
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(cities) %>% addTiles() %>%
addCircles(lng = ~Long, lat = ~Lat, weight = 1,
radius = ~sqrt(Pop) * 30, label = ~City, group = "cities") %>%
addDrawToolbar(
targetGroup = "cities",
editOptions = editToolbarOptions(selectedPathOptions = selectedPathOptions())) %>%
addLayersControl(overlayGroups = c("cities"), options =
layersControlOptions(collapsed = FALSE)) %>%
addStyleEditor()
Draw geodesic lines and circles. A geodesic line is the shortest path between two given points on the earth surface. It uses Vincenty’s formulae for highest precision and distance calculation.
# Generates a set of cities.
berlin <- c(52.51, 13.4)
losangeles <- c(34.05, -118.24)
santiago <- c(-33.44, -70.71)
tokio <- c(35.69, 139.69)
sydney <- c(-33.91, 151.08)
capetown <- c(-33.91, 18.41)
calgary <- c(51.05, -114.08)
hammerfest <- c(70.67, 23.68)
barrow <- c(71.29, -156.76)
# Generates a Dataset
df <- as.data.frame(rbind(hammerfest, calgary, losangeles, santiago, capetown, tokio, barrow))
names(df) <- c("lat", "lng")
#Map
leaflet(df) %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addGeodesicPolylines(lng = ~lng, lat = ~lat, weight = 2, color = "red",
steps = 50, opacity = 1) %>%
addCircleMarkers(df, lat = ~lat, lng = ~lng, radius = 3, stroke = FALSE, fillColor = "black", fillOpacity = 1)
Show measurements on paths; polylines, polygons and circles currently supported.
# Example 1:
fName <- "https://rawgit.com/benbalter/dc-maps/master/maps/ward-2012.geojson"
geoJson <- readr::read_file(fName)
leaflet() %>% addTiles() %>% setView(-77.0369, 38.9072, 11) %>%
addBootstrapDependency() %>%
enableMeasurePath() %>%
addGeoJSONChoropleth(
geoJson,
valueProperty = "AREASQMI",
scale = c("white", "red"), mode = "q", steps = 4, padding = c(0.2, 0),
labelProperty = "NAME",
popupProperty = propstoHTMLTable(
props = c("NAME", "AREASQMI", "REP_NAME", "WEB_URL", "REP_PHONE", "REP_EMAIL", "REP_OFFICE"),
table.attrs = list(class = "table table-striped table-bordered"), drop.na = T),
color = "#ffffff", weight = 1, fillOpacity = 0.7,
highlightOptions = highlightOptions(
weight = 2, color = "#000000",
fillOpacity = 1, opacity = 1,
bringToFront = TRUE, sendToBack = TRUE),
pathOptions = pathOptions(
showMeasurements = TRUE,
measurementOptions = measurePathOptions(imperial = TRUE)))
# Example 2: Dynamically show/hide measurements
leaflet() %>% addTiles() %>% setView(-77.0369, 38.9072, 11) %>%
addBootstrapDependency() %>%
addGeoJSONChoropleth(
geoJson,
valueProperty = "AREASQMI",
scale = c("white", "red"), mode = "q", steps = 4, padding = c(0.2, 0),
labelProperty = "NAME",
popupProperty = propstoHTMLTable(
props = c("NAME", "AREASQMI", "REP_NAME", "WEB_URL", "REP_PHONE", "REP_EMAIL", "REP_OFFICE"),
table.attrs = list(class = "table table-striped table-bordered"), drop.na = T),
color = "#ffffff", weight = 1, fillOpacity = 0.7,
highlightOptions = highlightOptions(
weight = 2, color = "#000000",
fillOpacity = 1, opacity = 1,
bringToFront = TRUE, sendToBack = TRUE)) %>%
addMeasurePathToolbar(options = measurePathOptions(imperial = TRUE, showDistances = FALSE))
#' Example 3: With Draw
#' You can update the measurements after editing by clicking on the refresh button of the measure path toolbar.
library(rbgm)
set.seed(2)
## pick one of the available model files
fs <- sample(bgmfiles::bgmfiles(), 1)
## read the model, and convert to Spatial (box for polygons, face for boundary lines)
model <- boxSpatial(bgmfile(fs))
## most of the BGM models will be in a local map projection
model <- spTransform(model, "+init=epsg:4326")
#+ fig.width=10, fig.height=8
leaflet() %>% addTiles() %>%
addPolygons(data = model, group = "model") %>%
addDrawToolbar(targetGroup = "model",
editOptions = editToolbarOptions(
selectedPathOptions = selectedPathOptions())) %>%
addLayersControl(overlayGroups = c("model"), options =
layersControlOptions(collapsed = FALSE)) %>%
addMeasurePathToolbar(options =
measurePathOptions(imperial = TRUE,
minPixelDistance = 100,
showDistances = FALSE))
london_crimes_files <- Sys.glob(
paste0(system.file("examples/data/London-Crimes", package = "leaflet.extras"),
"/*/*-city-of-london-street.csv.zip"))
london_crimes <- suppressMessages(
purrr::map(
london_crimes_files,
~readr::read_csv(.) %>%
dplyr::select(Latitude, Longitude) %>%
dplyr::filter(!is.na(Latitude))) %>%
magrittr::set_names(basename(Sys.glob(
paste0(system.file("examples/data/London-Crimes", package = "leaflet.extras"),
"/2016*")))))
leaf <- leaflet() %>%
addProviderTiles(providers$CartoDB.Positron)
purrr::walk(
names(london_crimes),
function(month) {
leaf <<- leaf %>%
addHeatmap(
data = london_crimes[[month]],
layerId = month, group = month,
lng = ~Longitude, lat = ~Latitude,
blur = 20, max = 0.05, radius = 15)
})
leaf %>%
setView(-0.094106, 51.515, 14) %>%
addLayersControl(
baseGroups = names(london_crimes),
options = layersControlOptions(collapsed = FALSE)
)
Renders pulsing icon.
# Example 1
leaf <- leaflet() %>% addTiles()
leaf %>%
addPulseMarkers(
lng = -118.456554, lat = 34.078039,
label = "This is a label",
icon = makePulseIcon(heartbeat = 0.5))
# Example 2
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"))
cities <- cities %>% mutate(PopCat = ifelse(Pop < 500000, "blue", "red"))
leaflet(cities) %>% addTiles() %>%
addPulseMarkers(lng = ~Long, lat = ~Lat,
label = ~City,
icon = makePulseIcon())
# Example 3
icon.pop <- pulseIcons(color = ifelse(cities$Pop < 500000, "blue", "red"),
heartbeat = ifelse(cities$Pop < 500000, "0.8", "0.4"))
leaflet(cities) %>% addTiles() %>%
addPulseMarkers(lng = ~Long, lat = ~Lat,
label = ~City,
icon = icon.pop)
# Example 4
# Make a list of icons (from two different icon libraries).
# We'll index into it based on name.
popIcons <- pulseIconList(
blue = makePulseIcon(color = "blue"),
red = makePulseIcon(color = "red")
)
leaflet(cities) %>% addTiles() %>%
addPulseMarkers(lng = ~Long, lat = ~Lat,
label = ~City,
labelOptions = rep(labelOptions(noHide = T), nrow(cities)),
icon = ~popIcons[PopCat] )
Allows you to interactively seach for the polygons or markers in your map.
# Example 1 - Pubs and Restaurants.
jsURL <- "https://rawgit.com/Norkart/Leaflet-MiniMap/master/example/local_pubs_restaurant_norway.js"
v8 <- V8::v8()
v8$source(jsURL)
geoJson <- v8$get("pubsGeoJSON")
# Is it a pub or a restaurant?
icons <- awesomeIconList(
pub = makeAwesomeIcon(icon = "glass", library = "fa", markerColor = "red"),
restaurant = makeAwesomeIcon(icon = "cutlery", library = "fa", markerColor = "blue")
)
leaflet() %>% addProviderTiles(providers$Esri.WorldStreetMap) %>%
addBootstrapDependency() %>%
setView(15, 65, 5) %>%
addGeoJSONv2(
jsonlite::toJSON(geoJson),
labelProperty = "name",
popupProperty = propstoHTMLTable(
table.attrs = list(class = "table table-striped table-bordered"), drop.na = T),
markerIcons = icons, markerIconProperty = "amenity",
markerOptions = markerOptions(riseOnHover = TRUE, opacity = 0.75),
clusterOptions = markerClusterOptions(),
group = "pubs") %>%
addResetMapButton() %>%
addSearchFeatures(
targetGroups = "pubs",
options = searchFeaturesOptions(
propertyName = "name", zoom = 18, openPopup = TRUE, firstTipSubmit = TRUE,
autoCollapse = TRUE, hideMarkerOnCollapse = TRUE )) %>%
addControl("<P>Search for pub/restaurants<br/>in Norway by name.</P>",
position = "bottomright")
# Example 2 - Population Density.
# GeoJSON w/ Polygons ----
fName <- "https://raw.githubusercontent.com/MinnPost/simple-map-d3/master/example-data/world-population.geo.json"
geoJson <- jsonlite::fromJSON(readr::read_file(fName))
# The geojson in question has some invalid geometry which needs to be fixed
# before we can use it in a custom projection.
geoJson <- geojsonio::as.json(geoJson) %>%
rmapshaper::ms_simplify()
leaf.world <- leaflet(
options = leafletOptions(
maxZoom = 5,
crs = leafletCRS(
crsClass = "L.Proj.CRS", code = "ESRI:53009",
proj4def = "+proj=moll +lon_0=0 +x_0=0 +y_0=0 +a=6371000 +b=6371000 +units=m +no_defs",
resolutions = c(65536, 32768, 16384, 8192, 4096, 2048)))) %>%
addGraticule(style = list(color = "#999", weight = 0.5, opacity = 1, fill = NA)) %>%
addGraticule(sphere = TRUE, style = list(color = "#777", weight = 1, opacity = 0.25, fill = NA)) %>%
addEasyButton(easyButton(
icon = "ion-arrow-shrink",
title = "Reset View",
onClick = JS("function(btn, map){ map.setView([0,0],1); }"))) %>%
setMapWidgetStyle(list(background = "white"))
#' The options `valueProperty`, `scale`, `mode`, `steps` are for the choropleth generation.
#' `valueProperty` can be a simple property or a JS function that computes a value as shown below.<br/>
#' In addition you can specify `labelProperty` & `popupProperty` both of which can be simple property names or functions that generate string/HTML.
leaf.world %>%
addBootstrapDependency() %>%
addGeoJSONChoropleth(
geoJson, group = "pop_density",
# Calculate the Population Density of each country
valueProperty =
JS("function(feature) {
return feature.properties.POP2005/Math.max(feature.properties.AREA,1);
}"),
scale = c("#ffc77fff", "#000000ff"), mode = "q", steps = 5,
# Select the data attributes to show in the popup.
popupProperty = propstoHTMLTable(
props = c("NAME", "REGION", "ISO_3_CODE", "ISO_2_CODE", "AREA", "POP2005"),
table.attrs = list(class = "table table-striped table-bordered"), drop.na = T),
labelProperty = "NAME",
color = "#ffffff", weight = 1, fillOpacity = 0.9,
highlightOptions = highlightOptions(
fillOpacity = 1, weight = 2, opacity = 1, color = "#ff0000",
bringToFront = TRUE, sendToBack = TRUE),
legendOptions = legendOptions(title = "Population Density (2005)")) %>%
addSearchFeatures(
targetGroups = "pop_density",
options = searchFeaturesOptions(
propertyName = "NAME", zoom = 2, openPopup = TRUE, firstTipSubmit = TRUE,
autoCollapse = FALSE, hideMarkerOnCollapse = TRUE )) %>%
addControl("<P><B>Hint!</B> Search for a Country by name</P>",
position = "bottomright")
# Example 3 - Arts and culutre
# GeoJSON Groups w/ Markers ----
artsAndCultures <- readr::read_file(
"https://rawgit.com/benbalter/dc-maps/master/maps/arts-and-culture-organizations-as-501-c-3.geojson")
bankLocations <- readr::read_file(
"https://raw.githubusercontent.com/benbalter/dc-maps/master/maps/bank-locations.geojson")
artsAndCulture <- makeAwesomeIcon(icon = "paintbrush", library = "ion", markerColor = "red", iconColor = "black")
bankLocation <- makeAwesomeIcon(icon = "cash", library = "ion", markerColor = "green", iconColor = "black")
leaf <- leaflet() %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addResetMapButton()
leaf %>% setView(-77.0369, 38.9072, 12) %>%
addBootstrapDependency() %>%
addGeoJSONv2(
artsAndCultures,
labelProperty = "NAME",
popupProperty = propstoHTMLTable(
table.attrs = list(class = "table table-striped table-bordered"), drop.na = T),
labelOptions = labelOptions(textsize = "12px", direction = "auto" ),
markerIcons = artsAndCulture,
markerOptions = markerOptions(riseOnHover = TRUE, opacity = 1),
clusterOptions = markerClusterOptions(), group = "Arts-n-Culture") %>%
addGeoJSONv2(
bankLocations,
labelProperty = "NAME",
popupProperty = propstoHTMLTable(
table.attrs = list(class = "table table-striped table-bordered"), drop.na = T),
labelOptions = labelOptions(textsize = "12px", direction = "auto" ),
markerIcons = bankLocation,
markerOptions = markerOptions(riseOnHover = TRUE, opacity = 1),
clusterOptions = markerClusterOptions(), group = "Bank Locations") %>%
addLayersControl(
overlayGroups = c("Arts-n-Culture", "Bank Locations"),
options = layersControlOptions(collapsed = F)) %>%
addSearchFeatures(
targetGroups = c("Arts-n-Culture", "Bank Locations"),
options = searchFeaturesOptions(
propertyName = "NAME", zoom = 18, openPopup = TRUE, firstTipSubmit = TRUE,
autoCollapse = TRUE, hideMarkerOnCollapse = TRUE, position = "topleft" )) %>%
addControl("<P><B>Hint!</B> Search for Arts-N-Culture or Bank Locations</P>",
position = "bottomright")
Suspends map scrolling. This helps when embedding leaflet in HTML pages using R Markdown, Bookdown, blogdown or in HTML presentations. The map will not scroll unless you hover/click it. This prevents unintentional map scrolling when scrolling the document.
leaflet(width = "100%") %>% setView(0, 0, 1) %>%
addTiles() %>%
suspendScroll()
The plugin displays any image URI you pass it on initialisation. However that is enough to create a nice looking legend.
Go to this link.
Check the map below:
leaflet(
options = leafletOptions(
center = c(-33.95293, 20.82824),
zoom = 14,
minZoom = 5,
maxZoom = 18,
maxBounds = list(
c(-33.91444, 20.75351),
c(-33.98731, 20.90626)
)
)
) %>%
#addTiles() %>%
addWMSTiles(baseUrl = "http://maps.kartoza.com/web/?map=/web/Boosmansbos/Boosmansbos.qgs",
layers = "Boosmansbos",
options = WMSTileOptions(format = "image/png", transparent = TRUE),
attribution = "(c)<a href=\"http://kartoza.com\">Kartoza.com</a> and <a href=\"http://www.ngi.gov.za/\">SA-NGI</a>") %>%
addWMSLegend(uri = "http://maps.kartoza.com/web/?map=/web/Boosmansbos/Boosmansbos.qgs&&SERVICE=WMS&VERSION=1.3.0&SLD_VERSION=1.1.0&REQUEST=GetLegendGraphic&FORMAT=image/jpeg&LAYER=Boosmansbos&STYLE=")